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 display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   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 code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132};
  133
  134pub use git::blame::BlameRenderer;
  135pub use proposed_changes_editor::{
  136    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  137};
  138use smallvec::smallvec;
  139use std::{cell::OnceCell, iter::Peekable};
  140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  141
  142pub use lsp::CompletionContext;
  143use lsp::{
  144    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  145    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  146};
  147
  148use language::BufferSnapshot;
  149pub use lsp_ext::lsp_tasks;
  150use movement::TextLayoutDetails;
  151pub use multi_buffer::{
  152    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  153    RowInfo, ToOffset, ToPoint,
  154};
  155use multi_buffer::{
  156    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  157    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  158};
  159use parking_lot::Mutex;
  160use project::{
  161    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  162    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  163    TaskSourceKind,
  164    debugger::breakpoint_store::Breakpoint,
  165    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  166    project_settings::{GitGutterSetting, ProjectSettings},
  167};
  168use rand::prelude::*;
  169use rpc::{ErrorExt, proto::*};
  170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  171use selections_collection::{
  172    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  173};
  174use serde::{Deserialize, Serialize};
  175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  176use smallvec::SmallVec;
  177use snippet::Snippet;
  178use std::sync::Arc;
  179use std::{
  180    any::TypeId,
  181    borrow::Cow,
  182    cell::RefCell,
  183    cmp::{self, Ordering, Reverse},
  184    mem,
  185    num::NonZeroU32,
  186    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  187    path::{Path, PathBuf},
  188    rc::Rc,
  189    time::{Duration, Instant},
  190};
  191pub use sum_tree::Bias;
  192use sum_tree::TreeMap;
  193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  194use theme::{
  195    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  196    observe_buffer_font_size_adjustment,
  197};
  198use ui::{
  199    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  200    IconSize, Key, Tooltip, h_flex, prelude::*,
  201};
  202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  203use workspace::{
  204    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  205    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  206    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  207    item::{ItemHandle, PreviewTabsSettings},
  208    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  209    searchable::SearchEvent,
  210};
  211
  212use crate::hover_links::{find_url, find_url_from_range};
  213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  214
  215pub const FILE_HEADER_HEIGHT: u32 = 2;
  216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  219const MAX_LINE_LEN: usize = 1024;
  220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  223#[doc(hidden)]
  224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  226
  227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  230
  231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  234
  235pub type RenderDiffHunkControlsFn = Arc<
  236    dyn Fn(
  237        u32,
  238        &DiffHunkStatus,
  239        Range<Anchor>,
  240        bool,
  241        Pixels,
  242        &Entity<Editor>,
  243        &mut Window,
  244        &mut App,
  245    ) -> AnyElement,
  246>;
  247
  248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  249    alt: true,
  250    shift: true,
  251    control: false,
  252    platform: false,
  253    function: false,
  254};
  255
  256struct InlineValueCache {
  257    enabled: bool,
  258    inlays: Vec<InlayId>,
  259    refresh_task: Task<Option<()>>,
  260}
  261
  262impl InlineValueCache {
  263    fn new(enabled: bool) -> Self {
  264        Self {
  265            enabled,
  266            inlays: Vec::new(),
  267            refresh_task: Task::ready(None),
  268        }
  269    }
  270}
  271
  272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  273pub enum InlayId {
  274    InlineCompletion(usize),
  275    Hint(usize),
  276    DebuggerValue(usize),
  277}
  278
  279impl InlayId {
  280    fn id(&self) -> usize {
  281        match self {
  282            Self::InlineCompletion(id) => *id,
  283            Self::Hint(id) => *id,
  284            Self::DebuggerValue(id) => *id,
  285        }
  286    }
  287}
  288
  289pub enum ActiveDebugLine {}
  290enum DocumentHighlightRead {}
  291enum DocumentHighlightWrite {}
  292enum InputComposition {}
  293enum SelectedTextHighlight {}
  294
  295pub enum ConflictsOuter {}
  296pub enum ConflictsOurs {}
  297pub enum ConflictsTheirs {}
  298pub enum ConflictsOursMarker {}
  299pub enum ConflictsTheirsMarker {}
  300
  301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  302pub enum Navigated {
  303    Yes,
  304    No,
  305}
  306
  307impl Navigated {
  308    pub fn from_bool(yes: bool) -> Navigated {
  309        if yes { Navigated::Yes } else { Navigated::No }
  310    }
  311}
  312
  313#[derive(Debug, Clone, PartialEq, Eq)]
  314enum DisplayDiffHunk {
  315    Folded {
  316        display_row: DisplayRow,
  317    },
  318    Unfolded {
  319        is_created_file: bool,
  320        diff_base_byte_range: Range<usize>,
  321        display_row_range: Range<DisplayRow>,
  322        multi_buffer_range: Range<Anchor>,
  323        status: DiffHunkStatus,
  324    },
  325}
  326
  327pub enum HideMouseCursorOrigin {
  328    TypingAction,
  329    MovementAction,
  330}
  331
  332pub fn init_settings(cx: &mut App) {
  333    EditorSettings::register(cx);
  334}
  335
  336pub fn init(cx: &mut App) {
  337    init_settings(cx);
  338
  339    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  340
  341    workspace::register_project_item::<Editor>(cx);
  342    workspace::FollowableViewRegistry::register::<Editor>(cx);
  343    workspace::register_serializable_item::<Editor>(cx);
  344
  345    cx.observe_new(
  346        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  347            workspace.register_action(Editor::new_file);
  348            workspace.register_action(Editor::new_file_vertical);
  349            workspace.register_action(Editor::new_file_horizontal);
  350            workspace.register_action(Editor::cancel_language_server_work);
  351        },
  352    )
  353    .detach();
  354
  355    cx.on_action(move |_: &workspace::NewFile, cx| {
  356        let app_state = workspace::AppState::global(cx);
  357        if let Some(app_state) = app_state.upgrade() {
  358            workspace::open_new(
  359                Default::default(),
  360                app_state,
  361                cx,
  362                |workspace, window, cx| {
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369    cx.on_action(move |_: &workspace::NewWindow, cx| {
  370        let app_state = workspace::AppState::global(cx);
  371        if let Some(app_state) = app_state.upgrade() {
  372            workspace::open_new(
  373                Default::default(),
  374                app_state,
  375                cx,
  376                |workspace, window, cx| {
  377                    cx.activate(true);
  378                    Editor::new_file(workspace, &Default::default(), window, cx)
  379                },
  380            )
  381            .detach();
  382        }
  383    });
  384}
  385
  386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  387    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  388}
  389
  390pub trait DiagnosticRenderer {
  391    fn render_group(
  392        &self,
  393        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  394        buffer_id: BufferId,
  395        snapshot: EditorSnapshot,
  396        editor: WeakEntity<Editor>,
  397        cx: &mut App,
  398    ) -> Vec<BlockProperties<Anchor>>;
  399
  400    fn render_hover(
  401        &self,
  402        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  403        range: Range<Point>,
  404        buffer_id: BufferId,
  405        cx: &mut App,
  406    ) -> Option<Entity<markdown::Markdown>>;
  407
  408    fn open_link(
  409        &self,
  410        editor: &mut Editor,
  411        link: SharedString,
  412        window: &mut Window,
  413        cx: &mut Context<Editor>,
  414    );
  415}
  416
  417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  418
  419impl GlobalDiagnosticRenderer {
  420    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  421        cx.try_global::<Self>().map(|g| g.0.clone())
  422    }
  423}
  424
  425impl gpui::Global for GlobalDiagnosticRenderer {}
  426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  427    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  428}
  429
  430pub struct SearchWithinRange;
  431
  432trait InvalidationRegion {
  433    fn ranges(&self) -> &[Range<Anchor>];
  434}
  435
  436#[derive(Clone, Debug, PartialEq)]
  437pub enum SelectPhase {
  438    Begin {
  439        position: DisplayPoint,
  440        add: bool,
  441        click_count: usize,
  442    },
  443    BeginColumnar {
  444        position: DisplayPoint,
  445        reset: bool,
  446        goal_column: u32,
  447    },
  448    Extend {
  449        position: DisplayPoint,
  450        click_count: usize,
  451    },
  452    Update {
  453        position: DisplayPoint,
  454        goal_column: u32,
  455        scroll_delta: gpui::Point<f32>,
  456    },
  457    End,
  458}
  459
  460#[derive(Clone, Debug)]
  461pub enum SelectMode {
  462    Character,
  463    Word(Range<Anchor>),
  464    Line(Range<Anchor>),
  465    All,
  466}
  467
  468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  469pub enum EditorMode {
  470    SingleLine {
  471        auto_width: bool,
  472    },
  473    AutoHeight {
  474        max_lines: usize,
  475    },
  476    Full {
  477        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  478        scale_ui_elements_with_buffer_font_size: bool,
  479        /// When set to `true`, the editor will render a background for the active line.
  480        show_active_line_background: bool,
  481        /// When set to `true`, the editor's height will be determined by its content.
  482        sized_by_content: bool,
  483    },
  484}
  485
  486impl EditorMode {
  487    pub fn full() -> Self {
  488        Self::Full {
  489            scale_ui_elements_with_buffer_font_size: true,
  490            show_active_line_background: true,
  491            sized_by_content: false,
  492        }
  493    }
  494
  495    pub fn is_full(&self) -> bool {
  496        matches!(self, Self::Full { .. })
  497    }
  498}
  499
  500#[derive(Copy, Clone, Debug)]
  501pub enum SoftWrap {
  502    /// Prefer not to wrap at all.
  503    ///
  504    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  505    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  506    GitDiff,
  507    /// Prefer a single line generally, unless an overly long line is encountered.
  508    None,
  509    /// Soft wrap lines that exceed the editor width.
  510    EditorWidth,
  511    /// Soft wrap lines at the preferred line length.
  512    Column(u32),
  513    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  514    Bounded(u32),
  515}
  516
  517#[derive(Clone)]
  518pub struct EditorStyle {
  519    pub background: Hsla,
  520    pub horizontal_padding: Pixels,
  521    pub local_player: PlayerColor,
  522    pub text: TextStyle,
  523    pub scrollbar_width: Pixels,
  524    pub syntax: Arc<SyntaxTheme>,
  525    pub status: StatusColors,
  526    pub inlay_hints_style: HighlightStyle,
  527    pub inline_completion_styles: InlineCompletionStyles,
  528    pub unnecessary_code_fade: f32,
  529}
  530
  531impl Default for EditorStyle {
  532    fn default() -> Self {
  533        Self {
  534            background: Hsla::default(),
  535            horizontal_padding: Pixels::default(),
  536            local_player: PlayerColor::default(),
  537            text: TextStyle::default(),
  538            scrollbar_width: Pixels::default(),
  539            syntax: Default::default(),
  540            // HACK: Status colors don't have a real default.
  541            // We should look into removing the status colors from the editor
  542            // style and retrieve them directly from the theme.
  543            status: StatusColors::dark(),
  544            inlay_hints_style: HighlightStyle::default(),
  545            inline_completion_styles: InlineCompletionStyles {
  546                insertion: HighlightStyle::default(),
  547                whitespace: HighlightStyle::default(),
  548            },
  549            unnecessary_code_fade: Default::default(),
  550        }
  551    }
  552}
  553
  554pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  555    let show_background = language_settings::language_settings(None, None, cx)
  556        .inlay_hints
  557        .show_background;
  558
  559    HighlightStyle {
  560        color: Some(cx.theme().status().hint),
  561        background_color: show_background.then(|| cx.theme().status().hint_background),
  562        ..HighlightStyle::default()
  563    }
  564}
  565
  566pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  567    InlineCompletionStyles {
  568        insertion: HighlightStyle {
  569            color: Some(cx.theme().status().predictive),
  570            ..HighlightStyle::default()
  571        },
  572        whitespace: HighlightStyle {
  573            background_color: Some(cx.theme().status().created_background),
  574            ..HighlightStyle::default()
  575        },
  576    }
  577}
  578
  579type CompletionId = usize;
  580
  581pub(crate) enum EditDisplayMode {
  582    TabAccept,
  583    DiffPopover,
  584    Inline,
  585}
  586
  587enum InlineCompletion {
  588    Edit {
  589        edits: Vec<(Range<Anchor>, String)>,
  590        edit_preview: Option<EditPreview>,
  591        display_mode: EditDisplayMode,
  592        snapshot: BufferSnapshot,
  593    },
  594    Move {
  595        target: Anchor,
  596        snapshot: BufferSnapshot,
  597    },
  598}
  599
  600struct InlineCompletionState {
  601    inlay_ids: Vec<InlayId>,
  602    completion: InlineCompletion,
  603    completion_id: Option<SharedString>,
  604    invalidation_range: Range<Anchor>,
  605}
  606
  607enum EditPredictionSettings {
  608    Disabled,
  609    Enabled {
  610        show_in_menu: bool,
  611        preview_requires_modifier: bool,
  612    },
  613}
  614
  615enum InlineCompletionHighlight {}
  616
  617#[derive(Debug, Clone)]
  618struct InlineDiagnostic {
  619    message: SharedString,
  620    group_id: usize,
  621    is_primary: bool,
  622    start: Point,
  623    severity: DiagnosticSeverity,
  624}
  625
  626pub enum MenuInlineCompletionsPolicy {
  627    Never,
  628    ByProvider,
  629}
  630
  631pub enum EditPredictionPreview {
  632    /// Modifier is not pressed
  633    Inactive { released_too_fast: bool },
  634    /// Modifier pressed
  635    Active {
  636        since: Instant,
  637        previous_scroll_position: Option<ScrollAnchor>,
  638    },
  639}
  640
  641impl EditPredictionPreview {
  642    pub fn released_too_fast(&self) -> bool {
  643        match self {
  644            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  645            EditPredictionPreview::Active { .. } => false,
  646        }
  647    }
  648
  649    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  650        if let EditPredictionPreview::Active {
  651            previous_scroll_position,
  652            ..
  653        } = self
  654        {
  655            *previous_scroll_position = scroll_position;
  656        }
  657    }
  658}
  659
  660pub struct ContextMenuOptions {
  661    pub min_entries_visible: usize,
  662    pub max_entries_visible: usize,
  663    pub placement: Option<ContextMenuPlacement>,
  664}
  665
  666#[derive(Debug, Clone, PartialEq, Eq)]
  667pub enum ContextMenuPlacement {
  668    Above,
  669    Below,
  670}
  671
  672#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  673struct EditorActionId(usize);
  674
  675impl EditorActionId {
  676    pub fn post_inc(&mut self) -> Self {
  677        let answer = self.0;
  678
  679        *self = Self(answer + 1);
  680
  681        Self(answer)
  682    }
  683}
  684
  685// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  686// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  687
  688type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  689type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  690
  691#[derive(Default)]
  692struct ScrollbarMarkerState {
  693    scrollbar_size: Size<Pixels>,
  694    dirty: bool,
  695    markers: Arc<[PaintQuad]>,
  696    pending_refresh: Option<Task<Result<()>>>,
  697}
  698
  699impl ScrollbarMarkerState {
  700    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  701        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  702    }
  703}
  704
  705#[derive(Clone, Debug)]
  706struct RunnableTasks {
  707    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  708    offset: multi_buffer::Anchor,
  709    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  710    column: u32,
  711    // Values of all named captures, including those starting with '_'
  712    extra_variables: HashMap<String, String>,
  713    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  714    context_range: Range<BufferOffset>,
  715}
  716
  717impl RunnableTasks {
  718    fn resolve<'a>(
  719        &'a self,
  720        cx: &'a task::TaskContext,
  721    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  722        self.templates.iter().filter_map(|(kind, template)| {
  723            template
  724                .resolve_task(&kind.to_id_base(), cx)
  725                .map(|task| (kind.clone(), task))
  726        })
  727    }
  728}
  729
  730#[derive(Clone)]
  731struct ResolvedTasks {
  732    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  733    position: Anchor,
  734}
  735
  736#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  737struct BufferOffset(usize);
  738
  739// Addons allow storing per-editor state in other crates (e.g. Vim)
  740pub trait Addon: 'static {
  741    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  742
  743    fn render_buffer_header_controls(
  744        &self,
  745        _: &ExcerptInfo,
  746        _: &Window,
  747        _: &App,
  748    ) -> Option<AnyElement> {
  749        None
  750    }
  751
  752    fn to_any(&self) -> &dyn std::any::Any;
  753
  754    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  755        None
  756    }
  757}
  758
  759/// A set of caret positions, registered when the editor was edited.
  760pub struct ChangeList {
  761    changes: Vec<Vec<Anchor>>,
  762    /// Currently "selected" change.
  763    position: Option<usize>,
  764}
  765
  766impl ChangeList {
  767    pub fn new() -> Self {
  768        Self {
  769            changes: Vec::new(),
  770            position: None,
  771        }
  772    }
  773
  774    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  775    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  776    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  777        if self.changes.is_empty() {
  778            return None;
  779        }
  780
  781        let prev = self.position.unwrap_or(self.changes.len());
  782        let next = if direction == Direction::Prev {
  783            prev.saturating_sub(count)
  784        } else {
  785            (prev + count).min(self.changes.len() - 1)
  786        };
  787        self.position = Some(next);
  788        self.changes.get(next).map(|anchors| anchors.as_slice())
  789    }
  790
  791    /// Adds a new change to the list, resetting the change list position.
  792    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  793        self.position.take();
  794        if pop_state {
  795            self.changes.pop();
  796        }
  797        self.changes.push(new_positions.clone());
  798    }
  799
  800    pub fn last(&self) -> Option<&[Anchor]> {
  801        self.changes.last().map(|anchors| anchors.as_slice())
  802    }
  803}
  804
  805#[derive(Clone)]
  806struct InlineBlamePopoverState {
  807    scroll_handle: ScrollHandle,
  808    commit_message: Option<ParsedCommitMessage>,
  809    markdown: Entity<Markdown>,
  810}
  811
  812struct InlineBlamePopover {
  813    position: gpui::Point<Pixels>,
  814    show_task: Option<Task<()>>,
  815    hide_task: Option<Task<()>>,
  816    popover_bounds: Option<Bounds<Pixels>>,
  817    popover_state: InlineBlamePopoverState,
  818}
  819
  820/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  821/// a breakpoint on them.
  822#[derive(Clone, Copy, Debug)]
  823struct PhantomBreakpointIndicator {
  824    display_row: DisplayRow,
  825    /// There's a small debounce between hovering over the line and showing the indicator.
  826    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  827    is_active: bool,
  828    collides_with_existing_breakpoint: bool,
  829}
  830/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  831///
  832/// See the [module level documentation](self) for more information.
  833pub struct Editor {
  834    focus_handle: FocusHandle,
  835    last_focused_descendant: Option<WeakFocusHandle>,
  836    /// The text buffer being edited
  837    buffer: Entity<MultiBuffer>,
  838    /// Map of how text in the buffer should be displayed.
  839    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  840    pub display_map: Entity<DisplayMap>,
  841    pub selections: SelectionsCollection,
  842    pub scroll_manager: ScrollManager,
  843    /// When inline assist editors are linked, they all render cursors because
  844    /// typing enters text into each of them, even the ones that aren't focused.
  845    pub(crate) show_cursor_when_unfocused: bool,
  846    columnar_selection_tail: Option<Anchor>,
  847    add_selections_state: Option<AddSelectionsState>,
  848    select_next_state: Option<SelectNextState>,
  849    select_prev_state: Option<SelectNextState>,
  850    selection_history: SelectionHistory,
  851    autoclose_regions: Vec<AutocloseRegion>,
  852    snippet_stack: InvalidationStack<SnippetState>,
  853    select_syntax_node_history: SelectSyntaxNodeHistory,
  854    ime_transaction: Option<TransactionId>,
  855    active_diagnostics: ActiveDiagnostic,
  856    show_inline_diagnostics: bool,
  857    inline_diagnostics_update: Task<()>,
  858    inline_diagnostics_enabled: bool,
  859    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  860    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  861    hard_wrap: Option<usize>,
  862
  863    // TODO: make this a access method
  864    pub project: Option<Entity<Project>>,
  865    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  866    completion_provider: Option<Box<dyn CompletionProvider>>,
  867    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  868    blink_manager: Entity<BlinkManager>,
  869    show_cursor_names: bool,
  870    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  871    pub show_local_selections: bool,
  872    mode: EditorMode,
  873    show_breadcrumbs: bool,
  874    show_gutter: bool,
  875    show_scrollbars: bool,
  876    disable_expand_excerpt_buttons: bool,
  877    show_line_numbers: Option<bool>,
  878    use_relative_line_numbers: Option<bool>,
  879    show_git_diff_gutter: Option<bool>,
  880    show_code_actions: Option<bool>,
  881    show_runnables: Option<bool>,
  882    show_breakpoints: Option<bool>,
  883    show_wrap_guides: Option<bool>,
  884    show_indent_guides: Option<bool>,
  885    placeholder_text: Option<Arc<str>>,
  886    highlight_order: usize,
  887    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  888    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  889    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  890    scrollbar_marker_state: ScrollbarMarkerState,
  891    active_indent_guides_state: ActiveIndentGuidesState,
  892    nav_history: Option<ItemNavHistory>,
  893    context_menu: RefCell<Option<CodeContextMenu>>,
  894    context_menu_options: Option<ContextMenuOptions>,
  895    mouse_context_menu: Option<MouseContextMenu>,
  896    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  897    inline_blame_popover: Option<InlineBlamePopover>,
  898    signature_help_state: SignatureHelpState,
  899    auto_signature_help: Option<bool>,
  900    find_all_references_task_sources: Vec<Anchor>,
  901    next_completion_id: CompletionId,
  902    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  903    code_actions_task: Option<Task<Result<()>>>,
  904    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  905    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  906    document_highlights_task: Option<Task<()>>,
  907    linked_editing_range_task: Option<Task<Option<()>>>,
  908    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  909    pending_rename: Option<RenameState>,
  910    searchable: bool,
  911    cursor_shape: CursorShape,
  912    current_line_highlight: Option<CurrentLineHighlight>,
  913    collapse_matches: bool,
  914    autoindent_mode: Option<AutoindentMode>,
  915    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  916    input_enabled: bool,
  917    use_modal_editing: bool,
  918    read_only: bool,
  919    leader_id: Option<CollaboratorId>,
  920    remote_id: Option<ViewId>,
  921    pub hover_state: HoverState,
  922    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  923    gutter_hovered: bool,
  924    hovered_link_state: Option<HoveredLinkState>,
  925    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  926    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  927    active_inline_completion: Option<InlineCompletionState>,
  928    /// Used to prevent flickering as the user types while the menu is open
  929    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  930    edit_prediction_settings: EditPredictionSettings,
  931    inline_completions_hidden_for_vim_mode: bool,
  932    show_inline_completions_override: Option<bool>,
  933    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  934    edit_prediction_preview: EditPredictionPreview,
  935    edit_prediction_indent_conflict: bool,
  936    edit_prediction_requires_modifier_in_indent_conflict: bool,
  937    inlay_hint_cache: InlayHintCache,
  938    next_inlay_id: usize,
  939    _subscriptions: Vec<Subscription>,
  940    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  941    gutter_dimensions: GutterDimensions,
  942    style: Option<EditorStyle>,
  943    text_style_refinement: Option<TextStyleRefinement>,
  944    next_editor_action_id: EditorActionId,
  945    editor_actions:
  946        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  947    use_autoclose: bool,
  948    use_auto_surround: bool,
  949    auto_replace_emoji_shortcode: bool,
  950    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  951    show_git_blame_gutter: bool,
  952    show_git_blame_inline: bool,
  953    show_git_blame_inline_delay_task: Option<Task<()>>,
  954    git_blame_inline_enabled: bool,
  955    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  956    serialize_dirty_buffers: bool,
  957    show_selection_menu: Option<bool>,
  958    blame: Option<Entity<GitBlame>>,
  959    blame_subscription: Option<Subscription>,
  960    custom_context_menu: Option<
  961        Box<
  962            dyn 'static
  963                + Fn(
  964                    &mut Self,
  965                    DisplayPoint,
  966                    &mut Window,
  967                    &mut Context<Self>,
  968                ) -> Option<Entity<ui::ContextMenu>>,
  969        >,
  970    >,
  971    last_bounds: Option<Bounds<Pixels>>,
  972    last_position_map: Option<Rc<PositionMap>>,
  973    expect_bounds_change: Option<Bounds<Pixels>>,
  974    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  975    tasks_update_task: Option<Task<()>>,
  976    breakpoint_store: Option<Entity<BreakpointStore>>,
  977    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
  978    in_project_search: bool,
  979    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  980    breadcrumb_header: Option<String>,
  981    focused_block: Option<FocusedBlock>,
  982    next_scroll_position: NextScrollCursorCenterTopBottom,
  983    addons: HashMap<TypeId, Box<dyn Addon>>,
  984    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  985    load_diff_task: Option<Shared<Task<()>>>,
  986    /// Whether we are temporarily displaying a diff other than git's
  987    temporary_diff_override: bool,
  988    selection_mark_mode: bool,
  989    toggle_fold_multiple_buffers: Task<()>,
  990    _scroll_cursor_center_top_bottom_task: Task<()>,
  991    serialize_selections: Task<()>,
  992    serialize_folds: Task<()>,
  993    mouse_cursor_hidden: bool,
  994    hide_mouse_mode: HideMouseMode,
  995    pub change_list: ChangeList,
  996    inline_value_cache: InlineValueCache,
  997}
  998
  999#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
 1000enum NextScrollCursorCenterTopBottom {
 1001    #[default]
 1002    Center,
 1003    Top,
 1004    Bottom,
 1005}
 1006
 1007impl NextScrollCursorCenterTopBottom {
 1008    fn next(&self) -> Self {
 1009        match self {
 1010            Self::Center => Self::Top,
 1011            Self::Top => Self::Bottom,
 1012            Self::Bottom => Self::Center,
 1013        }
 1014    }
 1015}
 1016
 1017#[derive(Clone)]
 1018pub struct EditorSnapshot {
 1019    pub mode: EditorMode,
 1020    show_gutter: bool,
 1021    show_line_numbers: Option<bool>,
 1022    show_git_diff_gutter: Option<bool>,
 1023    show_runnables: Option<bool>,
 1024    show_breakpoints: Option<bool>,
 1025    git_blame_gutter_max_author_length: Option<usize>,
 1026    pub display_snapshot: DisplaySnapshot,
 1027    pub placeholder_text: Option<Arc<str>>,
 1028    is_focused: bool,
 1029    scroll_anchor: ScrollAnchor,
 1030    ongoing_scroll: OngoingScroll,
 1031    current_line_highlight: CurrentLineHighlight,
 1032    gutter_hovered: bool,
 1033}
 1034
 1035#[derive(Default, Debug, Clone, Copy)]
 1036pub struct GutterDimensions {
 1037    pub left_padding: Pixels,
 1038    pub right_padding: Pixels,
 1039    pub width: Pixels,
 1040    pub margin: Pixels,
 1041    pub git_blame_entries_width: Option<Pixels>,
 1042}
 1043
 1044impl GutterDimensions {
 1045    /// The full width of the space taken up by the gutter.
 1046    pub fn full_width(&self) -> Pixels {
 1047        self.margin + self.width
 1048    }
 1049
 1050    /// The width of the space reserved for the fold indicators,
 1051    /// use alongside 'justify_end' and `gutter_width` to
 1052    /// right align content with the line numbers
 1053    pub fn fold_area_width(&self) -> Pixels {
 1054        self.margin + self.right_padding
 1055    }
 1056}
 1057
 1058#[derive(Debug)]
 1059pub struct RemoteSelection {
 1060    pub replica_id: ReplicaId,
 1061    pub selection: Selection<Anchor>,
 1062    pub cursor_shape: CursorShape,
 1063    pub collaborator_id: CollaboratorId,
 1064    pub line_mode: bool,
 1065    pub user_name: Option<SharedString>,
 1066    pub color: PlayerColor,
 1067}
 1068
 1069#[derive(Clone, Debug)]
 1070struct SelectionHistoryEntry {
 1071    selections: Arc<[Selection<Anchor>]>,
 1072    select_next_state: Option<SelectNextState>,
 1073    select_prev_state: Option<SelectNextState>,
 1074    add_selections_state: Option<AddSelectionsState>,
 1075}
 1076
 1077enum SelectionHistoryMode {
 1078    Normal,
 1079    Undoing,
 1080    Redoing,
 1081}
 1082
 1083#[derive(Clone, PartialEq, Eq, Hash)]
 1084struct HoveredCursor {
 1085    replica_id: u16,
 1086    selection_id: usize,
 1087}
 1088
 1089impl Default for SelectionHistoryMode {
 1090    fn default() -> Self {
 1091        Self::Normal
 1092    }
 1093}
 1094
 1095#[derive(Default)]
 1096struct SelectionHistory {
 1097    #[allow(clippy::type_complexity)]
 1098    selections_by_transaction:
 1099        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1100    mode: SelectionHistoryMode,
 1101    undo_stack: VecDeque<SelectionHistoryEntry>,
 1102    redo_stack: VecDeque<SelectionHistoryEntry>,
 1103}
 1104
 1105impl SelectionHistory {
 1106    fn insert_transaction(
 1107        &mut self,
 1108        transaction_id: TransactionId,
 1109        selections: Arc<[Selection<Anchor>]>,
 1110    ) {
 1111        self.selections_by_transaction
 1112            .insert(transaction_id, (selections, None));
 1113    }
 1114
 1115    #[allow(clippy::type_complexity)]
 1116    fn transaction(
 1117        &self,
 1118        transaction_id: TransactionId,
 1119    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1120        self.selections_by_transaction.get(&transaction_id)
 1121    }
 1122
 1123    #[allow(clippy::type_complexity)]
 1124    fn transaction_mut(
 1125        &mut self,
 1126        transaction_id: TransactionId,
 1127    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1128        self.selections_by_transaction.get_mut(&transaction_id)
 1129    }
 1130
 1131    fn push(&mut self, entry: SelectionHistoryEntry) {
 1132        if !entry.selections.is_empty() {
 1133            match self.mode {
 1134                SelectionHistoryMode::Normal => {
 1135                    self.push_undo(entry);
 1136                    self.redo_stack.clear();
 1137                }
 1138                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1139                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1140            }
 1141        }
 1142    }
 1143
 1144    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1145        if self
 1146            .undo_stack
 1147            .back()
 1148            .map_or(true, |e| e.selections != entry.selections)
 1149        {
 1150            self.undo_stack.push_back(entry);
 1151            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1152                self.undo_stack.pop_front();
 1153            }
 1154        }
 1155    }
 1156
 1157    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1158        if self
 1159            .redo_stack
 1160            .back()
 1161            .map_or(true, |e| e.selections != entry.selections)
 1162        {
 1163            self.redo_stack.push_back(entry);
 1164            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1165                self.redo_stack.pop_front();
 1166            }
 1167        }
 1168    }
 1169}
 1170
 1171#[derive(Clone, Copy)]
 1172pub struct RowHighlightOptions {
 1173    pub autoscroll: bool,
 1174    pub include_gutter: bool,
 1175}
 1176
 1177impl Default for RowHighlightOptions {
 1178    fn default() -> Self {
 1179        Self {
 1180            autoscroll: Default::default(),
 1181            include_gutter: true,
 1182        }
 1183    }
 1184}
 1185
 1186struct RowHighlight {
 1187    index: usize,
 1188    range: Range<Anchor>,
 1189    color: Hsla,
 1190    options: RowHighlightOptions,
 1191    type_id: TypeId,
 1192}
 1193
 1194#[derive(Clone, Debug)]
 1195struct AddSelectionsState {
 1196    above: bool,
 1197    stack: Vec<usize>,
 1198}
 1199
 1200#[derive(Clone)]
 1201struct SelectNextState {
 1202    query: AhoCorasick,
 1203    wordwise: bool,
 1204    done: bool,
 1205}
 1206
 1207impl std::fmt::Debug for SelectNextState {
 1208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1209        f.debug_struct(std::any::type_name::<Self>())
 1210            .field("wordwise", &self.wordwise)
 1211            .field("done", &self.done)
 1212            .finish()
 1213    }
 1214}
 1215
 1216#[derive(Debug)]
 1217struct AutocloseRegion {
 1218    selection_id: usize,
 1219    range: Range<Anchor>,
 1220    pair: BracketPair,
 1221}
 1222
 1223#[derive(Debug)]
 1224struct SnippetState {
 1225    ranges: Vec<Vec<Range<Anchor>>>,
 1226    active_index: usize,
 1227    choices: Vec<Option<Vec<String>>>,
 1228}
 1229
 1230#[doc(hidden)]
 1231pub struct RenameState {
 1232    pub range: Range<Anchor>,
 1233    pub old_name: Arc<str>,
 1234    pub editor: Entity<Editor>,
 1235    block_id: CustomBlockId,
 1236}
 1237
 1238struct InvalidationStack<T>(Vec<T>);
 1239
 1240struct RegisteredInlineCompletionProvider {
 1241    provider: Arc<dyn InlineCompletionProviderHandle>,
 1242    _subscription: Subscription,
 1243}
 1244
 1245#[derive(Debug, PartialEq, Eq)]
 1246pub struct ActiveDiagnosticGroup {
 1247    pub active_range: Range<Anchor>,
 1248    pub active_message: String,
 1249    pub group_id: usize,
 1250    pub blocks: HashSet<CustomBlockId>,
 1251}
 1252
 1253#[derive(Debug, PartialEq, Eq)]
 1254#[allow(clippy::large_enum_variant)]
 1255pub(crate) enum ActiveDiagnostic {
 1256    None,
 1257    All,
 1258    Group(ActiveDiagnosticGroup),
 1259}
 1260
 1261#[derive(Serialize, Deserialize, Clone, Debug)]
 1262pub struct ClipboardSelection {
 1263    /// The number of bytes in this selection.
 1264    pub len: usize,
 1265    /// Whether this was a full-line selection.
 1266    pub is_entire_line: bool,
 1267    /// The indentation of the first line when this content was originally copied.
 1268    pub first_line_indent: u32,
 1269}
 1270
 1271// selections, scroll behavior, was newest selection reversed
 1272type SelectSyntaxNodeHistoryState = (
 1273    Box<[Selection<usize>]>,
 1274    SelectSyntaxNodeScrollBehavior,
 1275    bool,
 1276);
 1277
 1278#[derive(Default)]
 1279struct SelectSyntaxNodeHistory {
 1280    stack: Vec<SelectSyntaxNodeHistoryState>,
 1281    // disable temporarily to allow changing selections without losing the stack
 1282    pub disable_clearing: bool,
 1283}
 1284
 1285impl SelectSyntaxNodeHistory {
 1286    pub fn try_clear(&mut self) {
 1287        if !self.disable_clearing {
 1288            self.stack.clear();
 1289        }
 1290    }
 1291
 1292    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1293        self.stack.push(selection);
 1294    }
 1295
 1296    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1297        self.stack.pop()
 1298    }
 1299}
 1300
 1301enum SelectSyntaxNodeScrollBehavior {
 1302    CursorTop,
 1303    FitSelection,
 1304    CursorBottom,
 1305}
 1306
 1307#[derive(Debug)]
 1308pub(crate) struct NavigationData {
 1309    cursor_anchor: Anchor,
 1310    cursor_position: Point,
 1311    scroll_anchor: ScrollAnchor,
 1312    scroll_top_row: u32,
 1313}
 1314
 1315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1316pub enum GotoDefinitionKind {
 1317    Symbol,
 1318    Declaration,
 1319    Type,
 1320    Implementation,
 1321}
 1322
 1323#[derive(Debug, Clone)]
 1324enum InlayHintRefreshReason {
 1325    ModifiersChanged(bool),
 1326    Toggle(bool),
 1327    SettingsChange(InlayHintSettings),
 1328    NewLinesShown,
 1329    BufferEdited(HashSet<Arc<Language>>),
 1330    RefreshRequested,
 1331    ExcerptsRemoved(Vec<ExcerptId>),
 1332}
 1333
 1334impl InlayHintRefreshReason {
 1335    fn description(&self) -> &'static str {
 1336        match self {
 1337            Self::ModifiersChanged(_) => "modifiers changed",
 1338            Self::Toggle(_) => "toggle",
 1339            Self::SettingsChange(_) => "settings change",
 1340            Self::NewLinesShown => "new lines shown",
 1341            Self::BufferEdited(_) => "buffer edited",
 1342            Self::RefreshRequested => "refresh requested",
 1343            Self::ExcerptsRemoved(_) => "excerpts removed",
 1344        }
 1345    }
 1346}
 1347
 1348pub enum FormatTarget {
 1349    Buffers,
 1350    Ranges(Vec<Range<MultiBufferPoint>>),
 1351}
 1352
 1353pub(crate) struct FocusedBlock {
 1354    id: BlockId,
 1355    focus_handle: WeakFocusHandle,
 1356}
 1357
 1358#[derive(Clone)]
 1359enum JumpData {
 1360    MultiBufferRow {
 1361        row: MultiBufferRow,
 1362        line_offset_from_top: u32,
 1363    },
 1364    MultiBufferPoint {
 1365        excerpt_id: ExcerptId,
 1366        position: Point,
 1367        anchor: text::Anchor,
 1368        line_offset_from_top: u32,
 1369    },
 1370}
 1371
 1372pub enum MultibufferSelectionMode {
 1373    First,
 1374    All,
 1375}
 1376
 1377#[derive(Clone, Copy, Debug, Default)]
 1378pub struct RewrapOptions {
 1379    pub override_language_settings: bool,
 1380    pub preserve_existing_whitespace: bool,
 1381}
 1382
 1383impl Editor {
 1384    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1385        let buffer = cx.new(|cx| Buffer::local("", cx));
 1386        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1387        Self::new(
 1388            EditorMode::SingleLine { auto_width: false },
 1389            buffer,
 1390            None,
 1391            window,
 1392            cx,
 1393        )
 1394    }
 1395
 1396    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1397        let buffer = cx.new(|cx| Buffer::local("", cx));
 1398        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1399        Self::new(EditorMode::full(), buffer, None, window, cx)
 1400    }
 1401
 1402    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1403        let buffer = cx.new(|cx| Buffer::local("", cx));
 1404        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1405        Self::new(
 1406            EditorMode::SingleLine { auto_width: true },
 1407            buffer,
 1408            None,
 1409            window,
 1410            cx,
 1411        )
 1412    }
 1413
 1414    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1415        let buffer = cx.new(|cx| Buffer::local("", cx));
 1416        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1417        Self::new(
 1418            EditorMode::AutoHeight { max_lines },
 1419            buffer,
 1420            None,
 1421            window,
 1422            cx,
 1423        )
 1424    }
 1425
 1426    pub fn for_buffer(
 1427        buffer: Entity<Buffer>,
 1428        project: Option<Entity<Project>>,
 1429        window: &mut Window,
 1430        cx: &mut Context<Self>,
 1431    ) -> Self {
 1432        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1433        Self::new(EditorMode::full(), buffer, project, window, cx)
 1434    }
 1435
 1436    pub fn for_multibuffer(
 1437        buffer: Entity<MultiBuffer>,
 1438        project: Option<Entity<Project>>,
 1439        window: &mut Window,
 1440        cx: &mut Context<Self>,
 1441    ) -> Self {
 1442        Self::new(EditorMode::full(), buffer, project, window, cx)
 1443    }
 1444
 1445    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1446        let mut clone = Self::new(
 1447            self.mode,
 1448            self.buffer.clone(),
 1449            self.project.clone(),
 1450            window,
 1451            cx,
 1452        );
 1453        self.display_map.update(cx, |display_map, cx| {
 1454            let snapshot = display_map.snapshot(cx);
 1455            clone.display_map.update(cx, |display_map, cx| {
 1456                display_map.set_state(&snapshot, cx);
 1457            });
 1458        });
 1459        clone.folds_did_change(cx);
 1460        clone.selections.clone_state(&self.selections);
 1461        clone.scroll_manager.clone_state(&self.scroll_manager);
 1462        clone.searchable = self.searchable;
 1463        clone.read_only = self.read_only;
 1464        clone
 1465    }
 1466
 1467    pub fn new(
 1468        mode: EditorMode,
 1469        buffer: Entity<MultiBuffer>,
 1470        project: Option<Entity<Project>>,
 1471        window: &mut Window,
 1472        cx: &mut Context<Self>,
 1473    ) -> Self {
 1474        let style = window.text_style();
 1475        let font_size = style.font_size.to_pixels(window.rem_size());
 1476        let editor = cx.entity().downgrade();
 1477        let fold_placeholder = FoldPlaceholder {
 1478            constrain_width: true,
 1479            render: Arc::new(move |fold_id, fold_range, cx| {
 1480                let editor = editor.clone();
 1481                div()
 1482                    .id(fold_id)
 1483                    .bg(cx.theme().colors().ghost_element_background)
 1484                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1485                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1486                    .rounded_xs()
 1487                    .size_full()
 1488                    .cursor_pointer()
 1489                    .child("")
 1490                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1491                    .on_click(move |_, _window, cx| {
 1492                        editor
 1493                            .update(cx, |editor, cx| {
 1494                                editor.unfold_ranges(
 1495                                    &[fold_range.start..fold_range.end],
 1496                                    true,
 1497                                    false,
 1498                                    cx,
 1499                                );
 1500                                cx.stop_propagation();
 1501                            })
 1502                            .ok();
 1503                    })
 1504                    .into_any()
 1505            }),
 1506            merge_adjacent: true,
 1507            ..Default::default()
 1508        };
 1509        let display_map = cx.new(|cx| {
 1510            DisplayMap::new(
 1511                buffer.clone(),
 1512                style.font(),
 1513                font_size,
 1514                None,
 1515                FILE_HEADER_HEIGHT,
 1516                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1517                fold_placeholder,
 1518                cx,
 1519            )
 1520        });
 1521
 1522        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1523
 1524        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1525
 1526        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1527            .then(|| language_settings::SoftWrap::None);
 1528
 1529        let mut project_subscriptions = Vec::new();
 1530        if mode.is_full() {
 1531            if let Some(project) = project.as_ref() {
 1532                project_subscriptions.push(cx.subscribe_in(
 1533                    project,
 1534                    window,
 1535                    |editor, _, event, window, cx| match event {
 1536                        project::Event::RefreshCodeLens => {
 1537                            // we always query lens with actions, without storing them, always refreshing them
 1538                        }
 1539                        project::Event::RefreshInlayHints => {
 1540                            editor
 1541                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1542                        }
 1543                        project::Event::SnippetEdit(id, snippet_edits) => {
 1544                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1545                                let focus_handle = editor.focus_handle(cx);
 1546                                if focus_handle.is_focused(window) {
 1547                                    let snapshot = buffer.read(cx).snapshot();
 1548                                    for (range, snippet) in snippet_edits {
 1549                                        let editor_range =
 1550                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1551                                        editor
 1552                                            .insert_snippet(
 1553                                                &[editor_range],
 1554                                                snippet.clone(),
 1555                                                window,
 1556                                                cx,
 1557                                            )
 1558                                            .ok();
 1559                                    }
 1560                                }
 1561                            }
 1562                        }
 1563                        _ => {}
 1564                    },
 1565                ));
 1566                if let Some(task_inventory) = project
 1567                    .read(cx)
 1568                    .task_store()
 1569                    .read(cx)
 1570                    .task_inventory()
 1571                    .cloned()
 1572                {
 1573                    project_subscriptions.push(cx.observe_in(
 1574                        &task_inventory,
 1575                        window,
 1576                        |editor, _, window, cx| {
 1577                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1578                        },
 1579                    ));
 1580                };
 1581
 1582                project_subscriptions.push(cx.subscribe_in(
 1583                    &project.read(cx).breakpoint_store(),
 1584                    window,
 1585                    |editor, _, event, window, cx| match event {
 1586                        BreakpointStoreEvent::ClearDebugLines => {
 1587                            editor.clear_row_highlights::<ActiveDebugLine>();
 1588                            editor.refresh_inline_values(cx);
 1589                        }
 1590                        BreakpointStoreEvent::SetDebugLine => {
 1591                            if editor.go_to_active_debug_line(window, cx) {
 1592                                cx.stop_propagation();
 1593                            }
 1594
 1595                            editor.refresh_inline_values(cx);
 1596                        }
 1597                        _ => {}
 1598                    },
 1599                ));
 1600            }
 1601        }
 1602
 1603        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1604
 1605        let inlay_hint_settings =
 1606            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1607        let focus_handle = cx.focus_handle();
 1608        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1609            .detach();
 1610        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1611            .detach();
 1612        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1613            .detach();
 1614        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1615            .detach();
 1616
 1617        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1618            Some(false)
 1619        } else {
 1620            None
 1621        };
 1622
 1623        let breakpoint_store = match (mode, project.as_ref()) {
 1624            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1625            _ => None,
 1626        };
 1627
 1628        let mut code_action_providers = Vec::new();
 1629        let mut load_uncommitted_diff = None;
 1630        if let Some(project) = project.clone() {
 1631            load_uncommitted_diff = Some(
 1632                update_uncommitted_diff_for_buffer(
 1633                    cx.entity(),
 1634                    &project,
 1635                    buffer.read(cx).all_buffers(),
 1636                    buffer.clone(),
 1637                    cx,
 1638                )
 1639                .shared(),
 1640            );
 1641            code_action_providers.push(Rc::new(project) as Rc<_>);
 1642        }
 1643
 1644        let mut this = Self {
 1645            focus_handle,
 1646            show_cursor_when_unfocused: false,
 1647            last_focused_descendant: None,
 1648            buffer: buffer.clone(),
 1649            display_map: display_map.clone(),
 1650            selections,
 1651            scroll_manager: ScrollManager::new(cx),
 1652            columnar_selection_tail: None,
 1653            add_selections_state: None,
 1654            select_next_state: None,
 1655            select_prev_state: None,
 1656            selection_history: Default::default(),
 1657            autoclose_regions: Default::default(),
 1658            snippet_stack: Default::default(),
 1659            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1660            ime_transaction: Default::default(),
 1661            active_diagnostics: ActiveDiagnostic::None,
 1662            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1663            inline_diagnostics_update: Task::ready(()),
 1664            inline_diagnostics: Vec::new(),
 1665            soft_wrap_mode_override,
 1666            hard_wrap: None,
 1667            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1668            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1669            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1670            project,
 1671            blink_manager: blink_manager.clone(),
 1672            show_local_selections: true,
 1673            show_scrollbars: true,
 1674            mode,
 1675            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1676            show_gutter: mode.is_full(),
 1677            show_line_numbers: None,
 1678            use_relative_line_numbers: None,
 1679            disable_expand_excerpt_buttons: false,
 1680            show_git_diff_gutter: None,
 1681            show_code_actions: None,
 1682            show_runnables: None,
 1683            show_breakpoints: None,
 1684            show_wrap_guides: None,
 1685            show_indent_guides,
 1686            placeholder_text: None,
 1687            highlight_order: 0,
 1688            highlighted_rows: HashMap::default(),
 1689            background_highlights: Default::default(),
 1690            gutter_highlights: TreeMap::default(),
 1691            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1692            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1693            nav_history: None,
 1694            context_menu: RefCell::new(None),
 1695            context_menu_options: None,
 1696            mouse_context_menu: None,
 1697            completion_tasks: Default::default(),
 1698            inline_blame_popover: Default::default(),
 1699            signature_help_state: SignatureHelpState::default(),
 1700            auto_signature_help: None,
 1701            find_all_references_task_sources: Vec::new(),
 1702            next_completion_id: 0,
 1703            next_inlay_id: 0,
 1704            code_action_providers,
 1705            available_code_actions: Default::default(),
 1706            code_actions_task: Default::default(),
 1707            quick_selection_highlight_task: Default::default(),
 1708            debounced_selection_highlight_task: Default::default(),
 1709            document_highlights_task: Default::default(),
 1710            linked_editing_range_task: Default::default(),
 1711            pending_rename: Default::default(),
 1712            searchable: true,
 1713            cursor_shape: EditorSettings::get_global(cx)
 1714                .cursor_shape
 1715                .unwrap_or_default(),
 1716            current_line_highlight: None,
 1717            autoindent_mode: Some(AutoindentMode::EachLine),
 1718            collapse_matches: false,
 1719            workspace: None,
 1720            input_enabled: true,
 1721            use_modal_editing: mode.is_full(),
 1722            read_only: false,
 1723            use_autoclose: true,
 1724            use_auto_surround: true,
 1725            auto_replace_emoji_shortcode: false,
 1726            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1727            leader_id: None,
 1728            remote_id: None,
 1729            hover_state: Default::default(),
 1730            pending_mouse_down: None,
 1731            hovered_link_state: Default::default(),
 1732            edit_prediction_provider: None,
 1733            active_inline_completion: None,
 1734            stale_inline_completion_in_menu: None,
 1735            edit_prediction_preview: EditPredictionPreview::Inactive {
 1736                released_too_fast: false,
 1737            },
 1738            inline_diagnostics_enabled: mode.is_full(),
 1739            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1740            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1741
 1742            gutter_hovered: false,
 1743            pixel_position_of_newest_cursor: None,
 1744            last_bounds: None,
 1745            last_position_map: None,
 1746            expect_bounds_change: None,
 1747            gutter_dimensions: GutterDimensions::default(),
 1748            style: None,
 1749            show_cursor_names: false,
 1750            hovered_cursors: Default::default(),
 1751            next_editor_action_id: EditorActionId::default(),
 1752            editor_actions: Rc::default(),
 1753            inline_completions_hidden_for_vim_mode: false,
 1754            show_inline_completions_override: None,
 1755            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1756            edit_prediction_settings: EditPredictionSettings::Disabled,
 1757            edit_prediction_indent_conflict: false,
 1758            edit_prediction_requires_modifier_in_indent_conflict: true,
 1759            custom_context_menu: None,
 1760            show_git_blame_gutter: false,
 1761            show_git_blame_inline: false,
 1762            show_selection_menu: None,
 1763            show_git_blame_inline_delay_task: None,
 1764            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1765            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1766            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1767                .session
 1768                .restore_unsaved_buffers,
 1769            blame: None,
 1770            blame_subscription: None,
 1771            tasks: Default::default(),
 1772
 1773            breakpoint_store,
 1774            gutter_breakpoint_indicator: (None, None),
 1775            _subscriptions: vec![
 1776                cx.observe(&buffer, Self::on_buffer_changed),
 1777                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1778                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1779                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1780                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1781                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1782                cx.observe_window_activation(window, |editor, window, cx| {
 1783                    let active = window.is_window_active();
 1784                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1785                        if active {
 1786                            blink_manager.enable(cx);
 1787                        } else {
 1788                            blink_manager.disable(cx);
 1789                        }
 1790                    });
 1791                }),
 1792            ],
 1793            tasks_update_task: None,
 1794            linked_edit_ranges: Default::default(),
 1795            in_project_search: false,
 1796            previous_search_ranges: None,
 1797            breadcrumb_header: None,
 1798            focused_block: None,
 1799            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1800            addons: HashMap::default(),
 1801            registered_buffers: HashMap::default(),
 1802            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1803            selection_mark_mode: false,
 1804            toggle_fold_multiple_buffers: Task::ready(()),
 1805            serialize_selections: Task::ready(()),
 1806            serialize_folds: Task::ready(()),
 1807            text_style_refinement: None,
 1808            load_diff_task: load_uncommitted_diff,
 1809            temporary_diff_override: false,
 1810            mouse_cursor_hidden: false,
 1811            hide_mouse_mode: EditorSettings::get_global(cx)
 1812                .hide_mouse
 1813                .unwrap_or_default(),
 1814            change_list: ChangeList::new(),
 1815        };
 1816        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1817            this._subscriptions
 1818                .push(cx.observe(breakpoints, |_, _, cx| {
 1819                    cx.notify();
 1820                }));
 1821        }
 1822        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1823        this._subscriptions.extend(project_subscriptions);
 1824
 1825        this._subscriptions.push(cx.subscribe_in(
 1826            &cx.entity(),
 1827            window,
 1828            |editor, _, e: &EditorEvent, window, cx| match e {
 1829                EditorEvent::ScrollPositionChanged { local, .. } => {
 1830                    if *local {
 1831                        let new_anchor = editor.scroll_manager.anchor();
 1832                        let snapshot = editor.snapshot(window, cx);
 1833                        editor.update_restoration_data(cx, move |data| {
 1834                            data.scroll_position = (
 1835                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1836                                new_anchor.offset,
 1837                            );
 1838                        });
 1839                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1840                        editor.inline_blame_popover.take();
 1841                    }
 1842                }
 1843                EditorEvent::Edited { .. } => {
 1844                    if !vim_enabled(cx) {
 1845                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1846                        let pop_state = editor
 1847                            .change_list
 1848                            .last()
 1849                            .map(|previous| {
 1850                                previous.len() == selections.len()
 1851                                    && previous.iter().enumerate().all(|(ix, p)| {
 1852                                        p.to_display_point(&map).row()
 1853                                            == selections[ix].head().row()
 1854                                    })
 1855                            })
 1856                            .unwrap_or(false);
 1857                        let new_positions = selections
 1858                            .into_iter()
 1859                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1860                            .collect();
 1861                        editor
 1862                            .change_list
 1863                            .push_to_change_list(pop_state, new_positions);
 1864                    }
 1865                }
 1866                _ => (),
 1867            },
 1868        ));
 1869
 1870        if let Some(dap_store) = this
 1871            .project
 1872            .as_ref()
 1873            .map(|project| project.read(cx).dap_store())
 1874        {
 1875            let weak_editor = cx.weak_entity();
 1876
 1877            this._subscriptions
 1878                .push(
 1879                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1880                        let session_entity = cx.entity();
 1881                        weak_editor
 1882                            .update(cx, |editor, cx| {
 1883                                editor._subscriptions.push(
 1884                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1885                                );
 1886                            })
 1887                            .ok();
 1888                    }),
 1889                );
 1890
 1891            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1892                this._subscriptions
 1893                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1894            }
 1895        }
 1896
 1897        this.end_selection(window, cx);
 1898        this.scroll_manager.show_scrollbars(window, cx);
 1899        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1900
 1901        if mode.is_full() {
 1902            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1903            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1904
 1905            if this.git_blame_inline_enabled {
 1906                this.git_blame_inline_enabled = true;
 1907                this.start_git_blame_inline(false, window, cx);
 1908            }
 1909
 1910            this.go_to_active_debug_line(window, cx);
 1911
 1912            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1913                if let Some(project) = this.project.as_ref() {
 1914                    let handle = project.update(cx, |project, cx| {
 1915                        project.register_buffer_with_language_servers(&buffer, cx)
 1916                    });
 1917                    this.registered_buffers
 1918                        .insert(buffer.read(cx).remote_id(), handle);
 1919                }
 1920            }
 1921        }
 1922
 1923        this.report_editor_event("Editor Opened", None, cx);
 1924        this
 1925    }
 1926
 1927    pub fn deploy_mouse_context_menu(
 1928        &mut self,
 1929        position: gpui::Point<Pixels>,
 1930        context_menu: Entity<ContextMenu>,
 1931        window: &mut Window,
 1932        cx: &mut Context<Self>,
 1933    ) {
 1934        self.mouse_context_menu = Some(MouseContextMenu::new(
 1935            self,
 1936            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1937            context_menu,
 1938            window,
 1939            cx,
 1940        ));
 1941    }
 1942
 1943    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1944        self.mouse_context_menu
 1945            .as_ref()
 1946            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1947    }
 1948
 1949    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1950        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1951    }
 1952
 1953    fn key_context_internal(
 1954        &self,
 1955        has_active_edit_prediction: bool,
 1956        window: &Window,
 1957        cx: &App,
 1958    ) -> KeyContext {
 1959        let mut key_context = KeyContext::new_with_defaults();
 1960        key_context.add("Editor");
 1961        let mode = match self.mode {
 1962            EditorMode::SingleLine { .. } => "single_line",
 1963            EditorMode::AutoHeight { .. } => "auto_height",
 1964            EditorMode::Full { .. } => "full",
 1965        };
 1966
 1967        if EditorSettings::jupyter_enabled(cx) {
 1968            key_context.add("jupyter");
 1969        }
 1970
 1971        key_context.set("mode", mode);
 1972        if self.pending_rename.is_some() {
 1973            key_context.add("renaming");
 1974        }
 1975
 1976        match self.context_menu.borrow().as_ref() {
 1977            Some(CodeContextMenu::Completions(_)) => {
 1978                key_context.add("menu");
 1979                key_context.add("showing_completions");
 1980            }
 1981            Some(CodeContextMenu::CodeActions(_)) => {
 1982                key_context.add("menu");
 1983                key_context.add("showing_code_actions")
 1984            }
 1985            None => {}
 1986        }
 1987
 1988        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1989        if !self.focus_handle(cx).contains_focused(window, cx)
 1990            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1991        {
 1992            for addon in self.addons.values() {
 1993                addon.extend_key_context(&mut key_context, cx)
 1994            }
 1995        }
 1996
 1997        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1998            if let Some(extension) = singleton_buffer
 1999                .read(cx)
 2000                .file()
 2001                .and_then(|file| file.path().extension()?.to_str())
 2002            {
 2003                key_context.set("extension", extension.to_string());
 2004            }
 2005        } else {
 2006            key_context.add("multibuffer");
 2007        }
 2008
 2009        if has_active_edit_prediction {
 2010            if self.edit_prediction_in_conflict() {
 2011                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2012            } else {
 2013                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2014                key_context.add("copilot_suggestion");
 2015            }
 2016        }
 2017
 2018        if self.selection_mark_mode {
 2019            key_context.add("selection_mode");
 2020        }
 2021
 2022        key_context
 2023    }
 2024
 2025    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2026        self.mouse_cursor_hidden = match origin {
 2027            HideMouseCursorOrigin::TypingAction => {
 2028                matches!(
 2029                    self.hide_mouse_mode,
 2030                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2031                )
 2032            }
 2033            HideMouseCursorOrigin::MovementAction => {
 2034                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2035            }
 2036        };
 2037    }
 2038
 2039    pub fn edit_prediction_in_conflict(&self) -> bool {
 2040        if !self.show_edit_predictions_in_menu() {
 2041            return false;
 2042        }
 2043
 2044        let showing_completions = self
 2045            .context_menu
 2046            .borrow()
 2047            .as_ref()
 2048            .map_or(false, |context| {
 2049                matches!(context, CodeContextMenu::Completions(_))
 2050            });
 2051
 2052        showing_completions
 2053            || self.edit_prediction_requires_modifier()
 2054            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2055            // bindings to insert tab characters.
 2056            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2057    }
 2058
 2059    pub fn accept_edit_prediction_keybind(
 2060        &self,
 2061        window: &Window,
 2062        cx: &App,
 2063    ) -> AcceptEditPredictionBinding {
 2064        let key_context = self.key_context_internal(true, window, cx);
 2065        let in_conflict = self.edit_prediction_in_conflict();
 2066
 2067        AcceptEditPredictionBinding(
 2068            window
 2069                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2070                .into_iter()
 2071                .filter(|binding| {
 2072                    !in_conflict
 2073                        || binding
 2074                            .keystrokes()
 2075                            .first()
 2076                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2077                })
 2078                .rev()
 2079                .min_by_key(|binding| {
 2080                    binding
 2081                        .keystrokes()
 2082                        .first()
 2083                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2084                }),
 2085        )
 2086    }
 2087
 2088    pub fn new_file(
 2089        workspace: &mut Workspace,
 2090        _: &workspace::NewFile,
 2091        window: &mut Window,
 2092        cx: &mut Context<Workspace>,
 2093    ) {
 2094        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2095            "Failed to create buffer",
 2096            window,
 2097            cx,
 2098            |e, _, _| match e.error_code() {
 2099                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2100                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2101                e.error_tag("required").unwrap_or("the latest version")
 2102            )),
 2103                _ => None,
 2104            },
 2105        );
 2106    }
 2107
 2108    pub fn new_in_workspace(
 2109        workspace: &mut Workspace,
 2110        window: &mut Window,
 2111        cx: &mut Context<Workspace>,
 2112    ) -> Task<Result<Entity<Editor>>> {
 2113        let project = workspace.project().clone();
 2114        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2115
 2116        cx.spawn_in(window, async move |workspace, cx| {
 2117            let buffer = create.await?;
 2118            workspace.update_in(cx, |workspace, window, cx| {
 2119                let editor =
 2120                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2121                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2122                editor
 2123            })
 2124        })
 2125    }
 2126
 2127    fn new_file_vertical(
 2128        workspace: &mut Workspace,
 2129        _: &workspace::NewFileSplitVertical,
 2130        window: &mut Window,
 2131        cx: &mut Context<Workspace>,
 2132    ) {
 2133        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2134    }
 2135
 2136    fn new_file_horizontal(
 2137        workspace: &mut Workspace,
 2138        _: &workspace::NewFileSplitHorizontal,
 2139        window: &mut Window,
 2140        cx: &mut Context<Workspace>,
 2141    ) {
 2142        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2143    }
 2144
 2145    fn new_file_in_direction(
 2146        workspace: &mut Workspace,
 2147        direction: SplitDirection,
 2148        window: &mut Window,
 2149        cx: &mut Context<Workspace>,
 2150    ) {
 2151        let project = workspace.project().clone();
 2152        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2153
 2154        cx.spawn_in(window, async move |workspace, cx| {
 2155            let buffer = create.await?;
 2156            workspace.update_in(cx, move |workspace, window, cx| {
 2157                workspace.split_item(
 2158                    direction,
 2159                    Box::new(
 2160                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2161                    ),
 2162                    window,
 2163                    cx,
 2164                )
 2165            })?;
 2166            anyhow::Ok(())
 2167        })
 2168        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2169            match e.error_code() {
 2170                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2171                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2172                e.error_tag("required").unwrap_or("the latest version")
 2173            )),
 2174                _ => None,
 2175            }
 2176        });
 2177    }
 2178
 2179    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2180        self.leader_id
 2181    }
 2182
 2183    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2184        &self.buffer
 2185    }
 2186
 2187    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2188        self.workspace.as_ref()?.0.upgrade()
 2189    }
 2190
 2191    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2192        self.buffer().read(cx).title(cx)
 2193    }
 2194
 2195    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2196        let git_blame_gutter_max_author_length = self
 2197            .render_git_blame_gutter(cx)
 2198            .then(|| {
 2199                if let Some(blame) = self.blame.as_ref() {
 2200                    let max_author_length =
 2201                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2202                    Some(max_author_length)
 2203                } else {
 2204                    None
 2205                }
 2206            })
 2207            .flatten();
 2208
 2209        EditorSnapshot {
 2210            mode: self.mode,
 2211            show_gutter: self.show_gutter,
 2212            show_line_numbers: self.show_line_numbers,
 2213            show_git_diff_gutter: self.show_git_diff_gutter,
 2214            show_runnables: self.show_runnables,
 2215            show_breakpoints: self.show_breakpoints,
 2216            git_blame_gutter_max_author_length,
 2217            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2218            scroll_anchor: self.scroll_manager.anchor(),
 2219            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2220            placeholder_text: self.placeholder_text.clone(),
 2221            is_focused: self.focus_handle.is_focused(window),
 2222            current_line_highlight: self
 2223                .current_line_highlight
 2224                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2225            gutter_hovered: self.gutter_hovered,
 2226        }
 2227    }
 2228
 2229    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2230        self.buffer.read(cx).language_at(point, cx)
 2231    }
 2232
 2233    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2234        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2235    }
 2236
 2237    pub fn active_excerpt(
 2238        &self,
 2239        cx: &App,
 2240    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2241        self.buffer
 2242            .read(cx)
 2243            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2244    }
 2245
 2246    pub fn mode(&self) -> EditorMode {
 2247        self.mode
 2248    }
 2249
 2250    pub fn set_mode(&mut self, mode: EditorMode) {
 2251        self.mode = mode;
 2252    }
 2253
 2254    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2255        self.collaboration_hub.as_deref()
 2256    }
 2257
 2258    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2259        self.collaboration_hub = Some(hub);
 2260    }
 2261
 2262    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2263        self.in_project_search = in_project_search;
 2264    }
 2265
 2266    pub fn set_custom_context_menu(
 2267        &mut self,
 2268        f: impl 'static
 2269        + Fn(
 2270            &mut Self,
 2271            DisplayPoint,
 2272            &mut Window,
 2273            &mut Context<Self>,
 2274        ) -> Option<Entity<ui::ContextMenu>>,
 2275    ) {
 2276        self.custom_context_menu = Some(Box::new(f))
 2277    }
 2278
 2279    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2280        self.completion_provider = provider;
 2281    }
 2282
 2283    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2284        self.semantics_provider.clone()
 2285    }
 2286
 2287    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2288        self.semantics_provider = provider;
 2289    }
 2290
 2291    pub fn set_edit_prediction_provider<T>(
 2292        &mut self,
 2293        provider: Option<Entity<T>>,
 2294        window: &mut Window,
 2295        cx: &mut Context<Self>,
 2296    ) where
 2297        T: EditPredictionProvider,
 2298    {
 2299        self.edit_prediction_provider =
 2300            provider.map(|provider| RegisteredInlineCompletionProvider {
 2301                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2302                    if this.focus_handle.is_focused(window) {
 2303                        this.update_visible_inline_completion(window, cx);
 2304                    }
 2305                }),
 2306                provider: Arc::new(provider),
 2307            });
 2308        self.update_edit_prediction_settings(cx);
 2309        self.refresh_inline_completion(false, false, window, cx);
 2310    }
 2311
 2312    pub fn placeholder_text(&self) -> Option<&str> {
 2313        self.placeholder_text.as_deref()
 2314    }
 2315
 2316    pub fn set_placeholder_text(
 2317        &mut self,
 2318        placeholder_text: impl Into<Arc<str>>,
 2319        cx: &mut Context<Self>,
 2320    ) {
 2321        let placeholder_text = Some(placeholder_text.into());
 2322        if self.placeholder_text != placeholder_text {
 2323            self.placeholder_text = placeholder_text;
 2324            cx.notify();
 2325        }
 2326    }
 2327
 2328    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2329        self.cursor_shape = cursor_shape;
 2330
 2331        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2332        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2333
 2334        cx.notify();
 2335    }
 2336
 2337    pub fn set_current_line_highlight(
 2338        &mut self,
 2339        current_line_highlight: Option<CurrentLineHighlight>,
 2340    ) {
 2341        self.current_line_highlight = current_line_highlight;
 2342    }
 2343
 2344    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2345        self.collapse_matches = collapse_matches;
 2346    }
 2347
 2348    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2349        let buffers = self.buffer.read(cx).all_buffers();
 2350        let Some(project) = self.project.as_ref() else {
 2351            return;
 2352        };
 2353        project.update(cx, |project, cx| {
 2354            for buffer in buffers {
 2355                self.registered_buffers
 2356                    .entry(buffer.read(cx).remote_id())
 2357                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2358            }
 2359        })
 2360    }
 2361
 2362    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2363        if self.collapse_matches {
 2364            return range.start..range.start;
 2365        }
 2366        range.clone()
 2367    }
 2368
 2369    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2370        if self.display_map.read(cx).clip_at_line_ends != clip {
 2371            self.display_map
 2372                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2373        }
 2374    }
 2375
 2376    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2377        self.input_enabled = input_enabled;
 2378    }
 2379
 2380    pub fn set_inline_completions_hidden_for_vim_mode(
 2381        &mut self,
 2382        hidden: bool,
 2383        window: &mut Window,
 2384        cx: &mut Context<Self>,
 2385    ) {
 2386        if hidden != self.inline_completions_hidden_for_vim_mode {
 2387            self.inline_completions_hidden_for_vim_mode = hidden;
 2388            if hidden {
 2389                self.update_visible_inline_completion(window, cx);
 2390            } else {
 2391                self.refresh_inline_completion(true, false, window, cx);
 2392            }
 2393        }
 2394    }
 2395
 2396    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2397        self.menu_inline_completions_policy = value;
 2398    }
 2399
 2400    pub fn set_autoindent(&mut self, autoindent: bool) {
 2401        if autoindent {
 2402            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2403        } else {
 2404            self.autoindent_mode = None;
 2405        }
 2406    }
 2407
 2408    pub fn read_only(&self, cx: &App) -> bool {
 2409        self.read_only || self.buffer.read(cx).read_only()
 2410    }
 2411
 2412    pub fn set_read_only(&mut self, read_only: bool) {
 2413        self.read_only = read_only;
 2414    }
 2415
 2416    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2417        self.use_autoclose = autoclose;
 2418    }
 2419
 2420    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2421        self.use_auto_surround = auto_surround;
 2422    }
 2423
 2424    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2425        self.auto_replace_emoji_shortcode = auto_replace;
 2426    }
 2427
 2428    pub fn toggle_edit_predictions(
 2429        &mut self,
 2430        _: &ToggleEditPrediction,
 2431        window: &mut Window,
 2432        cx: &mut Context<Self>,
 2433    ) {
 2434        if self.show_inline_completions_override.is_some() {
 2435            self.set_show_edit_predictions(None, window, cx);
 2436        } else {
 2437            let show_edit_predictions = !self.edit_predictions_enabled();
 2438            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2439        }
 2440    }
 2441
 2442    pub fn set_show_edit_predictions(
 2443        &mut self,
 2444        show_edit_predictions: Option<bool>,
 2445        window: &mut Window,
 2446        cx: &mut Context<Self>,
 2447    ) {
 2448        self.show_inline_completions_override = show_edit_predictions;
 2449        self.update_edit_prediction_settings(cx);
 2450
 2451        if let Some(false) = show_edit_predictions {
 2452            self.discard_inline_completion(false, cx);
 2453        } else {
 2454            self.refresh_inline_completion(false, true, window, cx);
 2455        }
 2456    }
 2457
 2458    fn inline_completions_disabled_in_scope(
 2459        &self,
 2460        buffer: &Entity<Buffer>,
 2461        buffer_position: language::Anchor,
 2462        cx: &App,
 2463    ) -> bool {
 2464        let snapshot = buffer.read(cx).snapshot();
 2465        let settings = snapshot.settings_at(buffer_position, cx);
 2466
 2467        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2468            return false;
 2469        };
 2470
 2471        scope.override_name().map_or(false, |scope_name| {
 2472            settings
 2473                .edit_predictions_disabled_in
 2474                .iter()
 2475                .any(|s| s == scope_name)
 2476        })
 2477    }
 2478
 2479    pub fn set_use_modal_editing(&mut self, to: bool) {
 2480        self.use_modal_editing = to;
 2481    }
 2482
 2483    pub fn use_modal_editing(&self) -> bool {
 2484        self.use_modal_editing
 2485    }
 2486
 2487    fn selections_did_change(
 2488        &mut self,
 2489        local: bool,
 2490        old_cursor_position: &Anchor,
 2491        show_completions: bool,
 2492        window: &mut Window,
 2493        cx: &mut Context<Self>,
 2494    ) {
 2495        window.invalidate_character_coordinates();
 2496
 2497        // Copy selections to primary selection buffer
 2498        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2499        if local {
 2500            let selections = self.selections.all::<usize>(cx);
 2501            let buffer_handle = self.buffer.read(cx).read(cx);
 2502
 2503            let mut text = String::new();
 2504            for (index, selection) in selections.iter().enumerate() {
 2505                let text_for_selection = buffer_handle
 2506                    .text_for_range(selection.start..selection.end)
 2507                    .collect::<String>();
 2508
 2509                text.push_str(&text_for_selection);
 2510                if index != selections.len() - 1 {
 2511                    text.push('\n');
 2512                }
 2513            }
 2514
 2515            if !text.is_empty() {
 2516                cx.write_to_primary(ClipboardItem::new_string(text));
 2517            }
 2518        }
 2519
 2520        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2521            self.buffer.update(cx, |buffer, cx| {
 2522                buffer.set_active_selections(
 2523                    &self.selections.disjoint_anchors(),
 2524                    self.selections.line_mode,
 2525                    self.cursor_shape,
 2526                    cx,
 2527                )
 2528            });
 2529        }
 2530        let display_map = self
 2531            .display_map
 2532            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2533        let buffer = &display_map.buffer_snapshot;
 2534        self.add_selections_state = None;
 2535        self.select_next_state = None;
 2536        self.select_prev_state = None;
 2537        self.select_syntax_node_history.try_clear();
 2538        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2539        self.snippet_stack
 2540            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2541        self.take_rename(false, window, cx);
 2542
 2543        let new_cursor_position = self.selections.newest_anchor().head();
 2544
 2545        self.push_to_nav_history(
 2546            *old_cursor_position,
 2547            Some(new_cursor_position.to_point(buffer)),
 2548            false,
 2549            cx,
 2550        );
 2551
 2552        if local {
 2553            let new_cursor_position = self.selections.newest_anchor().head();
 2554            let mut context_menu = self.context_menu.borrow_mut();
 2555            let completion_menu = match context_menu.as_ref() {
 2556                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2557                _ => {
 2558                    *context_menu = None;
 2559                    None
 2560                }
 2561            };
 2562            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2563                if !self.registered_buffers.contains_key(&buffer_id) {
 2564                    if let Some(project) = self.project.as_ref() {
 2565                        project.update(cx, |project, cx| {
 2566                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2567                                return;
 2568                            };
 2569                            self.registered_buffers.insert(
 2570                                buffer_id,
 2571                                project.register_buffer_with_language_servers(&buffer, cx),
 2572                            );
 2573                        })
 2574                    }
 2575                }
 2576            }
 2577
 2578            if let Some(completion_menu) = completion_menu {
 2579                let cursor_position = new_cursor_position.to_offset(buffer);
 2580                let (word_range, kind) =
 2581                    buffer.surrounding_word(completion_menu.initial_position, true);
 2582                if kind == Some(CharKind::Word)
 2583                    && word_range.to_inclusive().contains(&cursor_position)
 2584                {
 2585                    let mut completion_menu = completion_menu.clone();
 2586                    drop(context_menu);
 2587
 2588                    let query = Self::completion_query(buffer, cursor_position);
 2589                    cx.spawn(async move |this, cx| {
 2590                        completion_menu
 2591                            .filter(query.as_deref(), cx.background_executor().clone())
 2592                            .await;
 2593
 2594                        this.update(cx, |this, cx| {
 2595                            let mut context_menu = this.context_menu.borrow_mut();
 2596                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2597                            else {
 2598                                return;
 2599                            };
 2600
 2601                            if menu.id > completion_menu.id {
 2602                                return;
 2603                            }
 2604
 2605                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2606                            drop(context_menu);
 2607                            cx.notify();
 2608                        })
 2609                    })
 2610                    .detach();
 2611
 2612                    if show_completions {
 2613                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2614                    }
 2615                } else {
 2616                    drop(context_menu);
 2617                    self.hide_context_menu(window, cx);
 2618                }
 2619            } else {
 2620                drop(context_menu);
 2621            }
 2622
 2623            hide_hover(self, cx);
 2624
 2625            if old_cursor_position.to_display_point(&display_map).row()
 2626                != new_cursor_position.to_display_point(&display_map).row()
 2627            {
 2628                self.available_code_actions.take();
 2629            }
 2630            self.refresh_code_actions(window, cx);
 2631            self.refresh_document_highlights(cx);
 2632            self.refresh_selected_text_highlights(false, window, cx);
 2633            refresh_matching_bracket_highlights(self, window, cx);
 2634            self.update_visible_inline_completion(window, cx);
 2635            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2636            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2637            self.inline_blame_popover.take();
 2638            if self.git_blame_inline_enabled {
 2639                self.start_inline_blame_timer(window, cx);
 2640            }
 2641        }
 2642
 2643        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2644        cx.emit(EditorEvent::SelectionsChanged { local });
 2645
 2646        let selections = &self.selections.disjoint;
 2647        if selections.len() == 1 {
 2648            cx.emit(SearchEvent::ActiveMatchChanged)
 2649        }
 2650        if local {
 2651            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2652                let inmemory_selections = selections
 2653                    .iter()
 2654                    .map(|s| {
 2655                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2656                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2657                    })
 2658                    .collect();
 2659                self.update_restoration_data(cx, |data| {
 2660                    data.selections = inmemory_selections;
 2661                });
 2662
 2663                if WorkspaceSettings::get(None, cx).restore_on_startup
 2664                    != RestoreOnStartupBehavior::None
 2665                {
 2666                    if let Some(workspace_id) =
 2667                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2668                    {
 2669                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2670                        let selections = selections.clone();
 2671                        let background_executor = cx.background_executor().clone();
 2672                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2673                        self.serialize_selections = cx.background_spawn(async move {
 2674                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2675                    let db_selections = selections
 2676                        .iter()
 2677                        .map(|selection| {
 2678                            (
 2679                                selection.start.to_offset(&snapshot),
 2680                                selection.end.to_offset(&snapshot),
 2681                            )
 2682                        })
 2683                        .collect();
 2684
 2685                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2686                        .await
 2687                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2688                        .log_err();
 2689                });
 2690                    }
 2691                }
 2692            }
 2693        }
 2694
 2695        cx.notify();
 2696    }
 2697
 2698    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2699        use text::ToOffset as _;
 2700        use text::ToPoint as _;
 2701
 2702        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2703            return;
 2704        }
 2705
 2706        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2707            return;
 2708        };
 2709
 2710        let snapshot = singleton.read(cx).snapshot();
 2711        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2712            let display_snapshot = display_map.snapshot(cx);
 2713
 2714            display_snapshot
 2715                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2716                .map(|fold| {
 2717                    fold.range.start.text_anchor.to_point(&snapshot)
 2718                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2719                })
 2720                .collect()
 2721        });
 2722        self.update_restoration_data(cx, |data| {
 2723            data.folds = inmemory_folds;
 2724        });
 2725
 2726        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2727            return;
 2728        };
 2729        let background_executor = cx.background_executor().clone();
 2730        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2731        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2732            display_map
 2733                .snapshot(cx)
 2734                .folds_in_range(0..snapshot.len())
 2735                .map(|fold| {
 2736                    (
 2737                        fold.range.start.text_anchor.to_offset(&snapshot),
 2738                        fold.range.end.text_anchor.to_offset(&snapshot),
 2739                    )
 2740                })
 2741                .collect()
 2742        });
 2743        self.serialize_folds = cx.background_spawn(async move {
 2744            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2745            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2746                .await
 2747                .with_context(|| {
 2748                    format!(
 2749                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2750                    )
 2751                })
 2752                .log_err();
 2753        });
 2754    }
 2755
 2756    pub fn sync_selections(
 2757        &mut self,
 2758        other: Entity<Editor>,
 2759        cx: &mut Context<Self>,
 2760    ) -> gpui::Subscription {
 2761        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2762        self.selections.change_with(cx, |selections| {
 2763            selections.select_anchors(other_selections);
 2764        });
 2765
 2766        let other_subscription =
 2767            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2768                EditorEvent::SelectionsChanged { local: true } => {
 2769                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2770                    if other_selections.is_empty() {
 2771                        return;
 2772                    }
 2773                    this.selections.change_with(cx, |selections| {
 2774                        selections.select_anchors(other_selections);
 2775                    });
 2776                }
 2777                _ => {}
 2778            });
 2779
 2780        let this_subscription =
 2781            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2782                EditorEvent::SelectionsChanged { local: true } => {
 2783                    let these_selections = this.selections.disjoint.to_vec();
 2784                    if these_selections.is_empty() {
 2785                        return;
 2786                    }
 2787                    other.update(cx, |other_editor, cx| {
 2788                        other_editor.selections.change_with(cx, |selections| {
 2789                            selections.select_anchors(these_selections);
 2790                        })
 2791                    });
 2792                }
 2793                _ => {}
 2794            });
 2795
 2796        Subscription::join(other_subscription, this_subscription)
 2797    }
 2798
 2799    pub fn change_selections<R>(
 2800        &mut self,
 2801        autoscroll: Option<Autoscroll>,
 2802        window: &mut Window,
 2803        cx: &mut Context<Self>,
 2804        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2805    ) -> R {
 2806        self.change_selections_inner(autoscroll, true, window, cx, change)
 2807    }
 2808
 2809    fn change_selections_inner<R>(
 2810        &mut self,
 2811        autoscroll: Option<Autoscroll>,
 2812        request_completions: bool,
 2813        window: &mut Window,
 2814        cx: &mut Context<Self>,
 2815        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2816    ) -> R {
 2817        let old_cursor_position = self.selections.newest_anchor().head();
 2818        self.push_to_selection_history();
 2819
 2820        let (changed, result) = self.selections.change_with(cx, change);
 2821
 2822        if changed {
 2823            if let Some(autoscroll) = autoscroll {
 2824                self.request_autoscroll(autoscroll, cx);
 2825            }
 2826            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2827
 2828            if self.should_open_signature_help_automatically(
 2829                &old_cursor_position,
 2830                self.signature_help_state.backspace_pressed(),
 2831                cx,
 2832            ) {
 2833                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2834            }
 2835            self.signature_help_state.set_backspace_pressed(false);
 2836        }
 2837
 2838        result
 2839    }
 2840
 2841    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2842    where
 2843        I: IntoIterator<Item = (Range<S>, T)>,
 2844        S: ToOffset,
 2845        T: Into<Arc<str>>,
 2846    {
 2847        if self.read_only(cx) {
 2848            return;
 2849        }
 2850
 2851        self.buffer
 2852            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2853    }
 2854
 2855    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2856    where
 2857        I: IntoIterator<Item = (Range<S>, T)>,
 2858        S: ToOffset,
 2859        T: Into<Arc<str>>,
 2860    {
 2861        if self.read_only(cx) {
 2862            return;
 2863        }
 2864
 2865        self.buffer.update(cx, |buffer, cx| {
 2866            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2867        });
 2868    }
 2869
 2870    pub fn edit_with_block_indent<I, S, T>(
 2871        &mut self,
 2872        edits: I,
 2873        original_indent_columns: Vec<Option<u32>>,
 2874        cx: &mut Context<Self>,
 2875    ) where
 2876        I: IntoIterator<Item = (Range<S>, T)>,
 2877        S: ToOffset,
 2878        T: Into<Arc<str>>,
 2879    {
 2880        if self.read_only(cx) {
 2881            return;
 2882        }
 2883
 2884        self.buffer.update(cx, |buffer, cx| {
 2885            buffer.edit(
 2886                edits,
 2887                Some(AutoindentMode::Block {
 2888                    original_indent_columns,
 2889                }),
 2890                cx,
 2891            )
 2892        });
 2893    }
 2894
 2895    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2896        self.hide_context_menu(window, cx);
 2897
 2898        match phase {
 2899            SelectPhase::Begin {
 2900                position,
 2901                add,
 2902                click_count,
 2903            } => self.begin_selection(position, add, click_count, window, cx),
 2904            SelectPhase::BeginColumnar {
 2905                position,
 2906                goal_column,
 2907                reset,
 2908            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2909            SelectPhase::Extend {
 2910                position,
 2911                click_count,
 2912            } => self.extend_selection(position, click_count, window, cx),
 2913            SelectPhase::Update {
 2914                position,
 2915                goal_column,
 2916                scroll_delta,
 2917            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2918            SelectPhase::End => self.end_selection(window, cx),
 2919        }
 2920    }
 2921
 2922    fn extend_selection(
 2923        &mut self,
 2924        position: DisplayPoint,
 2925        click_count: usize,
 2926        window: &mut Window,
 2927        cx: &mut Context<Self>,
 2928    ) {
 2929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2930        let tail = self.selections.newest::<usize>(cx).tail();
 2931        self.begin_selection(position, false, click_count, window, cx);
 2932
 2933        let position = position.to_offset(&display_map, Bias::Left);
 2934        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2935
 2936        let mut pending_selection = self
 2937            .selections
 2938            .pending_anchor()
 2939            .expect("extend_selection not called with pending selection");
 2940        if position >= tail {
 2941            pending_selection.start = tail_anchor;
 2942        } else {
 2943            pending_selection.end = tail_anchor;
 2944            pending_selection.reversed = true;
 2945        }
 2946
 2947        let mut pending_mode = self.selections.pending_mode().unwrap();
 2948        match &mut pending_mode {
 2949            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2950            _ => {}
 2951        }
 2952
 2953        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 2954
 2955        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 2956            s.set_pending(pending_selection, pending_mode)
 2957        });
 2958    }
 2959
 2960    fn begin_selection(
 2961        &mut self,
 2962        position: DisplayPoint,
 2963        add: bool,
 2964        click_count: usize,
 2965        window: &mut Window,
 2966        cx: &mut Context<Self>,
 2967    ) {
 2968        if !self.focus_handle.is_focused(window) {
 2969            self.last_focused_descendant = None;
 2970            window.focus(&self.focus_handle);
 2971        }
 2972
 2973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2974        let buffer = &display_map.buffer_snapshot;
 2975        let position = display_map.clip_point(position, Bias::Left);
 2976
 2977        let start;
 2978        let end;
 2979        let mode;
 2980        let mut auto_scroll;
 2981        match click_count {
 2982            1 => {
 2983                start = buffer.anchor_before(position.to_point(&display_map));
 2984                end = start;
 2985                mode = SelectMode::Character;
 2986                auto_scroll = true;
 2987            }
 2988            2 => {
 2989                let range = movement::surrounding_word(&display_map, position);
 2990                start = buffer.anchor_before(range.start.to_point(&display_map));
 2991                end = buffer.anchor_before(range.end.to_point(&display_map));
 2992                mode = SelectMode::Word(start..end);
 2993                auto_scroll = true;
 2994            }
 2995            3 => {
 2996                let position = display_map
 2997                    .clip_point(position, Bias::Left)
 2998                    .to_point(&display_map);
 2999                let line_start = display_map.prev_line_boundary(position).0;
 3000                let next_line_start = buffer.clip_point(
 3001                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3002                    Bias::Left,
 3003                );
 3004                start = buffer.anchor_before(line_start);
 3005                end = buffer.anchor_before(next_line_start);
 3006                mode = SelectMode::Line(start..end);
 3007                auto_scroll = true;
 3008            }
 3009            _ => {
 3010                start = buffer.anchor_before(0);
 3011                end = buffer.anchor_before(buffer.len());
 3012                mode = SelectMode::All;
 3013                auto_scroll = false;
 3014            }
 3015        }
 3016        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3017
 3018        let point_to_delete: Option<usize> = {
 3019            let selected_points: Vec<Selection<Point>> =
 3020                self.selections.disjoint_in_range(start..end, cx);
 3021
 3022            if !add || click_count > 1 {
 3023                None
 3024            } else if !selected_points.is_empty() {
 3025                Some(selected_points[0].id)
 3026            } else {
 3027                let clicked_point_already_selected =
 3028                    self.selections.disjoint.iter().find(|selection| {
 3029                        selection.start.to_point(buffer) == start.to_point(buffer)
 3030                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3031                    });
 3032
 3033                clicked_point_already_selected.map(|selection| selection.id)
 3034            }
 3035        };
 3036
 3037        let selections_count = self.selections.count();
 3038
 3039        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3040            if let Some(point_to_delete) = point_to_delete {
 3041                s.delete(point_to_delete);
 3042
 3043                if selections_count == 1 {
 3044                    s.set_pending_anchor_range(start..end, mode);
 3045                }
 3046            } else {
 3047                if !add {
 3048                    s.clear_disjoint();
 3049                }
 3050
 3051                s.set_pending_anchor_range(start..end, mode);
 3052            }
 3053        });
 3054    }
 3055
 3056    fn begin_columnar_selection(
 3057        &mut self,
 3058        position: DisplayPoint,
 3059        goal_column: u32,
 3060        reset: bool,
 3061        window: &mut Window,
 3062        cx: &mut Context<Self>,
 3063    ) {
 3064        if !self.focus_handle.is_focused(window) {
 3065            self.last_focused_descendant = None;
 3066            window.focus(&self.focus_handle);
 3067        }
 3068
 3069        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3070
 3071        if reset {
 3072            let pointer_position = display_map
 3073                .buffer_snapshot
 3074                .anchor_before(position.to_point(&display_map));
 3075
 3076            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3077                s.clear_disjoint();
 3078                s.set_pending_anchor_range(
 3079                    pointer_position..pointer_position,
 3080                    SelectMode::Character,
 3081                );
 3082            });
 3083        }
 3084
 3085        let tail = self.selections.newest::<Point>(cx).tail();
 3086        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3087
 3088        if !reset {
 3089            self.select_columns(
 3090                tail.to_display_point(&display_map),
 3091                position,
 3092                goal_column,
 3093                &display_map,
 3094                window,
 3095                cx,
 3096            );
 3097        }
 3098    }
 3099
 3100    fn update_selection(
 3101        &mut self,
 3102        position: DisplayPoint,
 3103        goal_column: u32,
 3104        scroll_delta: gpui::Point<f32>,
 3105        window: &mut Window,
 3106        cx: &mut Context<Self>,
 3107    ) {
 3108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3109
 3110        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3111            let tail = tail.to_display_point(&display_map);
 3112            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3113        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3114            let buffer = self.buffer.read(cx).snapshot(cx);
 3115            let head;
 3116            let tail;
 3117            let mode = self.selections.pending_mode().unwrap();
 3118            match &mode {
 3119                SelectMode::Character => {
 3120                    head = position.to_point(&display_map);
 3121                    tail = pending.tail().to_point(&buffer);
 3122                }
 3123                SelectMode::Word(original_range) => {
 3124                    let original_display_range = original_range.start.to_display_point(&display_map)
 3125                        ..original_range.end.to_display_point(&display_map);
 3126                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3127                        ..original_display_range.end.to_point(&display_map);
 3128                    if movement::is_inside_word(&display_map, position)
 3129                        || original_display_range.contains(&position)
 3130                    {
 3131                        let word_range = movement::surrounding_word(&display_map, position);
 3132                        if word_range.start < original_display_range.start {
 3133                            head = word_range.start.to_point(&display_map);
 3134                        } else {
 3135                            head = word_range.end.to_point(&display_map);
 3136                        }
 3137                    } else {
 3138                        head = position.to_point(&display_map);
 3139                    }
 3140
 3141                    if head <= original_buffer_range.start {
 3142                        tail = original_buffer_range.end;
 3143                    } else {
 3144                        tail = original_buffer_range.start;
 3145                    }
 3146                }
 3147                SelectMode::Line(original_range) => {
 3148                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3149
 3150                    let position = display_map
 3151                        .clip_point(position, Bias::Left)
 3152                        .to_point(&display_map);
 3153                    let line_start = display_map.prev_line_boundary(position).0;
 3154                    let next_line_start = buffer.clip_point(
 3155                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3156                        Bias::Left,
 3157                    );
 3158
 3159                    if line_start < original_range.start {
 3160                        head = line_start
 3161                    } else {
 3162                        head = next_line_start
 3163                    }
 3164
 3165                    if head <= original_range.start {
 3166                        tail = original_range.end;
 3167                    } else {
 3168                        tail = original_range.start;
 3169                    }
 3170                }
 3171                SelectMode::All => {
 3172                    return;
 3173                }
 3174            };
 3175
 3176            if head < tail {
 3177                pending.start = buffer.anchor_before(head);
 3178                pending.end = buffer.anchor_before(tail);
 3179                pending.reversed = true;
 3180            } else {
 3181                pending.start = buffer.anchor_before(tail);
 3182                pending.end = buffer.anchor_before(head);
 3183                pending.reversed = false;
 3184            }
 3185
 3186            self.change_selections(None, window, cx, |s| {
 3187                s.set_pending(pending, mode);
 3188            });
 3189        } else {
 3190            log::error!("update_selection dispatched with no pending selection");
 3191            return;
 3192        }
 3193
 3194        self.apply_scroll_delta(scroll_delta, window, cx);
 3195        cx.notify();
 3196    }
 3197
 3198    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3199        self.columnar_selection_tail.take();
 3200        if self.selections.pending_anchor().is_some() {
 3201            let selections = self.selections.all::<usize>(cx);
 3202            self.change_selections(None, window, cx, |s| {
 3203                s.select(selections);
 3204                s.clear_pending();
 3205            });
 3206        }
 3207    }
 3208
 3209    fn select_columns(
 3210        &mut self,
 3211        tail: DisplayPoint,
 3212        head: DisplayPoint,
 3213        goal_column: u32,
 3214        display_map: &DisplaySnapshot,
 3215        window: &mut Window,
 3216        cx: &mut Context<Self>,
 3217    ) {
 3218        let start_row = cmp::min(tail.row(), head.row());
 3219        let end_row = cmp::max(tail.row(), head.row());
 3220        let start_column = cmp::min(tail.column(), goal_column);
 3221        let end_column = cmp::max(tail.column(), goal_column);
 3222        let reversed = start_column < tail.column();
 3223
 3224        let selection_ranges = (start_row.0..=end_row.0)
 3225            .map(DisplayRow)
 3226            .filter_map(|row| {
 3227                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3228                    let start = display_map
 3229                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3230                        .to_point(display_map);
 3231                    let end = display_map
 3232                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3233                        .to_point(display_map);
 3234                    if reversed {
 3235                        Some(end..start)
 3236                    } else {
 3237                        Some(start..end)
 3238                    }
 3239                } else {
 3240                    None
 3241                }
 3242            })
 3243            .collect::<Vec<_>>();
 3244
 3245        self.change_selections(None, window, cx, |s| {
 3246            s.select_ranges(selection_ranges);
 3247        });
 3248        cx.notify();
 3249    }
 3250
 3251    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3252        self.selections
 3253            .all_adjusted(cx)
 3254            .iter()
 3255            .any(|selection| !selection.is_empty())
 3256    }
 3257
 3258    pub fn has_pending_nonempty_selection(&self) -> bool {
 3259        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3260            Some(Selection { start, end, .. }) => start != end,
 3261            None => false,
 3262        };
 3263
 3264        pending_nonempty_selection
 3265            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3266    }
 3267
 3268    pub fn has_pending_selection(&self) -> bool {
 3269        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3270    }
 3271
 3272    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3273        self.selection_mark_mode = false;
 3274
 3275        if self.clear_expanded_diff_hunks(cx) {
 3276            cx.notify();
 3277            return;
 3278        }
 3279        if self.dismiss_menus_and_popups(true, window, cx) {
 3280            return;
 3281        }
 3282
 3283        if self.mode.is_full()
 3284            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3285        {
 3286            return;
 3287        }
 3288
 3289        cx.propagate();
 3290    }
 3291
 3292    pub fn dismiss_menus_and_popups(
 3293        &mut self,
 3294        is_user_requested: bool,
 3295        window: &mut Window,
 3296        cx: &mut Context<Self>,
 3297    ) -> bool {
 3298        if self.take_rename(false, window, cx).is_some() {
 3299            return true;
 3300        }
 3301
 3302        if hide_hover(self, cx) {
 3303            return true;
 3304        }
 3305
 3306        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3307            return true;
 3308        }
 3309
 3310        if self.hide_context_menu(window, cx).is_some() {
 3311            return true;
 3312        }
 3313
 3314        if self.mouse_context_menu.take().is_some() {
 3315            return true;
 3316        }
 3317
 3318        if is_user_requested && self.discard_inline_completion(true, cx) {
 3319            return true;
 3320        }
 3321
 3322        if self.snippet_stack.pop().is_some() {
 3323            return true;
 3324        }
 3325
 3326        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3327            self.dismiss_diagnostics(cx);
 3328            return true;
 3329        }
 3330
 3331        false
 3332    }
 3333
 3334    fn linked_editing_ranges_for(
 3335        &self,
 3336        selection: Range<text::Anchor>,
 3337        cx: &App,
 3338    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3339        if self.linked_edit_ranges.is_empty() {
 3340            return None;
 3341        }
 3342        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3343            selection.end.buffer_id.and_then(|end_buffer_id| {
 3344                if selection.start.buffer_id != Some(end_buffer_id) {
 3345                    return None;
 3346                }
 3347                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3348                let snapshot = buffer.read(cx).snapshot();
 3349                self.linked_edit_ranges
 3350                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3351                    .map(|ranges| (ranges, snapshot, buffer))
 3352            })?;
 3353        use text::ToOffset as TO;
 3354        // find offset from the start of current range to current cursor position
 3355        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3356
 3357        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3358        let start_difference = start_offset - start_byte_offset;
 3359        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3360        let end_difference = end_offset - start_byte_offset;
 3361        // Current range has associated linked ranges.
 3362        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3363        for range in linked_ranges.iter() {
 3364            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3365            let end_offset = start_offset + end_difference;
 3366            let start_offset = start_offset + start_difference;
 3367            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3368                continue;
 3369            }
 3370            if self.selections.disjoint_anchor_ranges().any(|s| {
 3371                if s.start.buffer_id != selection.start.buffer_id
 3372                    || s.end.buffer_id != selection.end.buffer_id
 3373                {
 3374                    return false;
 3375                }
 3376                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3377                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3378            }) {
 3379                continue;
 3380            }
 3381            let start = buffer_snapshot.anchor_after(start_offset);
 3382            let end = buffer_snapshot.anchor_after(end_offset);
 3383            linked_edits
 3384                .entry(buffer.clone())
 3385                .or_default()
 3386                .push(start..end);
 3387        }
 3388        Some(linked_edits)
 3389    }
 3390
 3391    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3392        let text: Arc<str> = text.into();
 3393
 3394        if self.read_only(cx) {
 3395            return;
 3396        }
 3397
 3398        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3399
 3400        let selections = self.selections.all_adjusted(cx);
 3401        let mut bracket_inserted = false;
 3402        let mut edits = Vec::new();
 3403        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3404        let mut new_selections = Vec::with_capacity(selections.len());
 3405        let mut new_autoclose_regions = Vec::new();
 3406        let snapshot = self.buffer.read(cx).read(cx);
 3407        let mut clear_linked_edit_ranges = false;
 3408
 3409        for (selection, autoclose_region) in
 3410            self.selections_with_autoclose_regions(selections, &snapshot)
 3411        {
 3412            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3413                // Determine if the inserted text matches the opening or closing
 3414                // bracket of any of this language's bracket pairs.
 3415                let mut bracket_pair = None;
 3416                let mut is_bracket_pair_start = false;
 3417                let mut is_bracket_pair_end = false;
 3418                if !text.is_empty() {
 3419                    let mut bracket_pair_matching_end = None;
 3420                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3421                    //  and they are removing the character that triggered IME popup.
 3422                    for (pair, enabled) in scope.brackets() {
 3423                        if !pair.close && !pair.surround {
 3424                            continue;
 3425                        }
 3426
 3427                        if enabled && pair.start.ends_with(text.as_ref()) {
 3428                            let prefix_len = pair.start.len() - text.len();
 3429                            let preceding_text_matches_prefix = prefix_len == 0
 3430                                || (selection.start.column >= (prefix_len as u32)
 3431                                    && snapshot.contains_str_at(
 3432                                        Point::new(
 3433                                            selection.start.row,
 3434                                            selection.start.column - (prefix_len as u32),
 3435                                        ),
 3436                                        &pair.start[..prefix_len],
 3437                                    ));
 3438                            if preceding_text_matches_prefix {
 3439                                bracket_pair = Some(pair.clone());
 3440                                is_bracket_pair_start = true;
 3441                                break;
 3442                            }
 3443                        }
 3444                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3445                        {
 3446                            // take first bracket pair matching end, but don't break in case a later bracket
 3447                            // pair matches start
 3448                            bracket_pair_matching_end = Some(pair.clone());
 3449                        }
 3450                    }
 3451                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3452                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3453                        is_bracket_pair_end = true;
 3454                    }
 3455                }
 3456
 3457                if let Some(bracket_pair) = bracket_pair {
 3458                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3459                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3460                    let auto_surround =
 3461                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3462                    if selection.is_empty() {
 3463                        if is_bracket_pair_start {
 3464                            // If the inserted text is a suffix of an opening bracket and the
 3465                            // selection is preceded by the rest of the opening bracket, then
 3466                            // insert the closing bracket.
 3467                            let following_text_allows_autoclose = snapshot
 3468                                .chars_at(selection.start)
 3469                                .next()
 3470                                .map_or(true, |c| scope.should_autoclose_before(c));
 3471
 3472                            let preceding_text_allows_autoclose = selection.start.column == 0
 3473                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3474                                    true,
 3475                                    |c| {
 3476                                        bracket_pair.start != bracket_pair.end
 3477                                            || !snapshot
 3478                                                .char_classifier_at(selection.start)
 3479                                                .is_word(c)
 3480                                    },
 3481                                );
 3482
 3483                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3484                                && bracket_pair.start.len() == 1
 3485                            {
 3486                                let target = bracket_pair.start.chars().next().unwrap();
 3487                                let current_line_count = snapshot
 3488                                    .reversed_chars_at(selection.start)
 3489                                    .take_while(|&c| c != '\n')
 3490                                    .filter(|&c| c == target)
 3491                                    .count();
 3492                                current_line_count % 2 == 1
 3493                            } else {
 3494                                false
 3495                            };
 3496
 3497                            if autoclose
 3498                                && bracket_pair.close
 3499                                && following_text_allows_autoclose
 3500                                && preceding_text_allows_autoclose
 3501                                && !is_closing_quote
 3502                            {
 3503                                let anchor = snapshot.anchor_before(selection.end);
 3504                                new_selections.push((selection.map(|_| anchor), text.len()));
 3505                                new_autoclose_regions.push((
 3506                                    anchor,
 3507                                    text.len(),
 3508                                    selection.id,
 3509                                    bracket_pair.clone(),
 3510                                ));
 3511                                edits.push((
 3512                                    selection.range(),
 3513                                    format!("{}{}", text, bracket_pair.end).into(),
 3514                                ));
 3515                                bracket_inserted = true;
 3516                                continue;
 3517                            }
 3518                        }
 3519
 3520                        if let Some(region) = autoclose_region {
 3521                            // If the selection is followed by an auto-inserted closing bracket,
 3522                            // then don't insert that closing bracket again; just move the selection
 3523                            // past the closing bracket.
 3524                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3525                                && text.as_ref() == region.pair.end.as_str();
 3526                            if should_skip {
 3527                                let anchor = snapshot.anchor_after(selection.end);
 3528                                new_selections
 3529                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3530                                continue;
 3531                            }
 3532                        }
 3533
 3534                        let always_treat_brackets_as_autoclosed = snapshot
 3535                            .language_settings_at(selection.start, cx)
 3536                            .always_treat_brackets_as_autoclosed;
 3537                        if always_treat_brackets_as_autoclosed
 3538                            && is_bracket_pair_end
 3539                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3540                        {
 3541                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3542                            // and the inserted text is a closing bracket and the selection is followed
 3543                            // by the closing bracket then move the selection past the closing bracket.
 3544                            let anchor = snapshot.anchor_after(selection.end);
 3545                            new_selections.push((selection.map(|_| anchor), text.len()));
 3546                            continue;
 3547                        }
 3548                    }
 3549                    // If an opening bracket is 1 character long and is typed while
 3550                    // text is selected, then surround that text with the bracket pair.
 3551                    else if auto_surround
 3552                        && bracket_pair.surround
 3553                        && is_bracket_pair_start
 3554                        && bracket_pair.start.chars().count() == 1
 3555                    {
 3556                        edits.push((selection.start..selection.start, text.clone()));
 3557                        edits.push((
 3558                            selection.end..selection.end,
 3559                            bracket_pair.end.as_str().into(),
 3560                        ));
 3561                        bracket_inserted = true;
 3562                        new_selections.push((
 3563                            Selection {
 3564                                id: selection.id,
 3565                                start: snapshot.anchor_after(selection.start),
 3566                                end: snapshot.anchor_before(selection.end),
 3567                                reversed: selection.reversed,
 3568                                goal: selection.goal,
 3569                            },
 3570                            0,
 3571                        ));
 3572                        continue;
 3573                    }
 3574                }
 3575            }
 3576
 3577            if self.auto_replace_emoji_shortcode
 3578                && selection.is_empty()
 3579                && text.as_ref().ends_with(':')
 3580            {
 3581                if let Some(possible_emoji_short_code) =
 3582                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3583                {
 3584                    if !possible_emoji_short_code.is_empty() {
 3585                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3586                            let emoji_shortcode_start = Point::new(
 3587                                selection.start.row,
 3588                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3589                            );
 3590
 3591                            // Remove shortcode from buffer
 3592                            edits.push((
 3593                                emoji_shortcode_start..selection.start,
 3594                                "".to_string().into(),
 3595                            ));
 3596                            new_selections.push((
 3597                                Selection {
 3598                                    id: selection.id,
 3599                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3600                                    end: snapshot.anchor_before(selection.start),
 3601                                    reversed: selection.reversed,
 3602                                    goal: selection.goal,
 3603                                },
 3604                                0,
 3605                            ));
 3606
 3607                            // Insert emoji
 3608                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3609                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3610                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3611
 3612                            continue;
 3613                        }
 3614                    }
 3615                }
 3616            }
 3617
 3618            // If not handling any auto-close operation, then just replace the selected
 3619            // text with the given input and move the selection to the end of the
 3620            // newly inserted text.
 3621            let anchor = snapshot.anchor_after(selection.end);
 3622            if !self.linked_edit_ranges.is_empty() {
 3623                let start_anchor = snapshot.anchor_before(selection.start);
 3624
 3625                let is_word_char = text.chars().next().map_or(true, |char| {
 3626                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3627                    classifier.is_word(char)
 3628                });
 3629
 3630                if is_word_char {
 3631                    if let Some(ranges) = self
 3632                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3633                    {
 3634                        for (buffer, edits) in ranges {
 3635                            linked_edits
 3636                                .entry(buffer.clone())
 3637                                .or_default()
 3638                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3639                        }
 3640                    }
 3641                } else {
 3642                    clear_linked_edit_ranges = true;
 3643                }
 3644            }
 3645
 3646            new_selections.push((selection.map(|_| anchor), 0));
 3647            edits.push((selection.start..selection.end, text.clone()));
 3648        }
 3649
 3650        drop(snapshot);
 3651
 3652        self.transact(window, cx, |this, window, cx| {
 3653            if clear_linked_edit_ranges {
 3654                this.linked_edit_ranges.clear();
 3655            }
 3656            let initial_buffer_versions =
 3657                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3658
 3659            this.buffer.update(cx, |buffer, cx| {
 3660                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3661            });
 3662            for (buffer, edits) in linked_edits {
 3663                buffer.update(cx, |buffer, cx| {
 3664                    let snapshot = buffer.snapshot();
 3665                    let edits = edits
 3666                        .into_iter()
 3667                        .map(|(range, text)| {
 3668                            use text::ToPoint as TP;
 3669                            let end_point = TP::to_point(&range.end, &snapshot);
 3670                            let start_point = TP::to_point(&range.start, &snapshot);
 3671                            (start_point..end_point, text)
 3672                        })
 3673                        .sorted_by_key(|(range, _)| range.start);
 3674                    buffer.edit(edits, None, cx);
 3675                })
 3676            }
 3677            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3678            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3679            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3680            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3681                .zip(new_selection_deltas)
 3682                .map(|(selection, delta)| Selection {
 3683                    id: selection.id,
 3684                    start: selection.start + delta,
 3685                    end: selection.end + delta,
 3686                    reversed: selection.reversed,
 3687                    goal: SelectionGoal::None,
 3688                })
 3689                .collect::<Vec<_>>();
 3690
 3691            let mut i = 0;
 3692            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3693                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3694                let start = map.buffer_snapshot.anchor_before(position);
 3695                let end = map.buffer_snapshot.anchor_after(position);
 3696                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3697                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3698                        Ordering::Less => i += 1,
 3699                        Ordering::Greater => break,
 3700                        Ordering::Equal => {
 3701                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3702                                Ordering::Less => i += 1,
 3703                                Ordering::Equal => break,
 3704                                Ordering::Greater => break,
 3705                            }
 3706                        }
 3707                    }
 3708                }
 3709                this.autoclose_regions.insert(
 3710                    i,
 3711                    AutocloseRegion {
 3712                        selection_id,
 3713                        range: start..end,
 3714                        pair,
 3715                    },
 3716                );
 3717            }
 3718
 3719            let had_active_inline_completion = this.has_active_inline_completion();
 3720            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3721                s.select(new_selections)
 3722            });
 3723
 3724            if !bracket_inserted {
 3725                if let Some(on_type_format_task) =
 3726                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3727                {
 3728                    on_type_format_task.detach_and_log_err(cx);
 3729                }
 3730            }
 3731
 3732            let editor_settings = EditorSettings::get_global(cx);
 3733            if bracket_inserted
 3734                && (editor_settings.auto_signature_help
 3735                    || editor_settings.show_signature_help_after_edits)
 3736            {
 3737                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3738            }
 3739
 3740            let trigger_in_words =
 3741                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3742            if this.hard_wrap.is_some() {
 3743                let latest: Range<Point> = this.selections.newest(cx).range();
 3744                if latest.is_empty()
 3745                    && this
 3746                        .buffer()
 3747                        .read(cx)
 3748                        .snapshot(cx)
 3749                        .line_len(MultiBufferRow(latest.start.row))
 3750                        == latest.start.column
 3751                {
 3752                    this.rewrap_impl(
 3753                        RewrapOptions {
 3754                            override_language_settings: true,
 3755                            preserve_existing_whitespace: true,
 3756                        },
 3757                        cx,
 3758                    )
 3759                }
 3760            }
 3761            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3762            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3763            this.refresh_inline_completion(true, false, window, cx);
 3764            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3765        });
 3766    }
 3767
 3768    fn find_possible_emoji_shortcode_at_position(
 3769        snapshot: &MultiBufferSnapshot,
 3770        position: Point,
 3771    ) -> Option<String> {
 3772        let mut chars = Vec::new();
 3773        let mut found_colon = false;
 3774        for char in snapshot.reversed_chars_at(position).take(100) {
 3775            // Found a possible emoji shortcode in the middle of the buffer
 3776            if found_colon {
 3777                if char.is_whitespace() {
 3778                    chars.reverse();
 3779                    return Some(chars.iter().collect());
 3780                }
 3781                // If the previous character is not a whitespace, we are in the middle of a word
 3782                // and we only want to complete the shortcode if the word is made up of other emojis
 3783                let mut containing_word = String::new();
 3784                for ch in snapshot
 3785                    .reversed_chars_at(position)
 3786                    .skip(chars.len() + 1)
 3787                    .take(100)
 3788                {
 3789                    if ch.is_whitespace() {
 3790                        break;
 3791                    }
 3792                    containing_word.push(ch);
 3793                }
 3794                let containing_word = containing_word.chars().rev().collect::<String>();
 3795                if util::word_consists_of_emojis(containing_word.as_str()) {
 3796                    chars.reverse();
 3797                    return Some(chars.iter().collect());
 3798                }
 3799            }
 3800
 3801            if char.is_whitespace() || !char.is_ascii() {
 3802                return None;
 3803            }
 3804            if char == ':' {
 3805                found_colon = true;
 3806            } else {
 3807                chars.push(char);
 3808            }
 3809        }
 3810        // Found a possible emoji shortcode at the beginning of the buffer
 3811        chars.reverse();
 3812        Some(chars.iter().collect())
 3813    }
 3814
 3815    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3816        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3817        self.transact(window, cx, |this, window, cx| {
 3818            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3819                let selections = this.selections.all::<usize>(cx);
 3820                let multi_buffer = this.buffer.read(cx);
 3821                let buffer = multi_buffer.snapshot(cx);
 3822                selections
 3823                    .iter()
 3824                    .map(|selection| {
 3825                        let start_point = selection.start.to_point(&buffer);
 3826                        let mut indent =
 3827                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3828                        indent.len = cmp::min(indent.len, start_point.column);
 3829                        let start = selection.start;
 3830                        let end = selection.end;
 3831                        let selection_is_empty = start == end;
 3832                        let language_scope = buffer.language_scope_at(start);
 3833                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3834                            &language_scope
 3835                        {
 3836                            let insert_extra_newline =
 3837                                insert_extra_newline_brackets(&buffer, start..end, language)
 3838                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3839
 3840                            // Comment extension on newline is allowed only for cursor selections
 3841                            let comment_delimiter = maybe!({
 3842                                if !selection_is_empty {
 3843                                    return None;
 3844                                }
 3845
 3846                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3847                                    return None;
 3848                                }
 3849
 3850                                let delimiters = language.line_comment_prefixes();
 3851                                let max_len_of_delimiter =
 3852                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3853                                let (snapshot, range) =
 3854                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3855
 3856                                let mut index_of_first_non_whitespace = 0;
 3857                                let comment_candidate = snapshot
 3858                                    .chars_for_range(range)
 3859                                    .skip_while(|c| {
 3860                                        let should_skip = c.is_whitespace();
 3861                                        if should_skip {
 3862                                            index_of_first_non_whitespace += 1;
 3863                                        }
 3864                                        should_skip
 3865                                    })
 3866                                    .take(max_len_of_delimiter)
 3867                                    .collect::<String>();
 3868                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3869                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3870                                })?;
 3871                                let cursor_is_placed_after_comment_marker =
 3872                                    index_of_first_non_whitespace + comment_prefix.len()
 3873                                        <= start_point.column as usize;
 3874                                if cursor_is_placed_after_comment_marker {
 3875                                    Some(comment_prefix.clone())
 3876                                } else {
 3877                                    None
 3878                                }
 3879                            });
 3880                            (comment_delimiter, insert_extra_newline)
 3881                        } else {
 3882                            (None, false)
 3883                        };
 3884
 3885                        let capacity_for_delimiter = comment_delimiter
 3886                            .as_deref()
 3887                            .map(str::len)
 3888                            .unwrap_or_default();
 3889                        let mut new_text =
 3890                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3891                        new_text.push('\n');
 3892                        new_text.extend(indent.chars());
 3893                        if let Some(delimiter) = &comment_delimiter {
 3894                            new_text.push_str(delimiter);
 3895                        }
 3896                        if insert_extra_newline {
 3897                            new_text = new_text.repeat(2);
 3898                        }
 3899
 3900                        let anchor = buffer.anchor_after(end);
 3901                        let new_selection = selection.map(|_| anchor);
 3902                        (
 3903                            (start..end, new_text),
 3904                            (insert_extra_newline, new_selection),
 3905                        )
 3906                    })
 3907                    .unzip()
 3908            };
 3909
 3910            this.edit_with_autoindent(edits, cx);
 3911            let buffer = this.buffer.read(cx).snapshot(cx);
 3912            let new_selections = selection_fixup_info
 3913                .into_iter()
 3914                .map(|(extra_newline_inserted, new_selection)| {
 3915                    let mut cursor = new_selection.end.to_point(&buffer);
 3916                    if extra_newline_inserted {
 3917                        cursor.row -= 1;
 3918                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3919                    }
 3920                    new_selection.map(|_| cursor)
 3921                })
 3922                .collect();
 3923
 3924            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3925                s.select(new_selections)
 3926            });
 3927            this.refresh_inline_completion(true, false, window, cx);
 3928        });
 3929    }
 3930
 3931    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3932        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3933
 3934        let buffer = self.buffer.read(cx);
 3935        let snapshot = buffer.snapshot(cx);
 3936
 3937        let mut edits = Vec::new();
 3938        let mut rows = Vec::new();
 3939
 3940        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3941            let cursor = selection.head();
 3942            let row = cursor.row;
 3943
 3944            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3945
 3946            let newline = "\n".to_string();
 3947            edits.push((start_of_line..start_of_line, newline));
 3948
 3949            rows.push(row + rows_inserted as u32);
 3950        }
 3951
 3952        self.transact(window, cx, |editor, window, cx| {
 3953            editor.edit(edits, cx);
 3954
 3955            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3956                let mut index = 0;
 3957                s.move_cursors_with(|map, _, _| {
 3958                    let row = rows[index];
 3959                    index += 1;
 3960
 3961                    let point = Point::new(row, 0);
 3962                    let boundary = map.next_line_boundary(point).1;
 3963                    let clipped = map.clip_point(boundary, Bias::Left);
 3964
 3965                    (clipped, SelectionGoal::None)
 3966                });
 3967            });
 3968
 3969            let mut indent_edits = Vec::new();
 3970            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3971            for row in rows {
 3972                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3973                for (row, indent) in indents {
 3974                    if indent.len == 0 {
 3975                        continue;
 3976                    }
 3977
 3978                    let text = match indent.kind {
 3979                        IndentKind::Space => " ".repeat(indent.len as usize),
 3980                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3981                    };
 3982                    let point = Point::new(row.0, 0);
 3983                    indent_edits.push((point..point, text));
 3984                }
 3985            }
 3986            editor.edit(indent_edits, cx);
 3987        });
 3988    }
 3989
 3990    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3991        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3992
 3993        let buffer = self.buffer.read(cx);
 3994        let snapshot = buffer.snapshot(cx);
 3995
 3996        let mut edits = Vec::new();
 3997        let mut rows = Vec::new();
 3998        let mut rows_inserted = 0;
 3999
 4000        for selection in self.selections.all_adjusted(cx) {
 4001            let cursor = selection.head();
 4002            let row = cursor.row;
 4003
 4004            let point = Point::new(row + 1, 0);
 4005            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4006
 4007            let newline = "\n".to_string();
 4008            edits.push((start_of_line..start_of_line, newline));
 4009
 4010            rows_inserted += 1;
 4011            rows.push(row + rows_inserted);
 4012        }
 4013
 4014        self.transact(window, cx, |editor, window, cx| {
 4015            editor.edit(edits, cx);
 4016
 4017            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4018                let mut index = 0;
 4019                s.move_cursors_with(|map, _, _| {
 4020                    let row = rows[index];
 4021                    index += 1;
 4022
 4023                    let point = Point::new(row, 0);
 4024                    let boundary = map.next_line_boundary(point).1;
 4025                    let clipped = map.clip_point(boundary, Bias::Left);
 4026
 4027                    (clipped, SelectionGoal::None)
 4028                });
 4029            });
 4030
 4031            let mut indent_edits = Vec::new();
 4032            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4033            for row in rows {
 4034                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4035                for (row, indent) in indents {
 4036                    if indent.len == 0 {
 4037                        continue;
 4038                    }
 4039
 4040                    let text = match indent.kind {
 4041                        IndentKind::Space => " ".repeat(indent.len as usize),
 4042                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4043                    };
 4044                    let point = Point::new(row.0, 0);
 4045                    indent_edits.push((point..point, text));
 4046                }
 4047            }
 4048            editor.edit(indent_edits, cx);
 4049        });
 4050    }
 4051
 4052    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4053        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4054            original_indent_columns: Vec::new(),
 4055        });
 4056        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4057    }
 4058
 4059    fn insert_with_autoindent_mode(
 4060        &mut self,
 4061        text: &str,
 4062        autoindent_mode: Option<AutoindentMode>,
 4063        window: &mut Window,
 4064        cx: &mut Context<Self>,
 4065    ) {
 4066        if self.read_only(cx) {
 4067            return;
 4068        }
 4069
 4070        let text: Arc<str> = text.into();
 4071        self.transact(window, cx, |this, window, cx| {
 4072            let old_selections = this.selections.all_adjusted(cx);
 4073            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4074                let anchors = {
 4075                    let snapshot = buffer.read(cx);
 4076                    old_selections
 4077                        .iter()
 4078                        .map(|s| {
 4079                            let anchor = snapshot.anchor_after(s.head());
 4080                            s.map(|_| anchor)
 4081                        })
 4082                        .collect::<Vec<_>>()
 4083                };
 4084                buffer.edit(
 4085                    old_selections
 4086                        .iter()
 4087                        .map(|s| (s.start..s.end, text.clone())),
 4088                    autoindent_mode,
 4089                    cx,
 4090                );
 4091                anchors
 4092            });
 4093
 4094            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4095                s.select_anchors(selection_anchors);
 4096            });
 4097
 4098            cx.notify();
 4099        });
 4100    }
 4101
 4102    fn trigger_completion_on_input(
 4103        &mut self,
 4104        text: &str,
 4105        trigger_in_words: bool,
 4106        window: &mut Window,
 4107        cx: &mut Context<Self>,
 4108    ) {
 4109        let ignore_completion_provider = self
 4110            .context_menu
 4111            .borrow()
 4112            .as_ref()
 4113            .map(|menu| match menu {
 4114                CodeContextMenu::Completions(completions_menu) => {
 4115                    completions_menu.ignore_completion_provider
 4116                }
 4117                CodeContextMenu::CodeActions(_) => false,
 4118            })
 4119            .unwrap_or(false);
 4120
 4121        if ignore_completion_provider {
 4122            self.show_word_completions(&ShowWordCompletions, window, cx);
 4123        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4124            self.show_completions(
 4125                &ShowCompletions {
 4126                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4127                },
 4128                window,
 4129                cx,
 4130            );
 4131        } else {
 4132            self.hide_context_menu(window, cx);
 4133        }
 4134    }
 4135
 4136    fn is_completion_trigger(
 4137        &self,
 4138        text: &str,
 4139        trigger_in_words: bool,
 4140        cx: &mut Context<Self>,
 4141    ) -> bool {
 4142        let position = self.selections.newest_anchor().head();
 4143        let multibuffer = self.buffer.read(cx);
 4144        let Some(buffer) = position
 4145            .buffer_id
 4146            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4147        else {
 4148            return false;
 4149        };
 4150
 4151        if let Some(completion_provider) = &self.completion_provider {
 4152            completion_provider.is_completion_trigger(
 4153                &buffer,
 4154                position.text_anchor,
 4155                text,
 4156                trigger_in_words,
 4157                cx,
 4158            )
 4159        } else {
 4160            false
 4161        }
 4162    }
 4163
 4164    /// If any empty selections is touching the start of its innermost containing autoclose
 4165    /// region, expand it to select the brackets.
 4166    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4167        let selections = self.selections.all::<usize>(cx);
 4168        let buffer = self.buffer.read(cx).read(cx);
 4169        let new_selections = self
 4170            .selections_with_autoclose_regions(selections, &buffer)
 4171            .map(|(mut selection, region)| {
 4172                if !selection.is_empty() {
 4173                    return selection;
 4174                }
 4175
 4176                if let Some(region) = region {
 4177                    let mut range = region.range.to_offset(&buffer);
 4178                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4179                        range.start -= region.pair.start.len();
 4180                        if buffer.contains_str_at(range.start, &region.pair.start)
 4181                            && buffer.contains_str_at(range.end, &region.pair.end)
 4182                        {
 4183                            range.end += region.pair.end.len();
 4184                            selection.start = range.start;
 4185                            selection.end = range.end;
 4186
 4187                            return selection;
 4188                        }
 4189                    }
 4190                }
 4191
 4192                let always_treat_brackets_as_autoclosed = buffer
 4193                    .language_settings_at(selection.start, cx)
 4194                    .always_treat_brackets_as_autoclosed;
 4195
 4196                if !always_treat_brackets_as_autoclosed {
 4197                    return selection;
 4198                }
 4199
 4200                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4201                    for (pair, enabled) in scope.brackets() {
 4202                        if !enabled || !pair.close {
 4203                            continue;
 4204                        }
 4205
 4206                        if buffer.contains_str_at(selection.start, &pair.end) {
 4207                            let pair_start_len = pair.start.len();
 4208                            if buffer.contains_str_at(
 4209                                selection.start.saturating_sub(pair_start_len),
 4210                                &pair.start,
 4211                            ) {
 4212                                selection.start -= pair_start_len;
 4213                                selection.end += pair.end.len();
 4214
 4215                                return selection;
 4216                            }
 4217                        }
 4218                    }
 4219                }
 4220
 4221                selection
 4222            })
 4223            .collect();
 4224
 4225        drop(buffer);
 4226        self.change_selections(None, window, cx, |selections| {
 4227            selections.select(new_selections)
 4228        });
 4229    }
 4230
 4231    /// Iterate the given selections, and for each one, find the smallest surrounding
 4232    /// autoclose region. This uses the ordering of the selections and the autoclose
 4233    /// regions to avoid repeated comparisons.
 4234    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4235        &'a self,
 4236        selections: impl IntoIterator<Item = Selection<D>>,
 4237        buffer: &'a MultiBufferSnapshot,
 4238    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4239        let mut i = 0;
 4240        let mut regions = self.autoclose_regions.as_slice();
 4241        selections.into_iter().map(move |selection| {
 4242            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4243
 4244            let mut enclosing = None;
 4245            while let Some(pair_state) = regions.get(i) {
 4246                if pair_state.range.end.to_offset(buffer) < range.start {
 4247                    regions = &regions[i + 1..];
 4248                    i = 0;
 4249                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4250                    break;
 4251                } else {
 4252                    if pair_state.selection_id == selection.id {
 4253                        enclosing = Some(pair_state);
 4254                    }
 4255                    i += 1;
 4256                }
 4257            }
 4258
 4259            (selection, enclosing)
 4260        })
 4261    }
 4262
 4263    /// Remove any autoclose regions that no longer contain their selection.
 4264    fn invalidate_autoclose_regions(
 4265        &mut self,
 4266        mut selections: &[Selection<Anchor>],
 4267        buffer: &MultiBufferSnapshot,
 4268    ) {
 4269        self.autoclose_regions.retain(|state| {
 4270            let mut i = 0;
 4271            while let Some(selection) = selections.get(i) {
 4272                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4273                    selections = &selections[1..];
 4274                    continue;
 4275                }
 4276                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4277                    break;
 4278                }
 4279                if selection.id == state.selection_id {
 4280                    return true;
 4281                } else {
 4282                    i += 1;
 4283                }
 4284            }
 4285            false
 4286        });
 4287    }
 4288
 4289    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4290        let offset = position.to_offset(buffer);
 4291        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4292        if offset > word_range.start && kind == Some(CharKind::Word) {
 4293            Some(
 4294                buffer
 4295                    .text_for_range(word_range.start..offset)
 4296                    .collect::<String>(),
 4297            )
 4298        } else {
 4299            None
 4300        }
 4301    }
 4302
 4303    pub fn toggle_inline_values(
 4304        &mut self,
 4305        _: &ToggleInlineValues,
 4306        _: &mut Window,
 4307        cx: &mut Context<Self>,
 4308    ) {
 4309        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4310
 4311        self.refresh_inline_values(cx);
 4312    }
 4313
 4314    pub fn toggle_inlay_hints(
 4315        &mut self,
 4316        _: &ToggleInlayHints,
 4317        _: &mut Window,
 4318        cx: &mut Context<Self>,
 4319    ) {
 4320        self.refresh_inlay_hints(
 4321            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4322            cx,
 4323        );
 4324    }
 4325
 4326    pub fn inlay_hints_enabled(&self) -> bool {
 4327        self.inlay_hint_cache.enabled
 4328    }
 4329
 4330    pub fn inline_values_enabled(&self) -> bool {
 4331        self.inline_value_cache.enabled
 4332    }
 4333
 4334    #[cfg(any(test, feature = "test-support"))]
 4335    pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
 4336        self.display_map
 4337            .read(cx)
 4338            .current_inlays()
 4339            .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
 4340            .cloned()
 4341            .collect()
 4342    }
 4343
 4344    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4345        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4346            return;
 4347        }
 4348
 4349        let reason_description = reason.description();
 4350        let ignore_debounce = matches!(
 4351            reason,
 4352            InlayHintRefreshReason::SettingsChange(_)
 4353                | InlayHintRefreshReason::Toggle(_)
 4354                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4355                | InlayHintRefreshReason::ModifiersChanged(_)
 4356        );
 4357        let (invalidate_cache, required_languages) = match reason {
 4358            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4359                match self.inlay_hint_cache.modifiers_override(enabled) {
 4360                    Some(enabled) => {
 4361                        if enabled {
 4362                            (InvalidationStrategy::RefreshRequested, None)
 4363                        } else {
 4364                            self.splice_inlays(
 4365                                &self
 4366                                    .visible_inlay_hints(cx)
 4367                                    .iter()
 4368                                    .map(|inlay| inlay.id)
 4369                                    .collect::<Vec<InlayId>>(),
 4370                                Vec::new(),
 4371                                cx,
 4372                            );
 4373                            return;
 4374                        }
 4375                    }
 4376                    None => return,
 4377                }
 4378            }
 4379            InlayHintRefreshReason::Toggle(enabled) => {
 4380                if self.inlay_hint_cache.toggle(enabled) {
 4381                    if enabled {
 4382                        (InvalidationStrategy::RefreshRequested, None)
 4383                    } else {
 4384                        self.splice_inlays(
 4385                            &self
 4386                                .visible_inlay_hints(cx)
 4387                                .iter()
 4388                                .map(|inlay| inlay.id)
 4389                                .collect::<Vec<InlayId>>(),
 4390                            Vec::new(),
 4391                            cx,
 4392                        );
 4393                        return;
 4394                    }
 4395                } else {
 4396                    return;
 4397                }
 4398            }
 4399            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4400                match self.inlay_hint_cache.update_settings(
 4401                    &self.buffer,
 4402                    new_settings,
 4403                    self.visible_inlay_hints(cx),
 4404                    cx,
 4405                ) {
 4406                    ControlFlow::Break(Some(InlaySplice {
 4407                        to_remove,
 4408                        to_insert,
 4409                    })) => {
 4410                        self.splice_inlays(&to_remove, to_insert, cx);
 4411                        return;
 4412                    }
 4413                    ControlFlow::Break(None) => return,
 4414                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4415                }
 4416            }
 4417            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4418                if let Some(InlaySplice {
 4419                    to_remove,
 4420                    to_insert,
 4421                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4422                {
 4423                    self.splice_inlays(&to_remove, to_insert, cx);
 4424                }
 4425                self.display_map.update(cx, |display_map, _| {
 4426                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4427                });
 4428                return;
 4429            }
 4430            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4431            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4432                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4433            }
 4434            InlayHintRefreshReason::RefreshRequested => {
 4435                (InvalidationStrategy::RefreshRequested, None)
 4436            }
 4437        };
 4438
 4439        if let Some(InlaySplice {
 4440            to_remove,
 4441            to_insert,
 4442        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4443            reason_description,
 4444            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4445            invalidate_cache,
 4446            ignore_debounce,
 4447            cx,
 4448        ) {
 4449            self.splice_inlays(&to_remove, to_insert, cx);
 4450        }
 4451    }
 4452
 4453    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4454        self.display_map
 4455            .read(cx)
 4456            .current_inlays()
 4457            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4458            .cloned()
 4459            .collect()
 4460    }
 4461
 4462    pub fn excerpts_for_inlay_hints_query(
 4463        &self,
 4464        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4465        cx: &mut Context<Editor>,
 4466    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4467        let Some(project) = self.project.as_ref() else {
 4468            return HashMap::default();
 4469        };
 4470        let project = project.read(cx);
 4471        let multi_buffer = self.buffer().read(cx);
 4472        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4473        let multi_buffer_visible_start = self
 4474            .scroll_manager
 4475            .anchor()
 4476            .anchor
 4477            .to_point(&multi_buffer_snapshot);
 4478        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4479            multi_buffer_visible_start
 4480                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4481            Bias::Left,
 4482        );
 4483        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4484        multi_buffer_snapshot
 4485            .range_to_buffer_ranges(multi_buffer_visible_range)
 4486            .into_iter()
 4487            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4488            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4489                let buffer_file = project::File::from_dyn(buffer.file())?;
 4490                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4491                let worktree_entry = buffer_worktree
 4492                    .read(cx)
 4493                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4494                if worktree_entry.is_ignored {
 4495                    return None;
 4496                }
 4497
 4498                let language = buffer.language()?;
 4499                if let Some(restrict_to_languages) = restrict_to_languages {
 4500                    if !restrict_to_languages.contains(language) {
 4501                        return None;
 4502                    }
 4503                }
 4504                Some((
 4505                    excerpt_id,
 4506                    (
 4507                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4508                        buffer.version().clone(),
 4509                        excerpt_visible_range,
 4510                    ),
 4511                ))
 4512            })
 4513            .collect()
 4514    }
 4515
 4516    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4517        TextLayoutDetails {
 4518            text_system: window.text_system().clone(),
 4519            editor_style: self.style.clone().unwrap(),
 4520            rem_size: window.rem_size(),
 4521            scroll_anchor: self.scroll_manager.anchor(),
 4522            visible_rows: self.visible_line_count(),
 4523            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4524        }
 4525    }
 4526
 4527    pub fn splice_inlays(
 4528        &self,
 4529        to_remove: &[InlayId],
 4530        to_insert: Vec<Inlay>,
 4531        cx: &mut Context<Self>,
 4532    ) {
 4533        self.display_map.update(cx, |display_map, cx| {
 4534            display_map.splice_inlays(to_remove, to_insert, cx)
 4535        });
 4536        cx.notify();
 4537    }
 4538
 4539    fn trigger_on_type_formatting(
 4540        &self,
 4541        input: String,
 4542        window: &mut Window,
 4543        cx: &mut Context<Self>,
 4544    ) -> Option<Task<Result<()>>> {
 4545        if input.len() != 1 {
 4546            return None;
 4547        }
 4548
 4549        let project = self.project.as_ref()?;
 4550        let position = self.selections.newest_anchor().head();
 4551        let (buffer, buffer_position) = self
 4552            .buffer
 4553            .read(cx)
 4554            .text_anchor_for_position(position, cx)?;
 4555
 4556        let settings = language_settings::language_settings(
 4557            buffer
 4558                .read(cx)
 4559                .language_at(buffer_position)
 4560                .map(|l| l.name()),
 4561            buffer.read(cx).file(),
 4562            cx,
 4563        );
 4564        if !settings.use_on_type_format {
 4565            return None;
 4566        }
 4567
 4568        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4569        // hence we do LSP request & edit on host side only — add formats to host's history.
 4570        let push_to_lsp_host_history = true;
 4571        // If this is not the host, append its history with new edits.
 4572        let push_to_client_history = project.read(cx).is_via_collab();
 4573
 4574        let on_type_formatting = project.update(cx, |project, cx| {
 4575            project.on_type_format(
 4576                buffer.clone(),
 4577                buffer_position,
 4578                input,
 4579                push_to_lsp_host_history,
 4580                cx,
 4581            )
 4582        });
 4583        Some(cx.spawn_in(window, async move |editor, cx| {
 4584            if let Some(transaction) = on_type_formatting.await? {
 4585                if push_to_client_history {
 4586                    buffer
 4587                        .update(cx, |buffer, _| {
 4588                            buffer.push_transaction(transaction, Instant::now());
 4589                            buffer.finalize_last_transaction();
 4590                        })
 4591                        .ok();
 4592                }
 4593                editor.update(cx, |editor, cx| {
 4594                    editor.refresh_document_highlights(cx);
 4595                })?;
 4596            }
 4597            Ok(())
 4598        }))
 4599    }
 4600
 4601    pub fn show_word_completions(
 4602        &mut self,
 4603        _: &ShowWordCompletions,
 4604        window: &mut Window,
 4605        cx: &mut Context<Self>,
 4606    ) {
 4607        self.open_completions_menu(true, None, window, cx);
 4608    }
 4609
 4610    pub fn show_completions(
 4611        &mut self,
 4612        options: &ShowCompletions,
 4613        window: &mut Window,
 4614        cx: &mut Context<Self>,
 4615    ) {
 4616        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4617    }
 4618
 4619    fn open_completions_menu(
 4620        &mut self,
 4621        ignore_completion_provider: bool,
 4622        trigger: Option<&str>,
 4623        window: &mut Window,
 4624        cx: &mut Context<Self>,
 4625    ) {
 4626        if self.pending_rename.is_some() {
 4627            return;
 4628        }
 4629        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4630            return;
 4631        }
 4632
 4633        let position = self.selections.newest_anchor().head();
 4634        if position.diff_base_anchor.is_some() {
 4635            return;
 4636        }
 4637        let (buffer, buffer_position) =
 4638            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4639                output
 4640            } else {
 4641                return;
 4642            };
 4643        let buffer_snapshot = buffer.read(cx).snapshot();
 4644        let show_completion_documentation = buffer_snapshot
 4645            .settings_at(buffer_position, cx)
 4646            .show_completion_documentation;
 4647
 4648        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4649
 4650        let trigger_kind = match trigger {
 4651            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4652                CompletionTriggerKind::TRIGGER_CHARACTER
 4653            }
 4654            _ => CompletionTriggerKind::INVOKED,
 4655        };
 4656        let completion_context = CompletionContext {
 4657            trigger_character: trigger.and_then(|trigger| {
 4658                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4659                    Some(String::from(trigger))
 4660                } else {
 4661                    None
 4662                }
 4663            }),
 4664            trigger_kind,
 4665        };
 4666
 4667        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4668        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4669            let word_to_exclude = buffer_snapshot
 4670                .text_for_range(old_range.clone())
 4671                .collect::<String>();
 4672            (
 4673                buffer_snapshot.anchor_before(old_range.start)
 4674                    ..buffer_snapshot.anchor_after(old_range.end),
 4675                Some(word_to_exclude),
 4676            )
 4677        } else {
 4678            (buffer_position..buffer_position, None)
 4679        };
 4680
 4681        let completion_settings = language_settings(
 4682            buffer_snapshot
 4683                .language_at(buffer_position)
 4684                .map(|language| language.name()),
 4685            buffer_snapshot.file(),
 4686            cx,
 4687        )
 4688        .completions;
 4689
 4690        // The document can be large, so stay in reasonable bounds when searching for words,
 4691        // otherwise completion pop-up might be slow to appear.
 4692        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4693        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4694        let min_word_search = buffer_snapshot.clip_point(
 4695            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4696            Bias::Left,
 4697        );
 4698        let max_word_search = buffer_snapshot.clip_point(
 4699            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4700            Bias::Right,
 4701        );
 4702        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4703            ..buffer_snapshot.point_to_offset(max_word_search);
 4704
 4705        let provider = self
 4706            .completion_provider
 4707            .as_ref()
 4708            .filter(|_| !ignore_completion_provider);
 4709        let skip_digits = query
 4710            .as_ref()
 4711            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4712
 4713        let (mut words, provided_completions) = match provider {
 4714            Some(provider) => {
 4715                let completions = provider.completions(
 4716                    position.excerpt_id,
 4717                    &buffer,
 4718                    buffer_position,
 4719                    completion_context,
 4720                    window,
 4721                    cx,
 4722                );
 4723
 4724                let words = match completion_settings.words {
 4725                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4726                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4727                        .background_spawn(async move {
 4728                            buffer_snapshot.words_in_range(WordsQuery {
 4729                                fuzzy_contents: None,
 4730                                range: word_search_range,
 4731                                skip_digits,
 4732                            })
 4733                        }),
 4734                };
 4735
 4736                (words, completions)
 4737            }
 4738            None => (
 4739                cx.background_spawn(async move {
 4740                    buffer_snapshot.words_in_range(WordsQuery {
 4741                        fuzzy_contents: None,
 4742                        range: word_search_range,
 4743                        skip_digits,
 4744                    })
 4745                }),
 4746                Task::ready(Ok(None)),
 4747            ),
 4748        };
 4749
 4750        let sort_completions = provider
 4751            .as_ref()
 4752            .map_or(false, |provider| provider.sort_completions());
 4753
 4754        let filter_completions = provider
 4755            .as_ref()
 4756            .map_or(true, |provider| provider.filter_completions());
 4757
 4758        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4759
 4760        let id = post_inc(&mut self.next_completion_id);
 4761        let task = cx.spawn_in(window, async move |editor, cx| {
 4762            async move {
 4763                editor.update(cx, |this, _| {
 4764                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4765                })?;
 4766
 4767                let mut completions = Vec::new();
 4768                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4769                    completions.extend(provided_completions);
 4770                    if completion_settings.words == WordsCompletionMode::Fallback {
 4771                        words = Task::ready(BTreeMap::default());
 4772                    }
 4773                }
 4774
 4775                let mut words = words.await;
 4776                if let Some(word_to_exclude) = &word_to_exclude {
 4777                    words.remove(word_to_exclude);
 4778                }
 4779                for lsp_completion in &completions {
 4780                    words.remove(&lsp_completion.new_text);
 4781                }
 4782                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4783                    replace_range: old_range.clone(),
 4784                    new_text: word.clone(),
 4785                    label: CodeLabel::plain(word, None),
 4786                    icon_path: None,
 4787                    documentation: None,
 4788                    source: CompletionSource::BufferWord {
 4789                        word_range,
 4790                        resolved: false,
 4791                    },
 4792                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4793                    confirm: None,
 4794                }));
 4795
 4796                let menu = if completions.is_empty() {
 4797                    None
 4798                } else {
 4799                    let mut menu = CompletionsMenu::new(
 4800                        id,
 4801                        sort_completions,
 4802                        show_completion_documentation,
 4803                        ignore_completion_provider,
 4804                        position,
 4805                        buffer.clone(),
 4806                        completions.into(),
 4807                        snippet_sort_order,
 4808                    );
 4809
 4810                    menu.filter(
 4811                        if filter_completions {
 4812                            query.as_deref()
 4813                        } else {
 4814                            None
 4815                        },
 4816                        cx.background_executor().clone(),
 4817                    )
 4818                    .await;
 4819
 4820                    menu.visible().then_some(menu)
 4821                };
 4822
 4823                editor.update_in(cx, |editor, window, cx| {
 4824                    match editor.context_menu.borrow().as_ref() {
 4825                        None => {}
 4826                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4827                            if prev_menu.id > id {
 4828                                return;
 4829                            }
 4830                        }
 4831                        _ => return,
 4832                    }
 4833
 4834                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4835                        let mut menu = menu.unwrap();
 4836                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4837
 4838                        *editor.context_menu.borrow_mut() =
 4839                            Some(CodeContextMenu::Completions(menu));
 4840
 4841                        if editor.show_edit_predictions_in_menu() {
 4842                            editor.update_visible_inline_completion(window, cx);
 4843                        } else {
 4844                            editor.discard_inline_completion(false, cx);
 4845                        }
 4846
 4847                        cx.notify();
 4848                    } else if editor.completion_tasks.len() <= 1 {
 4849                        // If there are no more completion tasks and the last menu was
 4850                        // empty, we should hide it.
 4851                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4852                        // If it was already hidden and we don't show inline
 4853                        // completions in the menu, we should also show the
 4854                        // inline-completion when available.
 4855                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4856                            editor.update_visible_inline_completion(window, cx);
 4857                        }
 4858                    }
 4859                })?;
 4860
 4861                anyhow::Ok(())
 4862            }
 4863            .log_err()
 4864            .await
 4865        });
 4866
 4867        self.completion_tasks.push((id, task));
 4868    }
 4869
 4870    #[cfg(feature = "test-support")]
 4871    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4872        let menu = self.context_menu.borrow();
 4873        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4874            let completions = menu.completions.borrow();
 4875            Some(completions.to_vec())
 4876        } else {
 4877            None
 4878        }
 4879    }
 4880
 4881    pub fn confirm_completion(
 4882        &mut self,
 4883        action: &ConfirmCompletion,
 4884        window: &mut Window,
 4885        cx: &mut Context<Self>,
 4886    ) -> Option<Task<Result<()>>> {
 4887        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4888        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4889    }
 4890
 4891    pub fn confirm_completion_insert(
 4892        &mut self,
 4893        _: &ConfirmCompletionInsert,
 4894        window: &mut Window,
 4895        cx: &mut Context<Self>,
 4896    ) -> Option<Task<Result<()>>> {
 4897        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4898        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4899    }
 4900
 4901    pub fn confirm_completion_replace(
 4902        &mut self,
 4903        _: &ConfirmCompletionReplace,
 4904        window: &mut Window,
 4905        cx: &mut Context<Self>,
 4906    ) -> Option<Task<Result<()>>> {
 4907        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4908        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4909    }
 4910
 4911    pub fn compose_completion(
 4912        &mut self,
 4913        action: &ComposeCompletion,
 4914        window: &mut Window,
 4915        cx: &mut Context<Self>,
 4916    ) -> Option<Task<Result<()>>> {
 4917        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4918        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4919    }
 4920
 4921    fn do_completion(
 4922        &mut self,
 4923        item_ix: Option<usize>,
 4924        intent: CompletionIntent,
 4925        window: &mut Window,
 4926        cx: &mut Context<Editor>,
 4927    ) -> Option<Task<Result<()>>> {
 4928        use language::ToOffset as _;
 4929
 4930        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4931        else {
 4932            return None;
 4933        };
 4934
 4935        let candidate_id = {
 4936            let entries = completions_menu.entries.borrow();
 4937            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4938            if self.show_edit_predictions_in_menu() {
 4939                self.discard_inline_completion(true, cx);
 4940            }
 4941            mat.candidate_id
 4942        };
 4943
 4944        let buffer_handle = completions_menu.buffer;
 4945        let completion = completions_menu
 4946            .completions
 4947            .borrow()
 4948            .get(candidate_id)?
 4949            .clone();
 4950        cx.stop_propagation();
 4951
 4952        let snippet;
 4953        let new_text;
 4954        if completion.is_snippet() {
 4955            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4956            new_text = snippet.as_ref().unwrap().text.clone();
 4957        } else {
 4958            snippet = None;
 4959            new_text = completion.new_text.clone();
 4960        };
 4961
 4962        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4963        let buffer = buffer_handle.read(cx);
 4964        let snapshot = self.buffer.read(cx).snapshot(cx);
 4965        let replace_range_multibuffer = {
 4966            let excerpt = snapshot
 4967                .excerpt_containing(self.selections.newest_anchor().range())
 4968                .unwrap();
 4969            let multibuffer_anchor = snapshot
 4970                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4971                .unwrap()
 4972                ..snapshot
 4973                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4974                    .unwrap();
 4975            multibuffer_anchor.start.to_offset(&snapshot)
 4976                ..multibuffer_anchor.end.to_offset(&snapshot)
 4977        };
 4978        let newest_anchor = self.selections.newest_anchor();
 4979        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4980            return None;
 4981        }
 4982
 4983        let old_text = buffer
 4984            .text_for_range(replace_range.clone())
 4985            .collect::<String>();
 4986        let lookbehind = newest_anchor
 4987            .start
 4988            .text_anchor
 4989            .to_offset(buffer)
 4990            .saturating_sub(replace_range.start);
 4991        let lookahead = replace_range
 4992            .end
 4993            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4994        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4995        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4996
 4997        let selections = self.selections.all::<usize>(cx);
 4998        let mut ranges = Vec::new();
 4999        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 5000
 5001        for selection in &selections {
 5002            let range = if selection.id == newest_anchor.id {
 5003                replace_range_multibuffer.clone()
 5004            } else {
 5005                let mut range = selection.range();
 5006
 5007                // if prefix is present, don't duplicate it
 5008                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5009                    range.start = range.start.saturating_sub(lookbehind);
 5010
 5011                    // if suffix is also present, mimic the newest cursor and replace it
 5012                    if selection.id != newest_anchor.id
 5013                        && snapshot.contains_str_at(range.end, suffix)
 5014                    {
 5015                        range.end += lookahead;
 5016                    }
 5017                }
 5018                range
 5019            };
 5020
 5021            ranges.push(range.clone());
 5022
 5023            if !self.linked_edit_ranges.is_empty() {
 5024                let start_anchor = snapshot.anchor_before(range.start);
 5025                let end_anchor = snapshot.anchor_after(range.end);
 5026                if let Some(ranges) = self
 5027                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5028                {
 5029                    for (buffer, edits) in ranges {
 5030                        linked_edits
 5031                            .entry(buffer.clone())
 5032                            .or_default()
 5033                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5034                    }
 5035                }
 5036            }
 5037        }
 5038
 5039        cx.emit(EditorEvent::InputHandled {
 5040            utf16_range_to_replace: None,
 5041            text: new_text.clone().into(),
 5042        });
 5043
 5044        self.transact(window, cx, |this, window, cx| {
 5045            if let Some(mut snippet) = snippet {
 5046                snippet.text = new_text.to_string();
 5047                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5048            } else {
 5049                this.buffer.update(cx, |buffer, cx| {
 5050                    let auto_indent = match completion.insert_text_mode {
 5051                        Some(InsertTextMode::AS_IS) => None,
 5052                        _ => this.autoindent_mode.clone(),
 5053                    };
 5054                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5055                    buffer.edit(edits, auto_indent, cx);
 5056                });
 5057            }
 5058            for (buffer, edits) in linked_edits {
 5059                buffer.update(cx, |buffer, cx| {
 5060                    let snapshot = buffer.snapshot();
 5061                    let edits = edits
 5062                        .into_iter()
 5063                        .map(|(range, text)| {
 5064                            use text::ToPoint as TP;
 5065                            let end_point = TP::to_point(&range.end, &snapshot);
 5066                            let start_point = TP::to_point(&range.start, &snapshot);
 5067                            (start_point..end_point, text)
 5068                        })
 5069                        .sorted_by_key(|(range, _)| range.start);
 5070                    buffer.edit(edits, None, cx);
 5071                })
 5072            }
 5073
 5074            this.refresh_inline_completion(true, false, window, cx);
 5075        });
 5076
 5077        let show_new_completions_on_confirm = completion
 5078            .confirm
 5079            .as_ref()
 5080            .map_or(false, |confirm| confirm(intent, window, cx));
 5081        if show_new_completions_on_confirm {
 5082            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5083        }
 5084
 5085        let provider = self.completion_provider.as_ref()?;
 5086        drop(completion);
 5087        let apply_edits = provider.apply_additional_edits_for_completion(
 5088            buffer_handle,
 5089            completions_menu.completions.clone(),
 5090            candidate_id,
 5091            true,
 5092            cx,
 5093        );
 5094
 5095        let editor_settings = EditorSettings::get_global(cx);
 5096        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5097            // After the code completion is finished, users often want to know what signatures are needed.
 5098            // so we should automatically call signature_help
 5099            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5100        }
 5101
 5102        Some(cx.foreground_executor().spawn(async move {
 5103            apply_edits.await?;
 5104            Ok(())
 5105        }))
 5106    }
 5107
 5108    pub fn toggle_code_actions(
 5109        &mut self,
 5110        action: &ToggleCodeActions,
 5111        window: &mut Window,
 5112        cx: &mut Context<Self>,
 5113    ) {
 5114        let quick_launch = action.quick_launch;
 5115        let mut context_menu = self.context_menu.borrow_mut();
 5116        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5117            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5118                // Toggle if we're selecting the same one
 5119                *context_menu = None;
 5120                cx.notify();
 5121                return;
 5122            } else {
 5123                // Otherwise, clear it and start a new one
 5124                *context_menu = None;
 5125                cx.notify();
 5126            }
 5127        }
 5128        drop(context_menu);
 5129        let snapshot = self.snapshot(window, cx);
 5130        let deployed_from_indicator = action.deployed_from_indicator;
 5131        let mut task = self.code_actions_task.take();
 5132        let action = action.clone();
 5133        cx.spawn_in(window, async move |editor, cx| {
 5134            while let Some(prev_task) = task {
 5135                prev_task.await.log_err();
 5136                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5137            }
 5138
 5139            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5140                if editor.focus_handle.is_focused(window) {
 5141                    let multibuffer_point = action
 5142                        .deployed_from_indicator
 5143                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5144                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5145                    let (buffer, buffer_row) = snapshot
 5146                        .buffer_snapshot
 5147                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5148                        .and_then(|(buffer_snapshot, range)| {
 5149                            editor
 5150                                .buffer
 5151                                .read(cx)
 5152                                .buffer(buffer_snapshot.remote_id())
 5153                                .map(|buffer| (buffer, range.start.row))
 5154                        })?;
 5155                    let (_, code_actions) = editor
 5156                        .available_code_actions
 5157                        .clone()
 5158                        .and_then(|(location, code_actions)| {
 5159                            let snapshot = location.buffer.read(cx).snapshot();
 5160                            let point_range = location.range.to_point(&snapshot);
 5161                            let point_range = point_range.start.row..=point_range.end.row;
 5162                            if point_range.contains(&buffer_row) {
 5163                                Some((location, code_actions))
 5164                            } else {
 5165                                None
 5166                            }
 5167                        })
 5168                        .unzip();
 5169                    let buffer_id = buffer.read(cx).remote_id();
 5170                    let tasks = editor
 5171                        .tasks
 5172                        .get(&(buffer_id, buffer_row))
 5173                        .map(|t| Arc::new(t.to_owned()));
 5174                    if tasks.is_none() && code_actions.is_none() {
 5175                        return None;
 5176                    }
 5177
 5178                    editor.completion_tasks.clear();
 5179                    editor.discard_inline_completion(false, cx);
 5180                    let task_context =
 5181                        tasks
 5182                            .as_ref()
 5183                            .zip(editor.project.clone())
 5184                            .map(|(tasks, project)| {
 5185                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5186                            });
 5187
 5188                    Some(cx.spawn_in(window, async move |editor, cx| {
 5189                        let task_context = match task_context {
 5190                            Some(task_context) => task_context.await,
 5191                            None => None,
 5192                        };
 5193                        let resolved_tasks =
 5194                            tasks
 5195                                .zip(task_context.clone())
 5196                                .map(|(tasks, task_context)| ResolvedTasks {
 5197                                    templates: tasks.resolve(&task_context).collect(),
 5198                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5199                                        multibuffer_point.row,
 5200                                        tasks.column,
 5201                                    )),
 5202                                });
 5203                        let spawn_straight_away = quick_launch
 5204                            && resolved_tasks
 5205                                .as_ref()
 5206                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5207                            && code_actions
 5208                                .as_ref()
 5209                                .map_or(true, |actions| actions.is_empty());
 5210                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5211                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5212                                maybe!({
 5213                                    let project = editor.project.as_ref()?;
 5214                                    let dap_store = project.read(cx).dap_store();
 5215                                    let mut scenarios = vec![];
 5216                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5217                                    let buffer = buffer.read(cx);
 5218                                    let language = buffer.language()?;
 5219                                    let file = buffer.file();
 5220                                    let debug_adapter =
 5221                                        language_settings(language.name().into(), file, cx)
 5222                                            .debuggers
 5223                                            .first()
 5224                                            .map(SharedString::from)
 5225                                            .or_else(|| {
 5226                                                language
 5227                                                    .config()
 5228                                                    .debuggers
 5229                                                    .first()
 5230                                                    .map(SharedString::from)
 5231                                            })?;
 5232
 5233                                    dap_store.update(cx, |this, cx| {
 5234                                        for (_, task) in &resolved_tasks.templates {
 5235                                            if let Some(scenario) = this
 5236                                                .debug_scenario_for_build_task(
 5237                                                    task.original_task().clone(),
 5238                                                    debug_adapter.clone(),
 5239                                                    cx,
 5240                                                )
 5241                                            {
 5242                                                scenarios.push(scenario);
 5243                                            }
 5244                                        }
 5245                                    });
 5246                                    Some(scenarios)
 5247                                })
 5248                                .unwrap_or_default()
 5249                            } else {
 5250                                vec![]
 5251                            }
 5252                        })?;
 5253                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5254                            *editor.context_menu.borrow_mut() =
 5255                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5256                                    buffer,
 5257                                    actions: CodeActionContents::new(
 5258                                        resolved_tasks,
 5259                                        code_actions,
 5260                                        debug_scenarios,
 5261                                        task_context.unwrap_or_default(),
 5262                                    ),
 5263                                    selected_item: Default::default(),
 5264                                    scroll_handle: UniformListScrollHandle::default(),
 5265                                    deployed_from_indicator,
 5266                                }));
 5267                            if spawn_straight_away {
 5268                                if let Some(task) = editor.confirm_code_action(
 5269                                    &ConfirmCodeAction { item_ix: Some(0) },
 5270                                    window,
 5271                                    cx,
 5272                                ) {
 5273                                    cx.notify();
 5274                                    return task;
 5275                                }
 5276                            }
 5277                            cx.notify();
 5278                            Task::ready(Ok(()))
 5279                        }) {
 5280                            task.await
 5281                        } else {
 5282                            Ok(())
 5283                        }
 5284                    }))
 5285                } else {
 5286                    Some(Task::ready(Ok(())))
 5287                }
 5288            })?;
 5289            if let Some(task) = spawned_test_task {
 5290                task.await?;
 5291            }
 5292
 5293            Ok::<_, anyhow::Error>(())
 5294        })
 5295        .detach_and_log_err(cx);
 5296    }
 5297
 5298    pub fn confirm_code_action(
 5299        &mut self,
 5300        action: &ConfirmCodeAction,
 5301        window: &mut Window,
 5302        cx: &mut Context<Self>,
 5303    ) -> Option<Task<Result<()>>> {
 5304        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5305
 5306        let actions_menu =
 5307            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5308                menu
 5309            } else {
 5310                return None;
 5311            };
 5312
 5313        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5314        let action = actions_menu.actions.get(action_ix)?;
 5315        let title = action.label();
 5316        let buffer = actions_menu.buffer;
 5317        let workspace = self.workspace()?;
 5318
 5319        match action {
 5320            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5321                workspace.update(cx, |workspace, cx| {
 5322                    workspace.schedule_resolved_task(
 5323                        task_source_kind,
 5324                        resolved_task,
 5325                        false,
 5326                        window,
 5327                        cx,
 5328                    );
 5329
 5330                    Some(Task::ready(Ok(())))
 5331                })
 5332            }
 5333            CodeActionsItem::CodeAction {
 5334                excerpt_id,
 5335                action,
 5336                provider,
 5337            } => {
 5338                let apply_code_action =
 5339                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5340                let workspace = workspace.downgrade();
 5341                Some(cx.spawn_in(window, async move |editor, cx| {
 5342                    let project_transaction = apply_code_action.await?;
 5343                    Self::open_project_transaction(
 5344                        &editor,
 5345                        workspace,
 5346                        project_transaction,
 5347                        title,
 5348                        cx,
 5349                    )
 5350                    .await
 5351                }))
 5352            }
 5353            CodeActionsItem::DebugScenario(scenario) => {
 5354                let context = actions_menu.actions.context.clone();
 5355
 5356                workspace.update(cx, |workspace, cx| {
 5357                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5358                });
 5359                Some(Task::ready(Ok(())))
 5360            }
 5361        }
 5362    }
 5363
 5364    pub async fn open_project_transaction(
 5365        this: &WeakEntity<Editor>,
 5366        workspace: WeakEntity<Workspace>,
 5367        transaction: ProjectTransaction,
 5368        title: String,
 5369        cx: &mut AsyncWindowContext,
 5370    ) -> Result<()> {
 5371        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5372        cx.update(|_, cx| {
 5373            entries.sort_unstable_by_key(|(buffer, _)| {
 5374                buffer.read(cx).file().map(|f| f.path().clone())
 5375            });
 5376        })?;
 5377
 5378        // If the project transaction's edits are all contained within this editor, then
 5379        // avoid opening a new editor to display them.
 5380
 5381        if let Some((buffer, transaction)) = entries.first() {
 5382            if entries.len() == 1 {
 5383                let excerpt = this.update(cx, |editor, cx| {
 5384                    editor
 5385                        .buffer()
 5386                        .read(cx)
 5387                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5388                })?;
 5389                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5390                    if excerpted_buffer == *buffer {
 5391                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5392                            let excerpt_range = excerpt_range.to_offset(buffer);
 5393                            buffer
 5394                                .edited_ranges_for_transaction::<usize>(transaction)
 5395                                .all(|range| {
 5396                                    excerpt_range.start <= range.start
 5397                                        && excerpt_range.end >= range.end
 5398                                })
 5399                        })?;
 5400
 5401                        if all_edits_within_excerpt {
 5402                            return Ok(());
 5403                        }
 5404                    }
 5405                }
 5406            }
 5407        } else {
 5408            return Ok(());
 5409        }
 5410
 5411        let mut ranges_to_highlight = Vec::new();
 5412        let excerpt_buffer = cx.new(|cx| {
 5413            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5414            for (buffer_handle, transaction) in &entries {
 5415                let edited_ranges = buffer_handle
 5416                    .read(cx)
 5417                    .edited_ranges_for_transaction::<Point>(transaction)
 5418                    .collect::<Vec<_>>();
 5419                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5420                    PathKey::for_buffer(buffer_handle, cx),
 5421                    buffer_handle.clone(),
 5422                    edited_ranges,
 5423                    DEFAULT_MULTIBUFFER_CONTEXT,
 5424                    cx,
 5425                );
 5426
 5427                ranges_to_highlight.extend(ranges);
 5428            }
 5429            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5430            multibuffer
 5431        })?;
 5432
 5433        workspace.update_in(cx, |workspace, window, cx| {
 5434            let project = workspace.project().clone();
 5435            let editor =
 5436                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5437            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5438            editor.update(cx, |editor, cx| {
 5439                editor.highlight_background::<Self>(
 5440                    &ranges_to_highlight,
 5441                    |theme| theme.editor_highlighted_line_background,
 5442                    cx,
 5443                );
 5444            });
 5445        })?;
 5446
 5447        Ok(())
 5448    }
 5449
 5450    pub fn clear_code_action_providers(&mut self) {
 5451        self.code_action_providers.clear();
 5452        self.available_code_actions.take();
 5453    }
 5454
 5455    pub fn add_code_action_provider(
 5456        &mut self,
 5457        provider: Rc<dyn CodeActionProvider>,
 5458        window: &mut Window,
 5459        cx: &mut Context<Self>,
 5460    ) {
 5461        if self
 5462            .code_action_providers
 5463            .iter()
 5464            .any(|existing_provider| existing_provider.id() == provider.id())
 5465        {
 5466            return;
 5467        }
 5468
 5469        self.code_action_providers.push(provider);
 5470        self.refresh_code_actions(window, cx);
 5471    }
 5472
 5473    pub fn remove_code_action_provider(
 5474        &mut self,
 5475        id: Arc<str>,
 5476        window: &mut Window,
 5477        cx: &mut Context<Self>,
 5478    ) {
 5479        self.code_action_providers
 5480            .retain(|provider| provider.id() != id);
 5481        self.refresh_code_actions(window, cx);
 5482    }
 5483
 5484    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5485        let newest_selection = self.selections.newest_anchor().clone();
 5486        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5487        let buffer = self.buffer.read(cx);
 5488        if newest_selection.head().diff_base_anchor.is_some() {
 5489            return None;
 5490        }
 5491        let (start_buffer, start) =
 5492            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5493        let (end_buffer, end) =
 5494            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5495        if start_buffer != end_buffer {
 5496            return None;
 5497        }
 5498
 5499        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5500            cx.background_executor()
 5501                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5502                .await;
 5503
 5504            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5505                let providers = this.code_action_providers.clone();
 5506                let tasks = this
 5507                    .code_action_providers
 5508                    .iter()
 5509                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5510                    .collect::<Vec<_>>();
 5511                (providers, tasks)
 5512            })?;
 5513
 5514            let mut actions = Vec::new();
 5515            for (provider, provider_actions) in
 5516                providers.into_iter().zip(future::join_all(tasks).await)
 5517            {
 5518                if let Some(provider_actions) = provider_actions.log_err() {
 5519                    actions.extend(provider_actions.into_iter().map(|action| {
 5520                        AvailableCodeAction {
 5521                            excerpt_id: newest_selection.start.excerpt_id,
 5522                            action,
 5523                            provider: provider.clone(),
 5524                        }
 5525                    }));
 5526                }
 5527            }
 5528
 5529            this.update(cx, |this, cx| {
 5530                this.available_code_actions = if actions.is_empty() {
 5531                    None
 5532                } else {
 5533                    Some((
 5534                        Location {
 5535                            buffer: start_buffer,
 5536                            range: start..end,
 5537                        },
 5538                        actions.into(),
 5539                    ))
 5540                };
 5541                cx.notify();
 5542            })
 5543        }));
 5544        None
 5545    }
 5546
 5547    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5548        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5549            self.show_git_blame_inline = false;
 5550
 5551            self.show_git_blame_inline_delay_task =
 5552                Some(cx.spawn_in(window, async move |this, cx| {
 5553                    cx.background_executor().timer(delay).await;
 5554
 5555                    this.update(cx, |this, cx| {
 5556                        this.show_git_blame_inline = true;
 5557                        cx.notify();
 5558                    })
 5559                    .log_err();
 5560                }));
 5561        }
 5562    }
 5563
 5564    fn show_blame_popover(
 5565        &mut self,
 5566        blame_entry: &BlameEntry,
 5567        position: gpui::Point<Pixels>,
 5568        cx: &mut Context<Self>,
 5569    ) {
 5570        if let Some(state) = &mut self.inline_blame_popover {
 5571            state.hide_task.take();
 5572            cx.notify();
 5573        } else {
 5574            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5575            let show_task = cx.spawn(async move |editor, cx| {
 5576                cx.background_executor()
 5577                    .timer(std::time::Duration::from_millis(delay))
 5578                    .await;
 5579                editor
 5580                    .update(cx, |editor, cx| {
 5581                        if let Some(state) = &mut editor.inline_blame_popover {
 5582                            state.show_task = None;
 5583                            cx.notify();
 5584                        }
 5585                    })
 5586                    .ok();
 5587            });
 5588            let Some(blame) = self.blame.as_ref() else {
 5589                return;
 5590            };
 5591            let blame = blame.read(cx);
 5592            let details = blame.details_for_entry(&blame_entry);
 5593            let markdown = cx.new(|cx| {
 5594                Markdown::new(
 5595                    details
 5596                        .as_ref()
 5597                        .map(|message| message.message.clone())
 5598                        .unwrap_or_default(),
 5599                    None,
 5600                    None,
 5601                    cx,
 5602                )
 5603            });
 5604            self.inline_blame_popover = Some(InlineBlamePopover {
 5605                position,
 5606                show_task: Some(show_task),
 5607                hide_task: None,
 5608                popover_bounds: None,
 5609                popover_state: InlineBlamePopoverState {
 5610                    scroll_handle: ScrollHandle::new(),
 5611                    commit_message: details,
 5612                    markdown,
 5613                },
 5614            });
 5615        }
 5616    }
 5617
 5618    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5619        if let Some(state) = &mut self.inline_blame_popover {
 5620            if state.show_task.is_some() {
 5621                self.inline_blame_popover.take();
 5622                cx.notify();
 5623            } else {
 5624                let hide_task = cx.spawn(async move |editor, cx| {
 5625                    cx.background_executor()
 5626                        .timer(std::time::Duration::from_millis(100))
 5627                        .await;
 5628                    editor
 5629                        .update(cx, |editor, cx| {
 5630                            editor.inline_blame_popover.take();
 5631                            cx.notify();
 5632                        })
 5633                        .ok();
 5634                });
 5635                state.hide_task = Some(hide_task);
 5636            }
 5637        }
 5638    }
 5639
 5640    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5641        if self.pending_rename.is_some() {
 5642            return None;
 5643        }
 5644
 5645        let provider = self.semantics_provider.clone()?;
 5646        let buffer = self.buffer.read(cx);
 5647        let newest_selection = self.selections.newest_anchor().clone();
 5648        let cursor_position = newest_selection.head();
 5649        let (cursor_buffer, cursor_buffer_position) =
 5650            buffer.text_anchor_for_position(cursor_position, cx)?;
 5651        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5652        if cursor_buffer != tail_buffer {
 5653            return None;
 5654        }
 5655        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5656        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5657            cx.background_executor()
 5658                .timer(Duration::from_millis(debounce))
 5659                .await;
 5660
 5661            let highlights = if let Some(highlights) = cx
 5662                .update(|cx| {
 5663                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5664                })
 5665                .ok()
 5666                .flatten()
 5667            {
 5668                highlights.await.log_err()
 5669            } else {
 5670                None
 5671            };
 5672
 5673            if let Some(highlights) = highlights {
 5674                this.update(cx, |this, cx| {
 5675                    if this.pending_rename.is_some() {
 5676                        return;
 5677                    }
 5678
 5679                    let buffer_id = cursor_position.buffer_id;
 5680                    let buffer = this.buffer.read(cx);
 5681                    if !buffer
 5682                        .text_anchor_for_position(cursor_position, cx)
 5683                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5684                    {
 5685                        return;
 5686                    }
 5687
 5688                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5689                    let mut write_ranges = Vec::new();
 5690                    let mut read_ranges = Vec::new();
 5691                    for highlight in highlights {
 5692                        for (excerpt_id, excerpt_range) in
 5693                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5694                        {
 5695                            let start = highlight
 5696                                .range
 5697                                .start
 5698                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5699                            let end = highlight
 5700                                .range
 5701                                .end
 5702                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5703                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5704                                continue;
 5705                            }
 5706
 5707                            let range = Anchor {
 5708                                buffer_id,
 5709                                excerpt_id,
 5710                                text_anchor: start,
 5711                                diff_base_anchor: None,
 5712                            }..Anchor {
 5713                                buffer_id,
 5714                                excerpt_id,
 5715                                text_anchor: end,
 5716                                diff_base_anchor: None,
 5717                            };
 5718                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5719                                write_ranges.push(range);
 5720                            } else {
 5721                                read_ranges.push(range);
 5722                            }
 5723                        }
 5724                    }
 5725
 5726                    this.highlight_background::<DocumentHighlightRead>(
 5727                        &read_ranges,
 5728                        |theme| theme.editor_document_highlight_read_background,
 5729                        cx,
 5730                    );
 5731                    this.highlight_background::<DocumentHighlightWrite>(
 5732                        &write_ranges,
 5733                        |theme| theme.editor_document_highlight_write_background,
 5734                        cx,
 5735                    );
 5736                    cx.notify();
 5737                })
 5738                .log_err();
 5739            }
 5740        }));
 5741        None
 5742    }
 5743
 5744    fn prepare_highlight_query_from_selection(
 5745        &mut self,
 5746        cx: &mut Context<Editor>,
 5747    ) -> Option<(String, Range<Anchor>)> {
 5748        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5749            return None;
 5750        }
 5751        if !EditorSettings::get_global(cx).selection_highlight {
 5752            return None;
 5753        }
 5754        if self.selections.count() != 1 || self.selections.line_mode {
 5755            return None;
 5756        }
 5757        let selection = self.selections.newest::<Point>(cx);
 5758        if selection.is_empty() || selection.start.row != selection.end.row {
 5759            return None;
 5760        }
 5761        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5762        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5763        let query = multi_buffer_snapshot
 5764            .text_for_range(selection_anchor_range.clone())
 5765            .collect::<String>();
 5766        if query.trim().is_empty() {
 5767            return None;
 5768        }
 5769        Some((query, selection_anchor_range))
 5770    }
 5771
 5772    fn update_selection_occurrence_highlights(
 5773        &mut self,
 5774        query_text: String,
 5775        query_range: Range<Anchor>,
 5776        multi_buffer_range_to_query: Range<Point>,
 5777        use_debounce: bool,
 5778        window: &mut Window,
 5779        cx: &mut Context<Editor>,
 5780    ) -> Task<()> {
 5781        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5782        cx.spawn_in(window, async move |editor, cx| {
 5783            if use_debounce {
 5784                cx.background_executor()
 5785                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5786                    .await;
 5787            }
 5788            let match_task = cx.background_spawn(async move {
 5789                let buffer_ranges = multi_buffer_snapshot
 5790                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5791                    .into_iter()
 5792                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5793                let mut match_ranges = Vec::new();
 5794                let Ok(regex) = project::search::SearchQuery::text(
 5795                    query_text.clone(),
 5796                    false,
 5797                    false,
 5798                    false,
 5799                    Default::default(),
 5800                    Default::default(),
 5801                    false,
 5802                    None,
 5803                ) else {
 5804                    return Vec::default();
 5805                };
 5806                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5807                    match_ranges.extend(
 5808                        regex
 5809                            .search(&buffer_snapshot, Some(search_range.clone()))
 5810                            .await
 5811                            .into_iter()
 5812                            .filter_map(|match_range| {
 5813                                let match_start = buffer_snapshot
 5814                                    .anchor_after(search_range.start + match_range.start);
 5815                                let match_end = buffer_snapshot
 5816                                    .anchor_before(search_range.start + match_range.end);
 5817                                let match_anchor_range = Anchor::range_in_buffer(
 5818                                    excerpt_id,
 5819                                    buffer_snapshot.remote_id(),
 5820                                    match_start..match_end,
 5821                                );
 5822                                (match_anchor_range != query_range).then_some(match_anchor_range)
 5823                            }),
 5824                    );
 5825                }
 5826                match_ranges
 5827            });
 5828            let match_ranges = match_task.await;
 5829            editor
 5830                .update_in(cx, |editor, _, cx| {
 5831                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5832                    if !match_ranges.is_empty() {
 5833                        editor.highlight_background::<SelectedTextHighlight>(
 5834                            &match_ranges,
 5835                            |theme| theme.editor_document_highlight_bracket_background,
 5836                            cx,
 5837                        )
 5838                    }
 5839                })
 5840                .log_err();
 5841        })
 5842    }
 5843
 5844    fn refresh_selected_text_highlights(
 5845        &mut self,
 5846        on_buffer_edit: bool,
 5847        window: &mut Window,
 5848        cx: &mut Context<Editor>,
 5849    ) {
 5850        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5851        else {
 5852            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5853            self.quick_selection_highlight_task.take();
 5854            self.debounced_selection_highlight_task.take();
 5855            return;
 5856        };
 5857        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5858        if on_buffer_edit
 5859            || self
 5860                .quick_selection_highlight_task
 5861                .as_ref()
 5862                .map_or(true, |(prev_anchor_range, _)| {
 5863                    prev_anchor_range != &query_range
 5864                })
 5865        {
 5866            let multi_buffer_visible_start = self
 5867                .scroll_manager
 5868                .anchor()
 5869                .anchor
 5870                .to_point(&multi_buffer_snapshot);
 5871            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5872                multi_buffer_visible_start
 5873                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5874                Bias::Left,
 5875            );
 5876            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5877            self.quick_selection_highlight_task = Some((
 5878                query_range.clone(),
 5879                self.update_selection_occurrence_highlights(
 5880                    query_text.clone(),
 5881                    query_range.clone(),
 5882                    multi_buffer_visible_range,
 5883                    false,
 5884                    window,
 5885                    cx,
 5886                ),
 5887            ));
 5888        }
 5889        if on_buffer_edit
 5890            || self
 5891                .debounced_selection_highlight_task
 5892                .as_ref()
 5893                .map_or(true, |(prev_anchor_range, _)| {
 5894                    prev_anchor_range != &query_range
 5895                })
 5896        {
 5897            let multi_buffer_start = multi_buffer_snapshot
 5898                .anchor_before(0)
 5899                .to_point(&multi_buffer_snapshot);
 5900            let multi_buffer_end = multi_buffer_snapshot
 5901                .anchor_after(multi_buffer_snapshot.len())
 5902                .to_point(&multi_buffer_snapshot);
 5903            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5904            self.debounced_selection_highlight_task = Some((
 5905                query_range.clone(),
 5906                self.update_selection_occurrence_highlights(
 5907                    query_text,
 5908                    query_range,
 5909                    multi_buffer_full_range,
 5910                    true,
 5911                    window,
 5912                    cx,
 5913                ),
 5914            ));
 5915        }
 5916    }
 5917
 5918    pub fn refresh_inline_completion(
 5919        &mut self,
 5920        debounce: bool,
 5921        user_requested: bool,
 5922        window: &mut Window,
 5923        cx: &mut Context<Self>,
 5924    ) -> Option<()> {
 5925        let provider = self.edit_prediction_provider()?;
 5926        let cursor = self.selections.newest_anchor().head();
 5927        let (buffer, cursor_buffer_position) =
 5928            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5929
 5930        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5931            self.discard_inline_completion(false, cx);
 5932            return None;
 5933        }
 5934
 5935        if !user_requested
 5936            && (!self.should_show_edit_predictions()
 5937                || !self.is_focused(window)
 5938                || buffer.read(cx).is_empty())
 5939        {
 5940            self.discard_inline_completion(false, cx);
 5941            return None;
 5942        }
 5943
 5944        self.update_visible_inline_completion(window, cx);
 5945        provider.refresh(
 5946            self.project.clone(),
 5947            buffer,
 5948            cursor_buffer_position,
 5949            debounce,
 5950            cx,
 5951        );
 5952        Some(())
 5953    }
 5954
 5955    fn show_edit_predictions_in_menu(&self) -> bool {
 5956        match self.edit_prediction_settings {
 5957            EditPredictionSettings::Disabled => false,
 5958            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5959        }
 5960    }
 5961
 5962    pub fn edit_predictions_enabled(&self) -> bool {
 5963        match self.edit_prediction_settings {
 5964            EditPredictionSettings::Disabled => false,
 5965            EditPredictionSettings::Enabled { .. } => true,
 5966        }
 5967    }
 5968
 5969    fn edit_prediction_requires_modifier(&self) -> bool {
 5970        match self.edit_prediction_settings {
 5971            EditPredictionSettings::Disabled => false,
 5972            EditPredictionSettings::Enabled {
 5973                preview_requires_modifier,
 5974                ..
 5975            } => preview_requires_modifier,
 5976        }
 5977    }
 5978
 5979    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5980        if self.edit_prediction_provider.is_none() {
 5981            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5982        } else {
 5983            let selection = self.selections.newest_anchor();
 5984            let cursor = selection.head();
 5985
 5986            if let Some((buffer, cursor_buffer_position)) =
 5987                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5988            {
 5989                self.edit_prediction_settings =
 5990                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5991            }
 5992        }
 5993    }
 5994
 5995    fn edit_prediction_settings_at_position(
 5996        &self,
 5997        buffer: &Entity<Buffer>,
 5998        buffer_position: language::Anchor,
 5999        cx: &App,
 6000    ) -> EditPredictionSettings {
 6001        if !self.mode.is_full()
 6002            || !self.show_inline_completions_override.unwrap_or(true)
 6003            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 6004        {
 6005            return EditPredictionSettings::Disabled;
 6006        }
 6007
 6008        let buffer = buffer.read(cx);
 6009
 6010        let file = buffer.file();
 6011
 6012        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 6013            return EditPredictionSettings::Disabled;
 6014        };
 6015
 6016        let by_provider = matches!(
 6017            self.menu_inline_completions_policy,
 6018            MenuInlineCompletionsPolicy::ByProvider
 6019        );
 6020
 6021        let show_in_menu = by_provider
 6022            && self
 6023                .edit_prediction_provider
 6024                .as_ref()
 6025                .map_or(false, |provider| {
 6026                    provider.provider.show_completions_in_menu()
 6027                });
 6028
 6029        let preview_requires_modifier =
 6030            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6031
 6032        EditPredictionSettings::Enabled {
 6033            show_in_menu,
 6034            preview_requires_modifier,
 6035        }
 6036    }
 6037
 6038    fn should_show_edit_predictions(&self) -> bool {
 6039        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6040    }
 6041
 6042    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6043        matches!(
 6044            self.edit_prediction_preview,
 6045            EditPredictionPreview::Active { .. }
 6046        )
 6047    }
 6048
 6049    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6050        let cursor = self.selections.newest_anchor().head();
 6051        if let Some((buffer, cursor_position)) =
 6052            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6053        {
 6054            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6055        } else {
 6056            false
 6057        }
 6058    }
 6059
 6060    fn edit_predictions_enabled_in_buffer(
 6061        &self,
 6062        buffer: &Entity<Buffer>,
 6063        buffer_position: language::Anchor,
 6064        cx: &App,
 6065    ) -> bool {
 6066        maybe!({
 6067            if self.read_only(cx) {
 6068                return Some(false);
 6069            }
 6070            let provider = self.edit_prediction_provider()?;
 6071            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6072                return Some(false);
 6073            }
 6074            let buffer = buffer.read(cx);
 6075            let Some(file) = buffer.file() else {
 6076                return Some(true);
 6077            };
 6078            let settings = all_language_settings(Some(file), cx);
 6079            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6080        })
 6081        .unwrap_or(false)
 6082    }
 6083
 6084    fn cycle_inline_completion(
 6085        &mut self,
 6086        direction: Direction,
 6087        window: &mut Window,
 6088        cx: &mut Context<Self>,
 6089    ) -> Option<()> {
 6090        let provider = self.edit_prediction_provider()?;
 6091        let cursor = self.selections.newest_anchor().head();
 6092        let (buffer, cursor_buffer_position) =
 6093            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6094        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6095            return None;
 6096        }
 6097
 6098        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6099        self.update_visible_inline_completion(window, cx);
 6100
 6101        Some(())
 6102    }
 6103
 6104    pub fn show_inline_completion(
 6105        &mut self,
 6106        _: &ShowEditPrediction,
 6107        window: &mut Window,
 6108        cx: &mut Context<Self>,
 6109    ) {
 6110        if !self.has_active_inline_completion() {
 6111            self.refresh_inline_completion(false, true, window, cx);
 6112            return;
 6113        }
 6114
 6115        self.update_visible_inline_completion(window, cx);
 6116    }
 6117
 6118    pub fn display_cursor_names(
 6119        &mut self,
 6120        _: &DisplayCursorNames,
 6121        window: &mut Window,
 6122        cx: &mut Context<Self>,
 6123    ) {
 6124        self.show_cursor_names(window, cx);
 6125    }
 6126
 6127    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6128        self.show_cursor_names = true;
 6129        cx.notify();
 6130        cx.spawn_in(window, async move |this, cx| {
 6131            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6132            this.update(cx, |this, cx| {
 6133                this.show_cursor_names = false;
 6134                cx.notify()
 6135            })
 6136            .ok()
 6137        })
 6138        .detach();
 6139    }
 6140
 6141    pub fn next_edit_prediction(
 6142        &mut self,
 6143        _: &NextEditPrediction,
 6144        window: &mut Window,
 6145        cx: &mut Context<Self>,
 6146    ) {
 6147        if self.has_active_inline_completion() {
 6148            self.cycle_inline_completion(Direction::Next, window, cx);
 6149        } else {
 6150            let is_copilot_disabled = self
 6151                .refresh_inline_completion(false, true, window, cx)
 6152                .is_none();
 6153            if is_copilot_disabled {
 6154                cx.propagate();
 6155            }
 6156        }
 6157    }
 6158
 6159    pub fn previous_edit_prediction(
 6160        &mut self,
 6161        _: &PreviousEditPrediction,
 6162        window: &mut Window,
 6163        cx: &mut Context<Self>,
 6164    ) {
 6165        if self.has_active_inline_completion() {
 6166            self.cycle_inline_completion(Direction::Prev, window, cx);
 6167        } else {
 6168            let is_copilot_disabled = self
 6169                .refresh_inline_completion(false, true, window, cx)
 6170                .is_none();
 6171            if is_copilot_disabled {
 6172                cx.propagate();
 6173            }
 6174        }
 6175    }
 6176
 6177    pub fn accept_edit_prediction(
 6178        &mut self,
 6179        _: &AcceptEditPrediction,
 6180        window: &mut Window,
 6181        cx: &mut Context<Self>,
 6182    ) {
 6183        if self.show_edit_predictions_in_menu() {
 6184            self.hide_context_menu(window, cx);
 6185        }
 6186
 6187        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6188            return;
 6189        };
 6190
 6191        self.report_inline_completion_event(
 6192            active_inline_completion.completion_id.clone(),
 6193            true,
 6194            cx,
 6195        );
 6196
 6197        match &active_inline_completion.completion {
 6198            InlineCompletion::Move { target, .. } => {
 6199                let target = *target;
 6200
 6201                if let Some(position_map) = &self.last_position_map {
 6202                    if position_map
 6203                        .visible_row_range
 6204                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6205                        || !self.edit_prediction_requires_modifier()
 6206                    {
 6207                        self.unfold_ranges(&[target..target], true, false, cx);
 6208                        // Note that this is also done in vim's handler of the Tab action.
 6209                        self.change_selections(
 6210                            Some(Autoscroll::newest()),
 6211                            window,
 6212                            cx,
 6213                            |selections| {
 6214                                selections.select_anchor_ranges([target..target]);
 6215                            },
 6216                        );
 6217                        self.clear_row_highlights::<EditPredictionPreview>();
 6218
 6219                        self.edit_prediction_preview
 6220                            .set_previous_scroll_position(None);
 6221                    } else {
 6222                        self.edit_prediction_preview
 6223                            .set_previous_scroll_position(Some(
 6224                                position_map.snapshot.scroll_anchor,
 6225                            ));
 6226
 6227                        self.highlight_rows::<EditPredictionPreview>(
 6228                            target..target,
 6229                            cx.theme().colors().editor_highlighted_line_background,
 6230                            RowHighlightOptions {
 6231                                autoscroll: true,
 6232                                ..Default::default()
 6233                            },
 6234                            cx,
 6235                        );
 6236                        self.request_autoscroll(Autoscroll::fit(), cx);
 6237                    }
 6238                }
 6239            }
 6240            InlineCompletion::Edit { edits, .. } => {
 6241                if let Some(provider) = self.edit_prediction_provider() {
 6242                    provider.accept(cx);
 6243                }
 6244
 6245                let snapshot = self.buffer.read(cx).snapshot(cx);
 6246                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6247
 6248                self.buffer.update(cx, |buffer, cx| {
 6249                    buffer.edit(edits.iter().cloned(), None, cx)
 6250                });
 6251
 6252                self.change_selections(None, window, cx, |s| {
 6253                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6254                });
 6255
 6256                self.update_visible_inline_completion(window, cx);
 6257                if self.active_inline_completion.is_none() {
 6258                    self.refresh_inline_completion(true, true, window, cx);
 6259                }
 6260
 6261                cx.notify();
 6262            }
 6263        }
 6264
 6265        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6266    }
 6267
 6268    pub fn accept_partial_inline_completion(
 6269        &mut self,
 6270        _: &AcceptPartialEditPrediction,
 6271        window: &mut Window,
 6272        cx: &mut Context<Self>,
 6273    ) {
 6274        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6275            return;
 6276        };
 6277        if self.selections.count() != 1 {
 6278            return;
 6279        }
 6280
 6281        self.report_inline_completion_event(
 6282            active_inline_completion.completion_id.clone(),
 6283            true,
 6284            cx,
 6285        );
 6286
 6287        match &active_inline_completion.completion {
 6288            InlineCompletion::Move { target, .. } => {
 6289                let target = *target;
 6290                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6291                    selections.select_anchor_ranges([target..target]);
 6292                });
 6293            }
 6294            InlineCompletion::Edit { edits, .. } => {
 6295                // Find an insertion that starts at the cursor position.
 6296                let snapshot = self.buffer.read(cx).snapshot(cx);
 6297                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6298                let insertion = edits.iter().find_map(|(range, text)| {
 6299                    let range = range.to_offset(&snapshot);
 6300                    if range.is_empty() && range.start == cursor_offset {
 6301                        Some(text)
 6302                    } else {
 6303                        None
 6304                    }
 6305                });
 6306
 6307                if let Some(text) = insertion {
 6308                    let mut partial_completion = text
 6309                        .chars()
 6310                        .by_ref()
 6311                        .take_while(|c| c.is_alphabetic())
 6312                        .collect::<String>();
 6313                    if partial_completion.is_empty() {
 6314                        partial_completion = text
 6315                            .chars()
 6316                            .by_ref()
 6317                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6318                            .collect::<String>();
 6319                    }
 6320
 6321                    cx.emit(EditorEvent::InputHandled {
 6322                        utf16_range_to_replace: None,
 6323                        text: partial_completion.clone().into(),
 6324                    });
 6325
 6326                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6327
 6328                    self.refresh_inline_completion(true, true, window, cx);
 6329                    cx.notify();
 6330                } else {
 6331                    self.accept_edit_prediction(&Default::default(), window, cx);
 6332                }
 6333            }
 6334        }
 6335    }
 6336
 6337    fn discard_inline_completion(
 6338        &mut self,
 6339        should_report_inline_completion_event: bool,
 6340        cx: &mut Context<Self>,
 6341    ) -> bool {
 6342        if should_report_inline_completion_event {
 6343            let completion_id = self
 6344                .active_inline_completion
 6345                .as_ref()
 6346                .and_then(|active_completion| active_completion.completion_id.clone());
 6347
 6348            self.report_inline_completion_event(completion_id, false, cx);
 6349        }
 6350
 6351        if let Some(provider) = self.edit_prediction_provider() {
 6352            provider.discard(cx);
 6353        }
 6354
 6355        self.take_active_inline_completion(cx)
 6356    }
 6357
 6358    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6359        let Some(provider) = self.edit_prediction_provider() else {
 6360            return;
 6361        };
 6362
 6363        let Some((_, buffer, _)) = self
 6364            .buffer
 6365            .read(cx)
 6366            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6367        else {
 6368            return;
 6369        };
 6370
 6371        let extension = buffer
 6372            .read(cx)
 6373            .file()
 6374            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6375
 6376        let event_type = match accepted {
 6377            true => "Edit Prediction Accepted",
 6378            false => "Edit Prediction Discarded",
 6379        };
 6380        telemetry::event!(
 6381            event_type,
 6382            provider = provider.name(),
 6383            prediction_id = id,
 6384            suggestion_accepted = accepted,
 6385            file_extension = extension,
 6386        );
 6387    }
 6388
 6389    pub fn has_active_inline_completion(&self) -> bool {
 6390        self.active_inline_completion.is_some()
 6391    }
 6392
 6393    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6394        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6395            return false;
 6396        };
 6397
 6398        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6399        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6400        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6401        true
 6402    }
 6403
 6404    /// Returns true when we're displaying the edit prediction popover below the cursor
 6405    /// like we are not previewing and the LSP autocomplete menu is visible
 6406    /// or we are in `when_holding_modifier` mode.
 6407    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6408        if self.edit_prediction_preview_is_active()
 6409            || !self.show_edit_predictions_in_menu()
 6410            || !self.edit_predictions_enabled()
 6411        {
 6412            return false;
 6413        }
 6414
 6415        if self.has_visible_completions_menu() {
 6416            return true;
 6417        }
 6418
 6419        has_completion && self.edit_prediction_requires_modifier()
 6420    }
 6421
 6422    fn handle_modifiers_changed(
 6423        &mut self,
 6424        modifiers: Modifiers,
 6425        position_map: &PositionMap,
 6426        window: &mut Window,
 6427        cx: &mut Context<Self>,
 6428    ) {
 6429        if self.show_edit_predictions_in_menu() {
 6430            self.update_edit_prediction_preview(&modifiers, window, cx);
 6431        }
 6432
 6433        self.update_selection_mode(&modifiers, position_map, window, cx);
 6434
 6435        let mouse_position = window.mouse_position();
 6436        if !position_map.text_hitbox.is_hovered(window) {
 6437            return;
 6438        }
 6439
 6440        self.update_hovered_link(
 6441            position_map.point_for_position(mouse_position),
 6442            &position_map.snapshot,
 6443            modifiers,
 6444            window,
 6445            cx,
 6446        )
 6447    }
 6448
 6449    fn update_selection_mode(
 6450        &mut self,
 6451        modifiers: &Modifiers,
 6452        position_map: &PositionMap,
 6453        window: &mut Window,
 6454        cx: &mut Context<Self>,
 6455    ) {
 6456        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6457            return;
 6458        }
 6459
 6460        let mouse_position = window.mouse_position();
 6461        let point_for_position = position_map.point_for_position(mouse_position);
 6462        let position = point_for_position.previous_valid;
 6463
 6464        self.select(
 6465            SelectPhase::BeginColumnar {
 6466                position,
 6467                reset: false,
 6468                goal_column: point_for_position.exact_unclipped.column(),
 6469            },
 6470            window,
 6471            cx,
 6472        );
 6473    }
 6474
 6475    fn update_edit_prediction_preview(
 6476        &mut self,
 6477        modifiers: &Modifiers,
 6478        window: &mut Window,
 6479        cx: &mut Context<Self>,
 6480    ) {
 6481        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6482        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6483            return;
 6484        };
 6485
 6486        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6487            if matches!(
 6488                self.edit_prediction_preview,
 6489                EditPredictionPreview::Inactive { .. }
 6490            ) {
 6491                self.edit_prediction_preview = EditPredictionPreview::Active {
 6492                    previous_scroll_position: None,
 6493                    since: Instant::now(),
 6494                };
 6495
 6496                self.update_visible_inline_completion(window, cx);
 6497                cx.notify();
 6498            }
 6499        } else if let EditPredictionPreview::Active {
 6500            previous_scroll_position,
 6501            since,
 6502        } = self.edit_prediction_preview
 6503        {
 6504            if let (Some(previous_scroll_position), Some(position_map)) =
 6505                (previous_scroll_position, self.last_position_map.as_ref())
 6506            {
 6507                self.set_scroll_position(
 6508                    previous_scroll_position
 6509                        .scroll_position(&position_map.snapshot.display_snapshot),
 6510                    window,
 6511                    cx,
 6512                );
 6513            }
 6514
 6515            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6516                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6517            };
 6518            self.clear_row_highlights::<EditPredictionPreview>();
 6519            self.update_visible_inline_completion(window, cx);
 6520            cx.notify();
 6521        }
 6522    }
 6523
 6524    fn update_visible_inline_completion(
 6525        &mut self,
 6526        _window: &mut Window,
 6527        cx: &mut Context<Self>,
 6528    ) -> Option<()> {
 6529        let selection = self.selections.newest_anchor();
 6530        let cursor = selection.head();
 6531        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6532        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6533        let excerpt_id = cursor.excerpt_id;
 6534
 6535        let show_in_menu = self.show_edit_predictions_in_menu();
 6536        let completions_menu_has_precedence = !show_in_menu
 6537            && (self.context_menu.borrow().is_some()
 6538                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6539
 6540        if completions_menu_has_precedence
 6541            || !offset_selection.is_empty()
 6542            || self
 6543                .active_inline_completion
 6544                .as_ref()
 6545                .map_or(false, |completion| {
 6546                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6547                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6548                    !invalidation_range.contains(&offset_selection.head())
 6549                })
 6550        {
 6551            self.discard_inline_completion(false, cx);
 6552            return None;
 6553        }
 6554
 6555        self.take_active_inline_completion(cx);
 6556        let Some(provider) = self.edit_prediction_provider() else {
 6557            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6558            return None;
 6559        };
 6560
 6561        let (buffer, cursor_buffer_position) =
 6562            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6563
 6564        self.edit_prediction_settings =
 6565            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6566
 6567        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6568
 6569        if self.edit_prediction_indent_conflict {
 6570            let cursor_point = cursor.to_point(&multibuffer);
 6571
 6572            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6573
 6574            if let Some((_, indent)) = indents.iter().next() {
 6575                if indent.len == cursor_point.column {
 6576                    self.edit_prediction_indent_conflict = false;
 6577                }
 6578            }
 6579        }
 6580
 6581        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6582        let edits = inline_completion
 6583            .edits
 6584            .into_iter()
 6585            .flat_map(|(range, new_text)| {
 6586                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6587                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6588                Some((start..end, new_text))
 6589            })
 6590            .collect::<Vec<_>>();
 6591        if edits.is_empty() {
 6592            return None;
 6593        }
 6594
 6595        let first_edit_start = edits.first().unwrap().0.start;
 6596        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6597        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6598
 6599        let last_edit_end = edits.last().unwrap().0.end;
 6600        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6601        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6602
 6603        let cursor_row = cursor.to_point(&multibuffer).row;
 6604
 6605        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6606
 6607        let mut inlay_ids = Vec::new();
 6608        let invalidation_row_range;
 6609        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6610            Some(cursor_row..edit_end_row)
 6611        } else if cursor_row > edit_end_row {
 6612            Some(edit_start_row..cursor_row)
 6613        } else {
 6614            None
 6615        };
 6616        let is_move =
 6617            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6618        let completion = if is_move {
 6619            invalidation_row_range =
 6620                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6621            let target = first_edit_start;
 6622            InlineCompletion::Move { target, snapshot }
 6623        } else {
 6624            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6625                && !self.inline_completions_hidden_for_vim_mode;
 6626
 6627            if show_completions_in_buffer {
 6628                if edits
 6629                    .iter()
 6630                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6631                {
 6632                    let mut inlays = Vec::new();
 6633                    for (range, new_text) in &edits {
 6634                        let inlay = Inlay::inline_completion(
 6635                            post_inc(&mut self.next_inlay_id),
 6636                            range.start,
 6637                            new_text.as_str(),
 6638                        );
 6639                        inlay_ids.push(inlay.id);
 6640                        inlays.push(inlay);
 6641                    }
 6642
 6643                    self.splice_inlays(&[], inlays, cx);
 6644                } else {
 6645                    let background_color = cx.theme().status().deleted_background;
 6646                    self.highlight_text::<InlineCompletionHighlight>(
 6647                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6648                        HighlightStyle {
 6649                            background_color: Some(background_color),
 6650                            ..Default::default()
 6651                        },
 6652                        cx,
 6653                    );
 6654                }
 6655            }
 6656
 6657            invalidation_row_range = edit_start_row..edit_end_row;
 6658
 6659            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6660                if provider.show_tab_accept_marker() {
 6661                    EditDisplayMode::TabAccept
 6662                } else {
 6663                    EditDisplayMode::Inline
 6664                }
 6665            } else {
 6666                EditDisplayMode::DiffPopover
 6667            };
 6668
 6669            InlineCompletion::Edit {
 6670                edits,
 6671                edit_preview: inline_completion.edit_preview,
 6672                display_mode,
 6673                snapshot,
 6674            }
 6675        };
 6676
 6677        let invalidation_range = multibuffer
 6678            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6679            ..multibuffer.anchor_after(Point::new(
 6680                invalidation_row_range.end,
 6681                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6682            ));
 6683
 6684        self.stale_inline_completion_in_menu = None;
 6685        self.active_inline_completion = Some(InlineCompletionState {
 6686            inlay_ids,
 6687            completion,
 6688            completion_id: inline_completion.id,
 6689            invalidation_range,
 6690        });
 6691
 6692        cx.notify();
 6693
 6694        Some(())
 6695    }
 6696
 6697    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6698        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6699    }
 6700
 6701    fn clear_tasks(&mut self) {
 6702        self.tasks.clear()
 6703    }
 6704
 6705    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6706        if self.tasks.insert(key, value).is_some() {
 6707            // This case should hopefully be rare, but just in case...
 6708            log::error!(
 6709                "multiple different run targets found on a single line, only the last target will be rendered"
 6710            )
 6711        }
 6712    }
 6713
 6714    /// Get all display points of breakpoints that will be rendered within editor
 6715    ///
 6716    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6717    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6718    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6719    fn active_breakpoints(
 6720        &self,
 6721        range: Range<DisplayRow>,
 6722        window: &mut Window,
 6723        cx: &mut Context<Self>,
 6724    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6725        let mut breakpoint_display_points = HashMap::default();
 6726
 6727        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6728            return breakpoint_display_points;
 6729        };
 6730
 6731        let snapshot = self.snapshot(window, cx);
 6732
 6733        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6734        let Some(project) = self.project.as_ref() else {
 6735            return breakpoint_display_points;
 6736        };
 6737
 6738        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6739            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6740
 6741        for (buffer_snapshot, range, excerpt_id) in
 6742            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6743        {
 6744            let Some(buffer) = project.read_with(cx, |this, cx| {
 6745                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6746            }) else {
 6747                continue;
 6748            };
 6749            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6750                &buffer,
 6751                Some(
 6752                    buffer_snapshot.anchor_before(range.start)
 6753                        ..buffer_snapshot.anchor_after(range.end),
 6754                ),
 6755                buffer_snapshot,
 6756                cx,
 6757            );
 6758            for (anchor, breakpoint) in breakpoints {
 6759                let multi_buffer_anchor =
 6760                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6761                let position = multi_buffer_anchor
 6762                    .to_point(&multi_buffer_snapshot)
 6763                    .to_display_point(&snapshot);
 6764
 6765                breakpoint_display_points
 6766                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6767            }
 6768        }
 6769
 6770        breakpoint_display_points
 6771    }
 6772
 6773    fn breakpoint_context_menu(
 6774        &self,
 6775        anchor: Anchor,
 6776        window: &mut Window,
 6777        cx: &mut Context<Self>,
 6778    ) -> Entity<ui::ContextMenu> {
 6779        let weak_editor = cx.weak_entity();
 6780        let focus_handle = self.focus_handle(cx);
 6781
 6782        let row = self
 6783            .buffer
 6784            .read(cx)
 6785            .snapshot(cx)
 6786            .summary_for_anchor::<Point>(&anchor)
 6787            .row;
 6788
 6789        let breakpoint = self
 6790            .breakpoint_at_row(row, window, cx)
 6791            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6792
 6793        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6794            "Edit Log Breakpoint"
 6795        } else {
 6796            "Set Log Breakpoint"
 6797        };
 6798
 6799        let condition_breakpoint_msg = if breakpoint
 6800            .as_ref()
 6801            .is_some_and(|bp| bp.1.condition.is_some())
 6802        {
 6803            "Edit Condition Breakpoint"
 6804        } else {
 6805            "Set Condition Breakpoint"
 6806        };
 6807
 6808        let hit_condition_breakpoint_msg = if breakpoint
 6809            .as_ref()
 6810            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6811        {
 6812            "Edit Hit Condition Breakpoint"
 6813        } else {
 6814            "Set Hit Condition Breakpoint"
 6815        };
 6816
 6817        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6818            "Unset Breakpoint"
 6819        } else {
 6820            "Set Breakpoint"
 6821        };
 6822
 6823        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6824            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6825
 6826        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6827            BreakpointState::Enabled => Some("Disable"),
 6828            BreakpointState::Disabled => Some("Enable"),
 6829        });
 6830
 6831        let (anchor, breakpoint) =
 6832            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6833
 6834        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6835            menu.on_blur_subscription(Subscription::new(|| {}))
 6836                .context(focus_handle)
 6837                .when(run_to_cursor, |this| {
 6838                    let weak_editor = weak_editor.clone();
 6839                    this.entry("Run to cursor", None, move |window, cx| {
 6840                        weak_editor
 6841                            .update(cx, |editor, cx| {
 6842                                editor.change_selections(None, window, cx, |s| {
 6843                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6844                                });
 6845                            })
 6846                            .ok();
 6847
 6848                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6849                    })
 6850                    .separator()
 6851                })
 6852                .when_some(toggle_state_msg, |this, msg| {
 6853                    this.entry(msg, None, {
 6854                        let weak_editor = weak_editor.clone();
 6855                        let breakpoint = breakpoint.clone();
 6856                        move |_window, cx| {
 6857                            weak_editor
 6858                                .update(cx, |this, cx| {
 6859                                    this.edit_breakpoint_at_anchor(
 6860                                        anchor,
 6861                                        breakpoint.as_ref().clone(),
 6862                                        BreakpointEditAction::InvertState,
 6863                                        cx,
 6864                                    );
 6865                                })
 6866                                .log_err();
 6867                        }
 6868                    })
 6869                })
 6870                .entry(set_breakpoint_msg, None, {
 6871                    let weak_editor = weak_editor.clone();
 6872                    let breakpoint = breakpoint.clone();
 6873                    move |_window, cx| {
 6874                        weak_editor
 6875                            .update(cx, |this, cx| {
 6876                                this.edit_breakpoint_at_anchor(
 6877                                    anchor,
 6878                                    breakpoint.as_ref().clone(),
 6879                                    BreakpointEditAction::Toggle,
 6880                                    cx,
 6881                                );
 6882                            })
 6883                            .log_err();
 6884                    }
 6885                })
 6886                .entry(log_breakpoint_msg, None, {
 6887                    let breakpoint = breakpoint.clone();
 6888                    let weak_editor = weak_editor.clone();
 6889                    move |window, cx| {
 6890                        weak_editor
 6891                            .update(cx, |this, cx| {
 6892                                this.add_edit_breakpoint_block(
 6893                                    anchor,
 6894                                    breakpoint.as_ref(),
 6895                                    BreakpointPromptEditAction::Log,
 6896                                    window,
 6897                                    cx,
 6898                                );
 6899                            })
 6900                            .log_err();
 6901                    }
 6902                })
 6903                .entry(condition_breakpoint_msg, None, {
 6904                    let breakpoint = breakpoint.clone();
 6905                    let weak_editor = weak_editor.clone();
 6906                    move |window, cx| {
 6907                        weak_editor
 6908                            .update(cx, |this, cx| {
 6909                                this.add_edit_breakpoint_block(
 6910                                    anchor,
 6911                                    breakpoint.as_ref(),
 6912                                    BreakpointPromptEditAction::Condition,
 6913                                    window,
 6914                                    cx,
 6915                                );
 6916                            })
 6917                            .log_err();
 6918                    }
 6919                })
 6920                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6921                    weak_editor
 6922                        .update(cx, |this, cx| {
 6923                            this.add_edit_breakpoint_block(
 6924                                anchor,
 6925                                breakpoint.as_ref(),
 6926                                BreakpointPromptEditAction::HitCondition,
 6927                                window,
 6928                                cx,
 6929                            );
 6930                        })
 6931                        .log_err();
 6932                })
 6933        })
 6934    }
 6935
 6936    fn render_breakpoint(
 6937        &self,
 6938        position: Anchor,
 6939        row: DisplayRow,
 6940        breakpoint: &Breakpoint,
 6941        cx: &mut Context<Self>,
 6942    ) -> IconButton {
 6943        // Is it a breakpoint that shows up when hovering over gutter?
 6944        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 6945            (false, false),
 6946            |PhantomBreakpointIndicator {
 6947                 is_active,
 6948                 display_row,
 6949                 collides_with_existing_breakpoint,
 6950             }| {
 6951                (
 6952                    is_active && display_row == row,
 6953                    collides_with_existing_breakpoint,
 6954                )
 6955            },
 6956        );
 6957
 6958        let (color, icon) = {
 6959            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6960                (false, false) => ui::IconName::DebugBreakpoint,
 6961                (true, false) => ui::IconName::DebugLogBreakpoint,
 6962                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6963                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6964            };
 6965
 6966            let color = if is_phantom {
 6967                Color::Hint
 6968            } else {
 6969                Color::Debugger
 6970            };
 6971
 6972            (color, icon)
 6973        };
 6974
 6975        let breakpoint = Arc::from(breakpoint.clone());
 6976
 6977        let alt_as_text = gpui::Keystroke {
 6978            modifiers: Modifiers::secondary_key(),
 6979            ..Default::default()
 6980        };
 6981        let primary_action_text = if breakpoint.is_disabled() {
 6982            "enable"
 6983        } else if is_phantom && !collides_with_existing {
 6984            "set"
 6985        } else {
 6986            "unset"
 6987        };
 6988        let mut primary_text = format!("Click to {primary_action_text}");
 6989        if collides_with_existing && !breakpoint.is_disabled() {
 6990            use std::fmt::Write;
 6991            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 6992        }
 6993        let primary_text = SharedString::from(primary_text);
 6994        let focus_handle = self.focus_handle.clone();
 6995        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6996            .icon_size(IconSize::XSmall)
 6997            .size(ui::ButtonSize::None)
 6998            .icon_color(color)
 6999            .style(ButtonStyle::Transparent)
 7000            .on_click(cx.listener({
 7001                let breakpoint = breakpoint.clone();
 7002
 7003                move |editor, event: &ClickEvent, window, cx| {
 7004                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7005                        BreakpointEditAction::InvertState
 7006                    } else {
 7007                        BreakpointEditAction::Toggle
 7008                    };
 7009
 7010                    window.focus(&editor.focus_handle(cx));
 7011                    editor.edit_breakpoint_at_anchor(
 7012                        position,
 7013                        breakpoint.as_ref().clone(),
 7014                        edit_action,
 7015                        cx,
 7016                    );
 7017                }
 7018            }))
 7019            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7020                editor.set_breakpoint_context_menu(
 7021                    row,
 7022                    Some(position),
 7023                    event.down.position,
 7024                    window,
 7025                    cx,
 7026                );
 7027            }))
 7028            .tooltip(move |window, cx| {
 7029                Tooltip::with_meta_in(
 7030                    primary_text.clone(),
 7031                    None,
 7032                    "Right-click for more options",
 7033                    &focus_handle,
 7034                    window,
 7035                    cx,
 7036                )
 7037            })
 7038    }
 7039
 7040    fn build_tasks_context(
 7041        project: &Entity<Project>,
 7042        buffer: &Entity<Buffer>,
 7043        buffer_row: u32,
 7044        tasks: &Arc<RunnableTasks>,
 7045        cx: &mut Context<Self>,
 7046    ) -> Task<Option<task::TaskContext>> {
 7047        let position = Point::new(buffer_row, tasks.column);
 7048        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7049        let location = Location {
 7050            buffer: buffer.clone(),
 7051            range: range_start..range_start,
 7052        };
 7053        // Fill in the environmental variables from the tree-sitter captures
 7054        let mut captured_task_variables = TaskVariables::default();
 7055        for (capture_name, value) in tasks.extra_variables.clone() {
 7056            captured_task_variables.insert(
 7057                task::VariableName::Custom(capture_name.into()),
 7058                value.clone(),
 7059            );
 7060        }
 7061        project.update(cx, |project, cx| {
 7062            project.task_store().update(cx, |task_store, cx| {
 7063                task_store.task_context_for_location(captured_task_variables, location, cx)
 7064            })
 7065        })
 7066    }
 7067
 7068    pub fn spawn_nearest_task(
 7069        &mut self,
 7070        action: &SpawnNearestTask,
 7071        window: &mut Window,
 7072        cx: &mut Context<Self>,
 7073    ) {
 7074        let Some((workspace, _)) = self.workspace.clone() else {
 7075            return;
 7076        };
 7077        let Some(project) = self.project.clone() else {
 7078            return;
 7079        };
 7080
 7081        // Try to find a closest, enclosing node using tree-sitter that has a
 7082        // task
 7083        let Some((buffer, buffer_row, tasks)) = self
 7084            .find_enclosing_node_task(cx)
 7085            // Or find the task that's closest in row-distance.
 7086            .or_else(|| self.find_closest_task(cx))
 7087        else {
 7088            return;
 7089        };
 7090
 7091        let reveal_strategy = action.reveal;
 7092        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7093        cx.spawn_in(window, async move |_, cx| {
 7094            let context = task_context.await?;
 7095            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7096
 7097            let resolved = &mut resolved_task.resolved;
 7098            resolved.reveal = reveal_strategy;
 7099
 7100            workspace
 7101                .update_in(cx, |workspace, window, cx| {
 7102                    workspace.schedule_resolved_task(
 7103                        task_source_kind,
 7104                        resolved_task,
 7105                        false,
 7106                        window,
 7107                        cx,
 7108                    );
 7109                })
 7110                .ok()
 7111        })
 7112        .detach();
 7113    }
 7114
 7115    fn find_closest_task(
 7116        &mut self,
 7117        cx: &mut Context<Self>,
 7118    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7119        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7120
 7121        let ((buffer_id, row), tasks) = self
 7122            .tasks
 7123            .iter()
 7124            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7125
 7126        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7127        let tasks = Arc::new(tasks.to_owned());
 7128        Some((buffer, *row, tasks))
 7129    }
 7130
 7131    fn find_enclosing_node_task(
 7132        &mut self,
 7133        cx: &mut Context<Self>,
 7134    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7135        let snapshot = self.buffer.read(cx).snapshot(cx);
 7136        let offset = self.selections.newest::<usize>(cx).head();
 7137        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7138        let buffer_id = excerpt.buffer().remote_id();
 7139
 7140        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7141        let mut cursor = layer.node().walk();
 7142
 7143        while cursor.goto_first_child_for_byte(offset).is_some() {
 7144            if cursor.node().end_byte() == offset {
 7145                cursor.goto_next_sibling();
 7146            }
 7147        }
 7148
 7149        // Ascend to the smallest ancestor that contains the range and has a task.
 7150        loop {
 7151            let node = cursor.node();
 7152            let node_range = node.byte_range();
 7153            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7154
 7155            // Check if this node contains our offset
 7156            if node_range.start <= offset && node_range.end >= offset {
 7157                // If it contains offset, check for task
 7158                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7159                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7160                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7161                }
 7162            }
 7163
 7164            if !cursor.goto_parent() {
 7165                break;
 7166            }
 7167        }
 7168        None
 7169    }
 7170
 7171    fn render_run_indicator(
 7172        &self,
 7173        _style: &EditorStyle,
 7174        is_active: bool,
 7175        row: DisplayRow,
 7176        breakpoint: Option<(Anchor, Breakpoint)>,
 7177        cx: &mut Context<Self>,
 7178    ) -> IconButton {
 7179        let color = Color::Muted;
 7180        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7181
 7182        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7183            .shape(ui::IconButtonShape::Square)
 7184            .icon_size(IconSize::XSmall)
 7185            .icon_color(color)
 7186            .toggle_state(is_active)
 7187            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7188                let quick_launch = e.down.button == MouseButton::Left;
 7189                window.focus(&editor.focus_handle(cx));
 7190                editor.toggle_code_actions(
 7191                    &ToggleCodeActions {
 7192                        deployed_from_indicator: Some(row),
 7193                        quick_launch,
 7194                    },
 7195                    window,
 7196                    cx,
 7197                );
 7198            }))
 7199            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7200                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7201            }))
 7202    }
 7203
 7204    pub fn context_menu_visible(&self) -> bool {
 7205        !self.edit_prediction_preview_is_active()
 7206            && self
 7207                .context_menu
 7208                .borrow()
 7209                .as_ref()
 7210                .map_or(false, |menu| menu.visible())
 7211    }
 7212
 7213    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7214        self.context_menu
 7215            .borrow()
 7216            .as_ref()
 7217            .map(|menu| menu.origin())
 7218    }
 7219
 7220    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7221        self.context_menu_options = Some(options);
 7222    }
 7223
 7224    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7225    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7226
 7227    fn render_edit_prediction_popover(
 7228        &mut self,
 7229        text_bounds: &Bounds<Pixels>,
 7230        content_origin: gpui::Point<Pixels>,
 7231        editor_snapshot: &EditorSnapshot,
 7232        visible_row_range: Range<DisplayRow>,
 7233        scroll_top: f32,
 7234        scroll_bottom: f32,
 7235        line_layouts: &[LineWithInvisibles],
 7236        line_height: Pixels,
 7237        scroll_pixel_position: gpui::Point<Pixels>,
 7238        newest_selection_head: Option<DisplayPoint>,
 7239        editor_width: Pixels,
 7240        style: &EditorStyle,
 7241        window: &mut Window,
 7242        cx: &mut App,
 7243    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7244        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7245
 7246        if self.edit_prediction_visible_in_cursor_popover(true) {
 7247            return None;
 7248        }
 7249
 7250        match &active_inline_completion.completion {
 7251            InlineCompletion::Move { target, .. } => {
 7252                let target_display_point = target.to_display_point(editor_snapshot);
 7253
 7254                if self.edit_prediction_requires_modifier() {
 7255                    if !self.edit_prediction_preview_is_active() {
 7256                        return None;
 7257                    }
 7258
 7259                    self.render_edit_prediction_modifier_jump_popover(
 7260                        text_bounds,
 7261                        content_origin,
 7262                        visible_row_range,
 7263                        line_layouts,
 7264                        line_height,
 7265                        scroll_pixel_position,
 7266                        newest_selection_head,
 7267                        target_display_point,
 7268                        window,
 7269                        cx,
 7270                    )
 7271                } else {
 7272                    self.render_edit_prediction_eager_jump_popover(
 7273                        text_bounds,
 7274                        content_origin,
 7275                        editor_snapshot,
 7276                        visible_row_range,
 7277                        scroll_top,
 7278                        scroll_bottom,
 7279                        line_height,
 7280                        scroll_pixel_position,
 7281                        target_display_point,
 7282                        editor_width,
 7283                        window,
 7284                        cx,
 7285                    )
 7286                }
 7287            }
 7288            InlineCompletion::Edit {
 7289                display_mode: EditDisplayMode::Inline,
 7290                ..
 7291            } => None,
 7292            InlineCompletion::Edit {
 7293                display_mode: EditDisplayMode::TabAccept,
 7294                edits,
 7295                ..
 7296            } => {
 7297                let range = &edits.first()?.0;
 7298                let target_display_point = range.end.to_display_point(editor_snapshot);
 7299
 7300                self.render_edit_prediction_end_of_line_popover(
 7301                    "Accept",
 7302                    editor_snapshot,
 7303                    visible_row_range,
 7304                    target_display_point,
 7305                    line_height,
 7306                    scroll_pixel_position,
 7307                    content_origin,
 7308                    editor_width,
 7309                    window,
 7310                    cx,
 7311                )
 7312            }
 7313            InlineCompletion::Edit {
 7314                edits,
 7315                edit_preview,
 7316                display_mode: EditDisplayMode::DiffPopover,
 7317                snapshot,
 7318            } => self.render_edit_prediction_diff_popover(
 7319                text_bounds,
 7320                content_origin,
 7321                editor_snapshot,
 7322                visible_row_range,
 7323                line_layouts,
 7324                line_height,
 7325                scroll_pixel_position,
 7326                newest_selection_head,
 7327                editor_width,
 7328                style,
 7329                edits,
 7330                edit_preview,
 7331                snapshot,
 7332                window,
 7333                cx,
 7334            ),
 7335        }
 7336    }
 7337
 7338    fn render_edit_prediction_modifier_jump_popover(
 7339        &mut self,
 7340        text_bounds: &Bounds<Pixels>,
 7341        content_origin: gpui::Point<Pixels>,
 7342        visible_row_range: Range<DisplayRow>,
 7343        line_layouts: &[LineWithInvisibles],
 7344        line_height: Pixels,
 7345        scroll_pixel_position: gpui::Point<Pixels>,
 7346        newest_selection_head: Option<DisplayPoint>,
 7347        target_display_point: DisplayPoint,
 7348        window: &mut Window,
 7349        cx: &mut App,
 7350    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7351        let scrolled_content_origin =
 7352            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7353
 7354        const SCROLL_PADDING_Y: Pixels = px(12.);
 7355
 7356        if target_display_point.row() < visible_row_range.start {
 7357            return self.render_edit_prediction_scroll_popover(
 7358                |_| SCROLL_PADDING_Y,
 7359                IconName::ArrowUp,
 7360                visible_row_range,
 7361                line_layouts,
 7362                newest_selection_head,
 7363                scrolled_content_origin,
 7364                window,
 7365                cx,
 7366            );
 7367        } else if target_display_point.row() >= visible_row_range.end {
 7368            return self.render_edit_prediction_scroll_popover(
 7369                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7370                IconName::ArrowDown,
 7371                visible_row_range,
 7372                line_layouts,
 7373                newest_selection_head,
 7374                scrolled_content_origin,
 7375                window,
 7376                cx,
 7377            );
 7378        }
 7379
 7380        const POLE_WIDTH: Pixels = px(2.);
 7381
 7382        let line_layout =
 7383            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7384        let target_column = target_display_point.column() as usize;
 7385
 7386        let target_x = line_layout.x_for_index(target_column);
 7387        let target_y =
 7388            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7389
 7390        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7391
 7392        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7393        border_color.l += 0.001;
 7394
 7395        let mut element = v_flex()
 7396            .items_end()
 7397            .when(flag_on_right, |el| el.items_start())
 7398            .child(if flag_on_right {
 7399                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7400                    .rounded_bl(px(0.))
 7401                    .rounded_tl(px(0.))
 7402                    .border_l_2()
 7403                    .border_color(border_color)
 7404            } else {
 7405                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7406                    .rounded_br(px(0.))
 7407                    .rounded_tr(px(0.))
 7408                    .border_r_2()
 7409                    .border_color(border_color)
 7410            })
 7411            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7412            .into_any();
 7413
 7414        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7415
 7416        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7417            - point(
 7418                if flag_on_right {
 7419                    POLE_WIDTH
 7420                } else {
 7421                    size.width - POLE_WIDTH
 7422                },
 7423                size.height - line_height,
 7424            );
 7425
 7426        origin.x = origin.x.max(content_origin.x);
 7427
 7428        element.prepaint_at(origin, window, cx);
 7429
 7430        Some((element, origin))
 7431    }
 7432
 7433    fn render_edit_prediction_scroll_popover(
 7434        &mut self,
 7435        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7436        scroll_icon: IconName,
 7437        visible_row_range: Range<DisplayRow>,
 7438        line_layouts: &[LineWithInvisibles],
 7439        newest_selection_head: Option<DisplayPoint>,
 7440        scrolled_content_origin: gpui::Point<Pixels>,
 7441        window: &mut Window,
 7442        cx: &mut App,
 7443    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7444        let mut element = self
 7445            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7446            .into_any();
 7447
 7448        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7449
 7450        let cursor = newest_selection_head?;
 7451        let cursor_row_layout =
 7452            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7453        let cursor_column = cursor.column() as usize;
 7454
 7455        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7456
 7457        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7458
 7459        element.prepaint_at(origin, window, cx);
 7460        Some((element, origin))
 7461    }
 7462
 7463    fn render_edit_prediction_eager_jump_popover(
 7464        &mut self,
 7465        text_bounds: &Bounds<Pixels>,
 7466        content_origin: gpui::Point<Pixels>,
 7467        editor_snapshot: &EditorSnapshot,
 7468        visible_row_range: Range<DisplayRow>,
 7469        scroll_top: f32,
 7470        scroll_bottom: f32,
 7471        line_height: Pixels,
 7472        scroll_pixel_position: gpui::Point<Pixels>,
 7473        target_display_point: DisplayPoint,
 7474        editor_width: Pixels,
 7475        window: &mut Window,
 7476        cx: &mut App,
 7477    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7478        if target_display_point.row().as_f32() < scroll_top {
 7479            let mut element = self
 7480                .render_edit_prediction_line_popover(
 7481                    "Jump to Edit",
 7482                    Some(IconName::ArrowUp),
 7483                    window,
 7484                    cx,
 7485                )?
 7486                .into_any();
 7487
 7488            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7489            let offset = point(
 7490                (text_bounds.size.width - size.width) / 2.,
 7491                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7492            );
 7493
 7494            let origin = text_bounds.origin + offset;
 7495            element.prepaint_at(origin, window, cx);
 7496            Some((element, origin))
 7497        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7498            let mut element = self
 7499                .render_edit_prediction_line_popover(
 7500                    "Jump to Edit",
 7501                    Some(IconName::ArrowDown),
 7502                    window,
 7503                    cx,
 7504                )?
 7505                .into_any();
 7506
 7507            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7508            let offset = point(
 7509                (text_bounds.size.width - size.width) / 2.,
 7510                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7511            );
 7512
 7513            let origin = text_bounds.origin + offset;
 7514            element.prepaint_at(origin, window, cx);
 7515            Some((element, origin))
 7516        } else {
 7517            self.render_edit_prediction_end_of_line_popover(
 7518                "Jump to Edit",
 7519                editor_snapshot,
 7520                visible_row_range,
 7521                target_display_point,
 7522                line_height,
 7523                scroll_pixel_position,
 7524                content_origin,
 7525                editor_width,
 7526                window,
 7527                cx,
 7528            )
 7529        }
 7530    }
 7531
 7532    fn render_edit_prediction_end_of_line_popover(
 7533        self: &mut Editor,
 7534        label: &'static str,
 7535        editor_snapshot: &EditorSnapshot,
 7536        visible_row_range: Range<DisplayRow>,
 7537        target_display_point: DisplayPoint,
 7538        line_height: Pixels,
 7539        scroll_pixel_position: gpui::Point<Pixels>,
 7540        content_origin: gpui::Point<Pixels>,
 7541        editor_width: Pixels,
 7542        window: &mut Window,
 7543        cx: &mut App,
 7544    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7545        let target_line_end = DisplayPoint::new(
 7546            target_display_point.row(),
 7547            editor_snapshot.line_len(target_display_point.row()),
 7548        );
 7549
 7550        let mut element = self
 7551            .render_edit_prediction_line_popover(label, None, window, cx)?
 7552            .into_any();
 7553
 7554        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7555
 7556        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7557
 7558        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7559        let mut origin = start_point
 7560            + line_origin
 7561            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7562        origin.x = origin.x.max(content_origin.x);
 7563
 7564        let max_x = content_origin.x + editor_width - size.width;
 7565
 7566        if origin.x > max_x {
 7567            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7568
 7569            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7570                origin.y += offset;
 7571                IconName::ArrowUp
 7572            } else {
 7573                origin.y -= offset;
 7574                IconName::ArrowDown
 7575            };
 7576
 7577            element = self
 7578                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7579                .into_any();
 7580
 7581            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7582
 7583            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7584        }
 7585
 7586        element.prepaint_at(origin, window, cx);
 7587        Some((element, origin))
 7588    }
 7589
 7590    fn render_edit_prediction_diff_popover(
 7591        self: &Editor,
 7592        text_bounds: &Bounds<Pixels>,
 7593        content_origin: gpui::Point<Pixels>,
 7594        editor_snapshot: &EditorSnapshot,
 7595        visible_row_range: Range<DisplayRow>,
 7596        line_layouts: &[LineWithInvisibles],
 7597        line_height: Pixels,
 7598        scroll_pixel_position: gpui::Point<Pixels>,
 7599        newest_selection_head: Option<DisplayPoint>,
 7600        editor_width: Pixels,
 7601        style: &EditorStyle,
 7602        edits: &Vec<(Range<Anchor>, String)>,
 7603        edit_preview: &Option<language::EditPreview>,
 7604        snapshot: &language::BufferSnapshot,
 7605        window: &mut Window,
 7606        cx: &mut App,
 7607    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7608        let edit_start = edits
 7609            .first()
 7610            .unwrap()
 7611            .0
 7612            .start
 7613            .to_display_point(editor_snapshot);
 7614        let edit_end = edits
 7615            .last()
 7616            .unwrap()
 7617            .0
 7618            .end
 7619            .to_display_point(editor_snapshot);
 7620
 7621        let is_visible = visible_row_range.contains(&edit_start.row())
 7622            || visible_row_range.contains(&edit_end.row());
 7623        if !is_visible {
 7624            return None;
 7625        }
 7626
 7627        let highlighted_edits =
 7628            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7629
 7630        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7631        let line_count = highlighted_edits.text.lines().count();
 7632
 7633        const BORDER_WIDTH: Pixels = px(1.);
 7634
 7635        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7636        let has_keybind = keybind.is_some();
 7637
 7638        let mut element = h_flex()
 7639            .items_start()
 7640            .child(
 7641                h_flex()
 7642                    .bg(cx.theme().colors().editor_background)
 7643                    .border(BORDER_WIDTH)
 7644                    .shadow_sm()
 7645                    .border_color(cx.theme().colors().border)
 7646                    .rounded_l_lg()
 7647                    .when(line_count > 1, |el| el.rounded_br_lg())
 7648                    .pr_1()
 7649                    .child(styled_text),
 7650            )
 7651            .child(
 7652                h_flex()
 7653                    .h(line_height + BORDER_WIDTH * 2.)
 7654                    .px_1p5()
 7655                    .gap_1()
 7656                    // Workaround: For some reason, there's a gap if we don't do this
 7657                    .ml(-BORDER_WIDTH)
 7658                    .shadow(smallvec![gpui::BoxShadow {
 7659                        color: gpui::black().opacity(0.05),
 7660                        offset: point(px(1.), px(1.)),
 7661                        blur_radius: px(2.),
 7662                        spread_radius: px(0.),
 7663                    }])
 7664                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7665                    .border(BORDER_WIDTH)
 7666                    .border_color(cx.theme().colors().border)
 7667                    .rounded_r_lg()
 7668                    .id("edit_prediction_diff_popover_keybind")
 7669                    .when(!has_keybind, |el| {
 7670                        let status_colors = cx.theme().status();
 7671
 7672                        el.bg(status_colors.error_background)
 7673                            .border_color(status_colors.error.opacity(0.6))
 7674                            .child(Icon::new(IconName::Info).color(Color::Error))
 7675                            .cursor_default()
 7676                            .hoverable_tooltip(move |_window, cx| {
 7677                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7678                            })
 7679                    })
 7680                    .children(keybind),
 7681            )
 7682            .into_any();
 7683
 7684        let longest_row =
 7685            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7686        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7687            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7688        } else {
 7689            layout_line(
 7690                longest_row,
 7691                editor_snapshot,
 7692                style,
 7693                editor_width,
 7694                |_| false,
 7695                window,
 7696                cx,
 7697            )
 7698            .width
 7699        };
 7700
 7701        let viewport_bounds =
 7702            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7703                right: -EditorElement::SCROLLBAR_WIDTH,
 7704                ..Default::default()
 7705            });
 7706
 7707        let x_after_longest =
 7708            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7709                - scroll_pixel_position.x;
 7710
 7711        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7712
 7713        // Fully visible if it can be displayed within the window (allow overlapping other
 7714        // panes). However, this is only allowed if the popover starts within text_bounds.
 7715        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7716            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7717
 7718        let mut origin = if can_position_to_the_right {
 7719            point(
 7720                x_after_longest,
 7721                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7722                    - scroll_pixel_position.y,
 7723            )
 7724        } else {
 7725            let cursor_row = newest_selection_head.map(|head| head.row());
 7726            let above_edit = edit_start
 7727                .row()
 7728                .0
 7729                .checked_sub(line_count as u32)
 7730                .map(DisplayRow);
 7731            let below_edit = Some(edit_end.row() + 1);
 7732            let above_cursor =
 7733                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7734            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7735
 7736            // Place the edit popover adjacent to the edit if there is a location
 7737            // available that is onscreen and does not obscure the cursor. Otherwise,
 7738            // place it adjacent to the cursor.
 7739            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7740                .into_iter()
 7741                .flatten()
 7742                .find(|&start_row| {
 7743                    let end_row = start_row + line_count as u32;
 7744                    visible_row_range.contains(&start_row)
 7745                        && visible_row_range.contains(&end_row)
 7746                        && cursor_row.map_or(true, |cursor_row| {
 7747                            !((start_row..end_row).contains(&cursor_row))
 7748                        })
 7749                })?;
 7750
 7751            content_origin
 7752                + point(
 7753                    -scroll_pixel_position.x,
 7754                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7755                )
 7756        };
 7757
 7758        origin.x -= BORDER_WIDTH;
 7759
 7760        window.defer_draw(element, origin, 1);
 7761
 7762        // Do not return an element, since it will already be drawn due to defer_draw.
 7763        None
 7764    }
 7765
 7766    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7767        px(30.)
 7768    }
 7769
 7770    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7771        if self.read_only(cx) {
 7772            cx.theme().players().read_only()
 7773        } else {
 7774            self.style.as_ref().unwrap().local_player
 7775        }
 7776    }
 7777
 7778    fn render_edit_prediction_accept_keybind(
 7779        &self,
 7780        window: &mut Window,
 7781        cx: &App,
 7782    ) -> Option<AnyElement> {
 7783        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7784        let accept_keystroke = accept_binding.keystroke()?;
 7785
 7786        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7787
 7788        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7789            Color::Accent
 7790        } else {
 7791            Color::Muted
 7792        };
 7793
 7794        h_flex()
 7795            .px_0p5()
 7796            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7797            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7798            .text_size(TextSize::XSmall.rems(cx))
 7799            .child(h_flex().children(ui::render_modifiers(
 7800                &accept_keystroke.modifiers,
 7801                PlatformStyle::platform(),
 7802                Some(modifiers_color),
 7803                Some(IconSize::XSmall.rems().into()),
 7804                true,
 7805            )))
 7806            .when(is_platform_style_mac, |parent| {
 7807                parent.child(accept_keystroke.key.clone())
 7808            })
 7809            .when(!is_platform_style_mac, |parent| {
 7810                parent.child(
 7811                    Key::new(
 7812                        util::capitalize(&accept_keystroke.key),
 7813                        Some(Color::Default),
 7814                    )
 7815                    .size(Some(IconSize::XSmall.rems().into())),
 7816                )
 7817            })
 7818            .into_any()
 7819            .into()
 7820    }
 7821
 7822    fn render_edit_prediction_line_popover(
 7823        &self,
 7824        label: impl Into<SharedString>,
 7825        icon: Option<IconName>,
 7826        window: &mut Window,
 7827        cx: &App,
 7828    ) -> Option<Stateful<Div>> {
 7829        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7830
 7831        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7832        let has_keybind = keybind.is_some();
 7833
 7834        let result = h_flex()
 7835            .id("ep-line-popover")
 7836            .py_0p5()
 7837            .pl_1()
 7838            .pr(padding_right)
 7839            .gap_1()
 7840            .rounded_md()
 7841            .border_1()
 7842            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7843            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7844            .shadow_sm()
 7845            .when(!has_keybind, |el| {
 7846                let status_colors = cx.theme().status();
 7847
 7848                el.bg(status_colors.error_background)
 7849                    .border_color(status_colors.error.opacity(0.6))
 7850                    .pl_2()
 7851                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7852                    .cursor_default()
 7853                    .hoverable_tooltip(move |_window, cx| {
 7854                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7855                    })
 7856            })
 7857            .children(keybind)
 7858            .child(
 7859                Label::new(label)
 7860                    .size(LabelSize::Small)
 7861                    .when(!has_keybind, |el| {
 7862                        el.color(cx.theme().status().error.into()).strikethrough()
 7863                    }),
 7864            )
 7865            .when(!has_keybind, |el| {
 7866                el.child(
 7867                    h_flex().ml_1().child(
 7868                        Icon::new(IconName::Info)
 7869                            .size(IconSize::Small)
 7870                            .color(cx.theme().status().error.into()),
 7871                    ),
 7872                )
 7873            })
 7874            .when_some(icon, |element, icon| {
 7875                element.child(
 7876                    div()
 7877                        .mt(px(1.5))
 7878                        .child(Icon::new(icon).size(IconSize::Small)),
 7879                )
 7880            });
 7881
 7882        Some(result)
 7883    }
 7884
 7885    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7886        let accent_color = cx.theme().colors().text_accent;
 7887        let editor_bg_color = cx.theme().colors().editor_background;
 7888        editor_bg_color.blend(accent_color.opacity(0.1))
 7889    }
 7890
 7891    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7892        let accent_color = cx.theme().colors().text_accent;
 7893        let editor_bg_color = cx.theme().colors().editor_background;
 7894        editor_bg_color.blend(accent_color.opacity(0.6))
 7895    }
 7896
 7897    fn render_edit_prediction_cursor_popover(
 7898        &self,
 7899        min_width: Pixels,
 7900        max_width: Pixels,
 7901        cursor_point: Point,
 7902        style: &EditorStyle,
 7903        accept_keystroke: Option<&gpui::Keystroke>,
 7904        _window: &Window,
 7905        cx: &mut Context<Editor>,
 7906    ) -> Option<AnyElement> {
 7907        let provider = self.edit_prediction_provider.as_ref()?;
 7908
 7909        if provider.provider.needs_terms_acceptance(cx) {
 7910            return Some(
 7911                h_flex()
 7912                    .min_w(min_width)
 7913                    .flex_1()
 7914                    .px_2()
 7915                    .py_1()
 7916                    .gap_3()
 7917                    .elevation_2(cx)
 7918                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7919                    .id("accept-terms")
 7920                    .cursor_pointer()
 7921                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7922                    .on_click(cx.listener(|this, _event, window, cx| {
 7923                        cx.stop_propagation();
 7924                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7925                        window.dispatch_action(
 7926                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7927                            cx,
 7928                        );
 7929                    }))
 7930                    .child(
 7931                        h_flex()
 7932                            .flex_1()
 7933                            .gap_2()
 7934                            .child(Icon::new(IconName::ZedPredict))
 7935                            .child(Label::new("Accept Terms of Service"))
 7936                            .child(div().w_full())
 7937                            .child(
 7938                                Icon::new(IconName::ArrowUpRight)
 7939                                    .color(Color::Muted)
 7940                                    .size(IconSize::Small),
 7941                            )
 7942                            .into_any_element(),
 7943                    )
 7944                    .into_any(),
 7945            );
 7946        }
 7947
 7948        let is_refreshing = provider.provider.is_refreshing(cx);
 7949
 7950        fn pending_completion_container() -> Div {
 7951            h_flex()
 7952                .h_full()
 7953                .flex_1()
 7954                .gap_2()
 7955                .child(Icon::new(IconName::ZedPredict))
 7956        }
 7957
 7958        let completion = match &self.active_inline_completion {
 7959            Some(prediction) => {
 7960                if !self.has_visible_completions_menu() {
 7961                    const RADIUS: Pixels = px(6.);
 7962                    const BORDER_WIDTH: Pixels = px(1.);
 7963
 7964                    return Some(
 7965                        h_flex()
 7966                            .elevation_2(cx)
 7967                            .border(BORDER_WIDTH)
 7968                            .border_color(cx.theme().colors().border)
 7969                            .when(accept_keystroke.is_none(), |el| {
 7970                                el.border_color(cx.theme().status().error)
 7971                            })
 7972                            .rounded(RADIUS)
 7973                            .rounded_tl(px(0.))
 7974                            .overflow_hidden()
 7975                            .child(div().px_1p5().child(match &prediction.completion {
 7976                                InlineCompletion::Move { target, snapshot } => {
 7977                                    use text::ToPoint as _;
 7978                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7979                                    {
 7980                                        Icon::new(IconName::ZedPredictDown)
 7981                                    } else {
 7982                                        Icon::new(IconName::ZedPredictUp)
 7983                                    }
 7984                                }
 7985                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7986                            }))
 7987                            .child(
 7988                                h_flex()
 7989                                    .gap_1()
 7990                                    .py_1()
 7991                                    .px_2()
 7992                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7993                                    .border_l_1()
 7994                                    .border_color(cx.theme().colors().border)
 7995                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7996                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7997                                        el.child(
 7998                                            Label::new("Hold")
 7999                                                .size(LabelSize::Small)
 8000                                                .when(accept_keystroke.is_none(), |el| {
 8001                                                    el.strikethrough()
 8002                                                })
 8003                                                .line_height_style(LineHeightStyle::UiLabel),
 8004                                        )
 8005                                    })
 8006                                    .id("edit_prediction_cursor_popover_keybind")
 8007                                    .when(accept_keystroke.is_none(), |el| {
 8008                                        let status_colors = cx.theme().status();
 8009
 8010                                        el.bg(status_colors.error_background)
 8011                                            .border_color(status_colors.error.opacity(0.6))
 8012                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8013                                            .cursor_default()
 8014                                            .hoverable_tooltip(move |_window, cx| {
 8015                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8016                                                    .into()
 8017                                            })
 8018                                    })
 8019                                    .when_some(
 8020                                        accept_keystroke.as_ref(),
 8021                                        |el, accept_keystroke| {
 8022                                            el.child(h_flex().children(ui::render_modifiers(
 8023                                                &accept_keystroke.modifiers,
 8024                                                PlatformStyle::platform(),
 8025                                                Some(Color::Default),
 8026                                                Some(IconSize::XSmall.rems().into()),
 8027                                                false,
 8028                                            )))
 8029                                        },
 8030                                    ),
 8031                            )
 8032                            .into_any(),
 8033                    );
 8034                }
 8035
 8036                self.render_edit_prediction_cursor_popover_preview(
 8037                    prediction,
 8038                    cursor_point,
 8039                    style,
 8040                    cx,
 8041                )?
 8042            }
 8043
 8044            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8045                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8046                    stale_completion,
 8047                    cursor_point,
 8048                    style,
 8049                    cx,
 8050                )?,
 8051
 8052                None => {
 8053                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8054                }
 8055            },
 8056
 8057            None => pending_completion_container().child(Label::new("No Prediction")),
 8058        };
 8059
 8060        let completion = if is_refreshing {
 8061            completion
 8062                .with_animation(
 8063                    "loading-completion",
 8064                    Animation::new(Duration::from_secs(2))
 8065                        .repeat()
 8066                        .with_easing(pulsating_between(0.4, 0.8)),
 8067                    |label, delta| label.opacity(delta),
 8068                )
 8069                .into_any_element()
 8070        } else {
 8071            completion.into_any_element()
 8072        };
 8073
 8074        let has_completion = self.active_inline_completion.is_some();
 8075
 8076        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8077        Some(
 8078            h_flex()
 8079                .min_w(min_width)
 8080                .max_w(max_width)
 8081                .flex_1()
 8082                .elevation_2(cx)
 8083                .border_color(cx.theme().colors().border)
 8084                .child(
 8085                    div()
 8086                        .flex_1()
 8087                        .py_1()
 8088                        .px_2()
 8089                        .overflow_hidden()
 8090                        .child(completion),
 8091                )
 8092                .when_some(accept_keystroke, |el, accept_keystroke| {
 8093                    if !accept_keystroke.modifiers.modified() {
 8094                        return el;
 8095                    }
 8096
 8097                    el.child(
 8098                        h_flex()
 8099                            .h_full()
 8100                            .border_l_1()
 8101                            .rounded_r_lg()
 8102                            .border_color(cx.theme().colors().border)
 8103                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8104                            .gap_1()
 8105                            .py_1()
 8106                            .px_2()
 8107                            .child(
 8108                                h_flex()
 8109                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8110                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8111                                    .child(h_flex().children(ui::render_modifiers(
 8112                                        &accept_keystroke.modifiers,
 8113                                        PlatformStyle::platform(),
 8114                                        Some(if !has_completion {
 8115                                            Color::Muted
 8116                                        } else {
 8117                                            Color::Default
 8118                                        }),
 8119                                        None,
 8120                                        false,
 8121                                    ))),
 8122                            )
 8123                            .child(Label::new("Preview").into_any_element())
 8124                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8125                    )
 8126                })
 8127                .into_any(),
 8128        )
 8129    }
 8130
 8131    fn render_edit_prediction_cursor_popover_preview(
 8132        &self,
 8133        completion: &InlineCompletionState,
 8134        cursor_point: Point,
 8135        style: &EditorStyle,
 8136        cx: &mut Context<Editor>,
 8137    ) -> Option<Div> {
 8138        use text::ToPoint as _;
 8139
 8140        fn render_relative_row_jump(
 8141            prefix: impl Into<String>,
 8142            current_row: u32,
 8143            target_row: u32,
 8144        ) -> Div {
 8145            let (row_diff, arrow) = if target_row < current_row {
 8146                (current_row - target_row, IconName::ArrowUp)
 8147            } else {
 8148                (target_row - current_row, IconName::ArrowDown)
 8149            };
 8150
 8151            h_flex()
 8152                .child(
 8153                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8154                        .color(Color::Muted)
 8155                        .size(LabelSize::Small),
 8156                )
 8157                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8158        }
 8159
 8160        match &completion.completion {
 8161            InlineCompletion::Move {
 8162                target, snapshot, ..
 8163            } => Some(
 8164                h_flex()
 8165                    .px_2()
 8166                    .gap_2()
 8167                    .flex_1()
 8168                    .child(
 8169                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8170                            Icon::new(IconName::ZedPredictDown)
 8171                        } else {
 8172                            Icon::new(IconName::ZedPredictUp)
 8173                        },
 8174                    )
 8175                    .child(Label::new("Jump to Edit")),
 8176            ),
 8177
 8178            InlineCompletion::Edit {
 8179                edits,
 8180                edit_preview,
 8181                snapshot,
 8182                display_mode: _,
 8183            } => {
 8184                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8185
 8186                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8187                    &snapshot,
 8188                    &edits,
 8189                    edit_preview.as_ref()?,
 8190                    true,
 8191                    cx,
 8192                )
 8193                .first_line_preview();
 8194
 8195                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8196                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8197
 8198                let preview = h_flex()
 8199                    .gap_1()
 8200                    .min_w_16()
 8201                    .child(styled_text)
 8202                    .when(has_more_lines, |parent| parent.child(""));
 8203
 8204                let left = if first_edit_row != cursor_point.row {
 8205                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8206                        .into_any_element()
 8207                } else {
 8208                    Icon::new(IconName::ZedPredict).into_any_element()
 8209                };
 8210
 8211                Some(
 8212                    h_flex()
 8213                        .h_full()
 8214                        .flex_1()
 8215                        .gap_2()
 8216                        .pr_1()
 8217                        .overflow_x_hidden()
 8218                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8219                        .child(left)
 8220                        .child(preview),
 8221                )
 8222            }
 8223        }
 8224    }
 8225
 8226    fn render_context_menu(
 8227        &self,
 8228        style: &EditorStyle,
 8229        max_height_in_lines: u32,
 8230        window: &mut Window,
 8231        cx: &mut Context<Editor>,
 8232    ) -> Option<AnyElement> {
 8233        let menu = self.context_menu.borrow();
 8234        let menu = menu.as_ref()?;
 8235        if !menu.visible() {
 8236            return None;
 8237        };
 8238        Some(menu.render(style, max_height_in_lines, window, cx))
 8239    }
 8240
 8241    fn render_context_menu_aside(
 8242        &mut self,
 8243        max_size: Size<Pixels>,
 8244        window: &mut Window,
 8245        cx: &mut Context<Editor>,
 8246    ) -> Option<AnyElement> {
 8247        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8248            if menu.visible() {
 8249                menu.render_aside(self, max_size, window, cx)
 8250            } else {
 8251                None
 8252            }
 8253        })
 8254    }
 8255
 8256    fn hide_context_menu(
 8257        &mut self,
 8258        window: &mut Window,
 8259        cx: &mut Context<Self>,
 8260    ) -> Option<CodeContextMenu> {
 8261        cx.notify();
 8262        self.completion_tasks.clear();
 8263        let context_menu = self.context_menu.borrow_mut().take();
 8264        self.stale_inline_completion_in_menu.take();
 8265        self.update_visible_inline_completion(window, cx);
 8266        context_menu
 8267    }
 8268
 8269    fn show_snippet_choices(
 8270        &mut self,
 8271        choices: &Vec<String>,
 8272        selection: Range<Anchor>,
 8273        cx: &mut Context<Self>,
 8274    ) {
 8275        if selection.start.buffer_id.is_none() {
 8276            return;
 8277        }
 8278        let buffer_id = selection.start.buffer_id.unwrap();
 8279        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8280        let id = post_inc(&mut self.next_completion_id);
 8281        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8282
 8283        if let Some(buffer) = buffer {
 8284            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8285                CompletionsMenu::new_snippet_choices(
 8286                    id,
 8287                    true,
 8288                    choices,
 8289                    selection,
 8290                    buffer,
 8291                    snippet_sort_order,
 8292                ),
 8293            ));
 8294        }
 8295    }
 8296
 8297    pub fn insert_snippet(
 8298        &mut self,
 8299        insertion_ranges: &[Range<usize>],
 8300        snippet: Snippet,
 8301        window: &mut Window,
 8302        cx: &mut Context<Self>,
 8303    ) -> Result<()> {
 8304        struct Tabstop<T> {
 8305            is_end_tabstop: bool,
 8306            ranges: Vec<Range<T>>,
 8307            choices: Option<Vec<String>>,
 8308        }
 8309
 8310        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8311            let snippet_text: Arc<str> = snippet.text.clone().into();
 8312            let edits = insertion_ranges
 8313                .iter()
 8314                .cloned()
 8315                .map(|range| (range, snippet_text.clone()));
 8316            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8317
 8318            let snapshot = &*buffer.read(cx);
 8319            let snippet = &snippet;
 8320            snippet
 8321                .tabstops
 8322                .iter()
 8323                .map(|tabstop| {
 8324                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8325                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8326                    });
 8327                    let mut tabstop_ranges = tabstop
 8328                        .ranges
 8329                        .iter()
 8330                        .flat_map(|tabstop_range| {
 8331                            let mut delta = 0_isize;
 8332                            insertion_ranges.iter().map(move |insertion_range| {
 8333                                let insertion_start = insertion_range.start as isize + delta;
 8334                                delta +=
 8335                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8336
 8337                                let start = ((insertion_start + tabstop_range.start) as usize)
 8338                                    .min(snapshot.len());
 8339                                let end = ((insertion_start + tabstop_range.end) as usize)
 8340                                    .min(snapshot.len());
 8341                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8342                            })
 8343                        })
 8344                        .collect::<Vec<_>>();
 8345                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8346
 8347                    Tabstop {
 8348                        is_end_tabstop,
 8349                        ranges: tabstop_ranges,
 8350                        choices: tabstop.choices.clone(),
 8351                    }
 8352                })
 8353                .collect::<Vec<_>>()
 8354        });
 8355        if let Some(tabstop) = tabstops.first() {
 8356            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8357                s.select_ranges(tabstop.ranges.iter().cloned());
 8358            });
 8359
 8360            if let Some(choices) = &tabstop.choices {
 8361                if let Some(selection) = tabstop.ranges.first() {
 8362                    self.show_snippet_choices(choices, selection.clone(), cx)
 8363                }
 8364            }
 8365
 8366            // If we're already at the last tabstop and it's at the end of the snippet,
 8367            // we're done, we don't need to keep the state around.
 8368            if !tabstop.is_end_tabstop {
 8369                let choices = tabstops
 8370                    .iter()
 8371                    .map(|tabstop| tabstop.choices.clone())
 8372                    .collect();
 8373
 8374                let ranges = tabstops
 8375                    .into_iter()
 8376                    .map(|tabstop| tabstop.ranges)
 8377                    .collect::<Vec<_>>();
 8378
 8379                self.snippet_stack.push(SnippetState {
 8380                    active_index: 0,
 8381                    ranges,
 8382                    choices,
 8383                });
 8384            }
 8385
 8386            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8387            if self.autoclose_regions.is_empty() {
 8388                let snapshot = self.buffer.read(cx).snapshot(cx);
 8389                for selection in &mut self.selections.all::<Point>(cx) {
 8390                    let selection_head = selection.head();
 8391                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8392                        continue;
 8393                    };
 8394
 8395                    let mut bracket_pair = None;
 8396                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8397                    let prev_chars = snapshot
 8398                        .reversed_chars_at(selection_head)
 8399                        .collect::<String>();
 8400                    for (pair, enabled) in scope.brackets() {
 8401                        if enabled
 8402                            && pair.close
 8403                            && prev_chars.starts_with(pair.start.as_str())
 8404                            && next_chars.starts_with(pair.end.as_str())
 8405                        {
 8406                            bracket_pair = Some(pair.clone());
 8407                            break;
 8408                        }
 8409                    }
 8410                    if let Some(pair) = bracket_pair {
 8411                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8412                        let autoclose_enabled =
 8413                            self.use_autoclose && snapshot_settings.use_autoclose;
 8414                        if autoclose_enabled {
 8415                            let start = snapshot.anchor_after(selection_head);
 8416                            let end = snapshot.anchor_after(selection_head);
 8417                            self.autoclose_regions.push(AutocloseRegion {
 8418                                selection_id: selection.id,
 8419                                range: start..end,
 8420                                pair,
 8421                            });
 8422                        }
 8423                    }
 8424                }
 8425            }
 8426        }
 8427        Ok(())
 8428    }
 8429
 8430    pub fn move_to_next_snippet_tabstop(
 8431        &mut self,
 8432        window: &mut Window,
 8433        cx: &mut Context<Self>,
 8434    ) -> bool {
 8435        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8436    }
 8437
 8438    pub fn move_to_prev_snippet_tabstop(
 8439        &mut self,
 8440        window: &mut Window,
 8441        cx: &mut Context<Self>,
 8442    ) -> bool {
 8443        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8444    }
 8445
 8446    pub fn move_to_snippet_tabstop(
 8447        &mut self,
 8448        bias: Bias,
 8449        window: &mut Window,
 8450        cx: &mut Context<Self>,
 8451    ) -> bool {
 8452        if let Some(mut snippet) = self.snippet_stack.pop() {
 8453            match bias {
 8454                Bias::Left => {
 8455                    if snippet.active_index > 0 {
 8456                        snippet.active_index -= 1;
 8457                    } else {
 8458                        self.snippet_stack.push(snippet);
 8459                        return false;
 8460                    }
 8461                }
 8462                Bias::Right => {
 8463                    if snippet.active_index + 1 < snippet.ranges.len() {
 8464                        snippet.active_index += 1;
 8465                    } else {
 8466                        self.snippet_stack.push(snippet);
 8467                        return false;
 8468                    }
 8469                }
 8470            }
 8471            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8472                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8473                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8474                });
 8475
 8476                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8477                    if let Some(selection) = current_ranges.first() {
 8478                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8479                    }
 8480                }
 8481
 8482                // If snippet state is not at the last tabstop, push it back on the stack
 8483                if snippet.active_index + 1 < snippet.ranges.len() {
 8484                    self.snippet_stack.push(snippet);
 8485                }
 8486                return true;
 8487            }
 8488        }
 8489
 8490        false
 8491    }
 8492
 8493    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8494        self.transact(window, cx, |this, window, cx| {
 8495            this.select_all(&SelectAll, window, cx);
 8496            this.insert("", window, cx);
 8497        });
 8498    }
 8499
 8500    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8501        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8502        self.transact(window, cx, |this, window, cx| {
 8503            this.select_autoclose_pair(window, cx);
 8504            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8505            if !this.linked_edit_ranges.is_empty() {
 8506                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8507                let snapshot = this.buffer.read(cx).snapshot(cx);
 8508
 8509                for selection in selections.iter() {
 8510                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8511                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8512                    if selection_start.buffer_id != selection_end.buffer_id {
 8513                        continue;
 8514                    }
 8515                    if let Some(ranges) =
 8516                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8517                    {
 8518                        for (buffer, entries) in ranges {
 8519                            linked_ranges.entry(buffer).or_default().extend(entries);
 8520                        }
 8521                    }
 8522                }
 8523            }
 8524
 8525            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8526            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8527            for selection in &mut selections {
 8528                if selection.is_empty() {
 8529                    let old_head = selection.head();
 8530                    let mut new_head =
 8531                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8532                            .to_point(&display_map);
 8533                    if let Some((buffer, line_buffer_range)) = display_map
 8534                        .buffer_snapshot
 8535                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8536                    {
 8537                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8538                        let indent_len = match indent_size.kind {
 8539                            IndentKind::Space => {
 8540                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8541                            }
 8542                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8543                        };
 8544                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8545                            let indent_len = indent_len.get();
 8546                            new_head = cmp::min(
 8547                                new_head,
 8548                                MultiBufferPoint::new(
 8549                                    old_head.row,
 8550                                    ((old_head.column - 1) / indent_len) * indent_len,
 8551                                ),
 8552                            );
 8553                        }
 8554                    }
 8555
 8556                    selection.set_head(new_head, SelectionGoal::None);
 8557                }
 8558            }
 8559
 8560            this.signature_help_state.set_backspace_pressed(true);
 8561            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8562                s.select(selections)
 8563            });
 8564            this.insert("", window, cx);
 8565            let empty_str: Arc<str> = Arc::from("");
 8566            for (buffer, edits) in linked_ranges {
 8567                let snapshot = buffer.read(cx).snapshot();
 8568                use text::ToPoint as TP;
 8569
 8570                let edits = edits
 8571                    .into_iter()
 8572                    .map(|range| {
 8573                        let end_point = TP::to_point(&range.end, &snapshot);
 8574                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8575
 8576                        if end_point == start_point {
 8577                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8578                                .saturating_sub(1);
 8579                            start_point =
 8580                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8581                        };
 8582
 8583                        (start_point..end_point, empty_str.clone())
 8584                    })
 8585                    .sorted_by_key(|(range, _)| range.start)
 8586                    .collect::<Vec<_>>();
 8587                buffer.update(cx, |this, cx| {
 8588                    this.edit(edits, None, cx);
 8589                })
 8590            }
 8591            this.refresh_inline_completion(true, false, window, cx);
 8592            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8593        });
 8594    }
 8595
 8596    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8597        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8598        self.transact(window, cx, |this, window, cx| {
 8599            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8600                s.move_with(|map, selection| {
 8601                    if selection.is_empty() {
 8602                        let cursor = movement::right(map, selection.head());
 8603                        selection.end = cursor;
 8604                        selection.reversed = true;
 8605                        selection.goal = SelectionGoal::None;
 8606                    }
 8607                })
 8608            });
 8609            this.insert("", window, cx);
 8610            this.refresh_inline_completion(true, false, window, cx);
 8611        });
 8612    }
 8613
 8614    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8615        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8616        if self.move_to_prev_snippet_tabstop(window, cx) {
 8617            return;
 8618        }
 8619        self.outdent(&Outdent, window, cx);
 8620    }
 8621
 8622    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8623        if self.move_to_next_snippet_tabstop(window, cx) {
 8624            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8625            return;
 8626        }
 8627        if self.read_only(cx) {
 8628            return;
 8629        }
 8630        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8631        let mut selections = self.selections.all_adjusted(cx);
 8632        let buffer = self.buffer.read(cx);
 8633        let snapshot = buffer.snapshot(cx);
 8634        let rows_iter = selections.iter().map(|s| s.head().row);
 8635        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8636
 8637        let has_some_cursor_in_whitespace = selections
 8638            .iter()
 8639            .filter(|selection| selection.is_empty())
 8640            .any(|selection| {
 8641                let cursor = selection.head();
 8642                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8643                cursor.column < current_indent.len
 8644            });
 8645
 8646        let mut edits = Vec::new();
 8647        let mut prev_edited_row = 0;
 8648        let mut row_delta = 0;
 8649        for selection in &mut selections {
 8650            if selection.start.row != prev_edited_row {
 8651                row_delta = 0;
 8652            }
 8653            prev_edited_row = selection.end.row;
 8654
 8655            // If the selection is non-empty, then increase the indentation of the selected lines.
 8656            if !selection.is_empty() {
 8657                row_delta =
 8658                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8659                continue;
 8660            }
 8661
 8662            // If the selection is empty and the cursor is in the leading whitespace before the
 8663            // suggested indentation, then auto-indent the line.
 8664            let cursor = selection.head();
 8665            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8666            if let Some(suggested_indent) =
 8667                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8668            {
 8669                // If there exist any empty selection in the leading whitespace, then skip
 8670                // indent for selections at the boundary.
 8671                if has_some_cursor_in_whitespace
 8672                    && cursor.column == current_indent.len
 8673                    && current_indent.len == suggested_indent.len
 8674                {
 8675                    continue;
 8676                }
 8677
 8678                if cursor.column < suggested_indent.len
 8679                    && cursor.column <= current_indent.len
 8680                    && current_indent.len <= suggested_indent.len
 8681                {
 8682                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8683                    selection.end = selection.start;
 8684                    if row_delta == 0 {
 8685                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8686                            cursor.row,
 8687                            current_indent,
 8688                            suggested_indent,
 8689                        ));
 8690                        row_delta = suggested_indent.len - current_indent.len;
 8691                    }
 8692                    continue;
 8693                }
 8694            }
 8695
 8696            // Otherwise, insert a hard or soft tab.
 8697            let settings = buffer.language_settings_at(cursor, cx);
 8698            let tab_size = if settings.hard_tabs {
 8699                IndentSize::tab()
 8700            } else {
 8701                let tab_size = settings.tab_size.get();
 8702                let indent_remainder = snapshot
 8703                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8704                    .flat_map(str::chars)
 8705                    .fold(row_delta % tab_size, |counter: u32, c| {
 8706                        if c == '\t' {
 8707                            0
 8708                        } else {
 8709                            (counter + 1) % tab_size
 8710                        }
 8711                    });
 8712
 8713                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8714                IndentSize::spaces(chars_to_next_tab_stop)
 8715            };
 8716            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8717            selection.end = selection.start;
 8718            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8719            row_delta += tab_size.len;
 8720        }
 8721
 8722        self.transact(window, cx, |this, window, cx| {
 8723            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8724            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8725                s.select(selections)
 8726            });
 8727            this.refresh_inline_completion(true, false, window, cx);
 8728        });
 8729    }
 8730
 8731    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8732        if self.read_only(cx) {
 8733            return;
 8734        }
 8735        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8736        let mut selections = self.selections.all::<Point>(cx);
 8737        let mut prev_edited_row = 0;
 8738        let mut row_delta = 0;
 8739        let mut edits = Vec::new();
 8740        let buffer = self.buffer.read(cx);
 8741        let snapshot = buffer.snapshot(cx);
 8742        for selection in &mut selections {
 8743            if selection.start.row != prev_edited_row {
 8744                row_delta = 0;
 8745            }
 8746            prev_edited_row = selection.end.row;
 8747
 8748            row_delta =
 8749                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8750        }
 8751
 8752        self.transact(window, cx, |this, window, cx| {
 8753            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8754            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8755                s.select(selections)
 8756            });
 8757        });
 8758    }
 8759
 8760    fn indent_selection(
 8761        buffer: &MultiBuffer,
 8762        snapshot: &MultiBufferSnapshot,
 8763        selection: &mut Selection<Point>,
 8764        edits: &mut Vec<(Range<Point>, String)>,
 8765        delta_for_start_row: u32,
 8766        cx: &App,
 8767    ) -> u32 {
 8768        let settings = buffer.language_settings_at(selection.start, cx);
 8769        let tab_size = settings.tab_size.get();
 8770        let indent_kind = if settings.hard_tabs {
 8771            IndentKind::Tab
 8772        } else {
 8773            IndentKind::Space
 8774        };
 8775        let mut start_row = selection.start.row;
 8776        let mut end_row = selection.end.row + 1;
 8777
 8778        // If a selection ends at the beginning of a line, don't indent
 8779        // that last line.
 8780        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8781            end_row -= 1;
 8782        }
 8783
 8784        // Avoid re-indenting a row that has already been indented by a
 8785        // previous selection, but still update this selection's column
 8786        // to reflect that indentation.
 8787        if delta_for_start_row > 0 {
 8788            start_row += 1;
 8789            selection.start.column += delta_for_start_row;
 8790            if selection.end.row == selection.start.row {
 8791                selection.end.column += delta_for_start_row;
 8792            }
 8793        }
 8794
 8795        let mut delta_for_end_row = 0;
 8796        let has_multiple_rows = start_row + 1 != end_row;
 8797        for row in start_row..end_row {
 8798            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8799            let indent_delta = match (current_indent.kind, indent_kind) {
 8800                (IndentKind::Space, IndentKind::Space) => {
 8801                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8802                    IndentSize::spaces(columns_to_next_tab_stop)
 8803                }
 8804                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8805                (_, IndentKind::Tab) => IndentSize::tab(),
 8806            };
 8807
 8808            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8809                0
 8810            } else {
 8811                selection.start.column
 8812            };
 8813            let row_start = Point::new(row, start);
 8814            edits.push((
 8815                row_start..row_start,
 8816                indent_delta.chars().collect::<String>(),
 8817            ));
 8818
 8819            // Update this selection's endpoints to reflect the indentation.
 8820            if row == selection.start.row {
 8821                selection.start.column += indent_delta.len;
 8822            }
 8823            if row == selection.end.row {
 8824                selection.end.column += indent_delta.len;
 8825                delta_for_end_row = indent_delta.len;
 8826            }
 8827        }
 8828
 8829        if selection.start.row == selection.end.row {
 8830            delta_for_start_row + delta_for_end_row
 8831        } else {
 8832            delta_for_end_row
 8833        }
 8834    }
 8835
 8836    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8837        if self.read_only(cx) {
 8838            return;
 8839        }
 8840        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8841        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8842        let selections = self.selections.all::<Point>(cx);
 8843        let mut deletion_ranges = Vec::new();
 8844        let mut last_outdent = None;
 8845        {
 8846            let buffer = self.buffer.read(cx);
 8847            let snapshot = buffer.snapshot(cx);
 8848            for selection in &selections {
 8849                let settings = buffer.language_settings_at(selection.start, cx);
 8850                let tab_size = settings.tab_size.get();
 8851                let mut rows = selection.spanned_rows(false, &display_map);
 8852
 8853                // Avoid re-outdenting a row that has already been outdented by a
 8854                // previous selection.
 8855                if let Some(last_row) = last_outdent {
 8856                    if last_row == rows.start {
 8857                        rows.start = rows.start.next_row();
 8858                    }
 8859                }
 8860                let has_multiple_rows = rows.len() > 1;
 8861                for row in rows.iter_rows() {
 8862                    let indent_size = snapshot.indent_size_for_line(row);
 8863                    if indent_size.len > 0 {
 8864                        let deletion_len = match indent_size.kind {
 8865                            IndentKind::Space => {
 8866                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8867                                if columns_to_prev_tab_stop == 0 {
 8868                                    tab_size
 8869                                } else {
 8870                                    columns_to_prev_tab_stop
 8871                                }
 8872                            }
 8873                            IndentKind::Tab => 1,
 8874                        };
 8875                        let start = if has_multiple_rows
 8876                            || deletion_len > selection.start.column
 8877                            || indent_size.len < selection.start.column
 8878                        {
 8879                            0
 8880                        } else {
 8881                            selection.start.column - deletion_len
 8882                        };
 8883                        deletion_ranges.push(
 8884                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8885                        );
 8886                        last_outdent = Some(row);
 8887                    }
 8888                }
 8889            }
 8890        }
 8891
 8892        self.transact(window, cx, |this, window, cx| {
 8893            this.buffer.update(cx, |buffer, cx| {
 8894                let empty_str: Arc<str> = Arc::default();
 8895                buffer.edit(
 8896                    deletion_ranges
 8897                        .into_iter()
 8898                        .map(|range| (range, empty_str.clone())),
 8899                    None,
 8900                    cx,
 8901                );
 8902            });
 8903            let selections = this.selections.all::<usize>(cx);
 8904            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8905                s.select(selections)
 8906            });
 8907        });
 8908    }
 8909
 8910    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8911        if self.read_only(cx) {
 8912            return;
 8913        }
 8914        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8915        let selections = self
 8916            .selections
 8917            .all::<usize>(cx)
 8918            .into_iter()
 8919            .map(|s| s.range());
 8920
 8921        self.transact(window, cx, |this, window, cx| {
 8922            this.buffer.update(cx, |buffer, cx| {
 8923                buffer.autoindent_ranges(selections, cx);
 8924            });
 8925            let selections = this.selections.all::<usize>(cx);
 8926            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8927                s.select(selections)
 8928            });
 8929        });
 8930    }
 8931
 8932    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8933        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8934        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8935        let selections = self.selections.all::<Point>(cx);
 8936
 8937        let mut new_cursors = Vec::new();
 8938        let mut edit_ranges = Vec::new();
 8939        let mut selections = selections.iter().peekable();
 8940        while let Some(selection) = selections.next() {
 8941            let mut rows = selection.spanned_rows(false, &display_map);
 8942            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8943
 8944            // Accumulate contiguous regions of rows that we want to delete.
 8945            while let Some(next_selection) = selections.peek() {
 8946                let next_rows = next_selection.spanned_rows(false, &display_map);
 8947                if next_rows.start <= rows.end {
 8948                    rows.end = next_rows.end;
 8949                    selections.next().unwrap();
 8950                } else {
 8951                    break;
 8952                }
 8953            }
 8954
 8955            let buffer = &display_map.buffer_snapshot;
 8956            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8957            let edit_end;
 8958            let cursor_buffer_row;
 8959            if buffer.max_point().row >= rows.end.0 {
 8960                // If there's a line after the range, delete the \n from the end of the row range
 8961                // and position the cursor on the next line.
 8962                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8963                cursor_buffer_row = rows.end;
 8964            } else {
 8965                // If there isn't a line after the range, delete the \n from the line before the
 8966                // start of the row range and position the cursor there.
 8967                edit_start = edit_start.saturating_sub(1);
 8968                edit_end = buffer.len();
 8969                cursor_buffer_row = rows.start.previous_row();
 8970            }
 8971
 8972            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8973            *cursor.column_mut() =
 8974                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8975
 8976            new_cursors.push((
 8977                selection.id,
 8978                buffer.anchor_after(cursor.to_point(&display_map)),
 8979            ));
 8980            edit_ranges.push(edit_start..edit_end);
 8981        }
 8982
 8983        self.transact(window, cx, |this, window, cx| {
 8984            let buffer = this.buffer.update(cx, |buffer, cx| {
 8985                let empty_str: Arc<str> = Arc::default();
 8986                buffer.edit(
 8987                    edit_ranges
 8988                        .into_iter()
 8989                        .map(|range| (range, empty_str.clone())),
 8990                    None,
 8991                    cx,
 8992                );
 8993                buffer.snapshot(cx)
 8994            });
 8995            let new_selections = new_cursors
 8996                .into_iter()
 8997                .map(|(id, cursor)| {
 8998                    let cursor = cursor.to_point(&buffer);
 8999                    Selection {
 9000                        id,
 9001                        start: cursor,
 9002                        end: cursor,
 9003                        reversed: false,
 9004                        goal: SelectionGoal::None,
 9005                    }
 9006                })
 9007                .collect();
 9008
 9009            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9010                s.select(new_selections);
 9011            });
 9012        });
 9013    }
 9014
 9015    pub fn join_lines_impl(
 9016        &mut self,
 9017        insert_whitespace: bool,
 9018        window: &mut Window,
 9019        cx: &mut Context<Self>,
 9020    ) {
 9021        if self.read_only(cx) {
 9022            return;
 9023        }
 9024        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9025        for selection in self.selections.all::<Point>(cx) {
 9026            let start = MultiBufferRow(selection.start.row);
 9027            // Treat single line selections as if they include the next line. Otherwise this action
 9028            // would do nothing for single line selections individual cursors.
 9029            let end = if selection.start.row == selection.end.row {
 9030                MultiBufferRow(selection.start.row + 1)
 9031            } else {
 9032                MultiBufferRow(selection.end.row)
 9033            };
 9034
 9035            if let Some(last_row_range) = row_ranges.last_mut() {
 9036                if start <= last_row_range.end {
 9037                    last_row_range.end = end;
 9038                    continue;
 9039                }
 9040            }
 9041            row_ranges.push(start..end);
 9042        }
 9043
 9044        let snapshot = self.buffer.read(cx).snapshot(cx);
 9045        let mut cursor_positions = Vec::new();
 9046        for row_range in &row_ranges {
 9047            let anchor = snapshot.anchor_before(Point::new(
 9048                row_range.end.previous_row().0,
 9049                snapshot.line_len(row_range.end.previous_row()),
 9050            ));
 9051            cursor_positions.push(anchor..anchor);
 9052        }
 9053
 9054        self.transact(window, cx, |this, window, cx| {
 9055            for row_range in row_ranges.into_iter().rev() {
 9056                for row in row_range.iter_rows().rev() {
 9057                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9058                    let next_line_row = row.next_row();
 9059                    let indent = snapshot.indent_size_for_line(next_line_row);
 9060                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9061
 9062                    let replace =
 9063                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9064                            " "
 9065                        } else {
 9066                            ""
 9067                        };
 9068
 9069                    this.buffer.update(cx, |buffer, cx| {
 9070                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9071                    });
 9072                }
 9073            }
 9074
 9075            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9076                s.select_anchor_ranges(cursor_positions)
 9077            });
 9078        });
 9079    }
 9080
 9081    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9082        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9083        self.join_lines_impl(true, window, cx);
 9084    }
 9085
 9086    pub fn sort_lines_case_sensitive(
 9087        &mut self,
 9088        _: &SortLinesCaseSensitive,
 9089        window: &mut Window,
 9090        cx: &mut Context<Self>,
 9091    ) {
 9092        self.manipulate_lines(window, cx, |lines| lines.sort())
 9093    }
 9094
 9095    pub fn sort_lines_case_insensitive(
 9096        &mut self,
 9097        _: &SortLinesCaseInsensitive,
 9098        window: &mut Window,
 9099        cx: &mut Context<Self>,
 9100    ) {
 9101        self.manipulate_lines(window, cx, |lines| {
 9102            lines.sort_by_key(|line| line.to_lowercase())
 9103        })
 9104    }
 9105
 9106    pub fn unique_lines_case_insensitive(
 9107        &mut self,
 9108        _: &UniqueLinesCaseInsensitive,
 9109        window: &mut Window,
 9110        cx: &mut Context<Self>,
 9111    ) {
 9112        self.manipulate_lines(window, cx, |lines| {
 9113            let mut seen = HashSet::default();
 9114            lines.retain(|line| seen.insert(line.to_lowercase()));
 9115        })
 9116    }
 9117
 9118    pub fn unique_lines_case_sensitive(
 9119        &mut self,
 9120        _: &UniqueLinesCaseSensitive,
 9121        window: &mut Window,
 9122        cx: &mut Context<Self>,
 9123    ) {
 9124        self.manipulate_lines(window, cx, |lines| {
 9125            let mut seen = HashSet::default();
 9126            lines.retain(|line| seen.insert(*line));
 9127        })
 9128    }
 9129
 9130    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9131        let Some(project) = self.project.clone() else {
 9132            return;
 9133        };
 9134        self.reload(project, window, cx)
 9135            .detach_and_notify_err(window, cx);
 9136    }
 9137
 9138    pub fn restore_file(
 9139        &mut self,
 9140        _: &::git::RestoreFile,
 9141        window: &mut Window,
 9142        cx: &mut Context<Self>,
 9143    ) {
 9144        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9145        let mut buffer_ids = HashSet::default();
 9146        let snapshot = self.buffer().read(cx).snapshot(cx);
 9147        for selection in self.selections.all::<usize>(cx) {
 9148            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9149        }
 9150
 9151        let buffer = self.buffer().read(cx);
 9152        let ranges = buffer_ids
 9153            .into_iter()
 9154            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9155            .collect::<Vec<_>>();
 9156
 9157        self.restore_hunks_in_ranges(ranges, window, cx);
 9158    }
 9159
 9160    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9161        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9162        let selections = self
 9163            .selections
 9164            .all(cx)
 9165            .into_iter()
 9166            .map(|s| s.range())
 9167            .collect();
 9168        self.restore_hunks_in_ranges(selections, window, cx);
 9169    }
 9170
 9171    pub fn restore_hunks_in_ranges(
 9172        &mut self,
 9173        ranges: Vec<Range<Point>>,
 9174        window: &mut Window,
 9175        cx: &mut Context<Editor>,
 9176    ) {
 9177        let mut revert_changes = HashMap::default();
 9178        let chunk_by = self
 9179            .snapshot(window, cx)
 9180            .hunks_for_ranges(ranges)
 9181            .into_iter()
 9182            .chunk_by(|hunk| hunk.buffer_id);
 9183        for (buffer_id, hunks) in &chunk_by {
 9184            let hunks = hunks.collect::<Vec<_>>();
 9185            for hunk in &hunks {
 9186                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9187            }
 9188            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9189        }
 9190        drop(chunk_by);
 9191        if !revert_changes.is_empty() {
 9192            self.transact(window, cx, |editor, window, cx| {
 9193                editor.restore(revert_changes, window, cx);
 9194            });
 9195        }
 9196    }
 9197
 9198    pub fn open_active_item_in_terminal(
 9199        &mut self,
 9200        _: &OpenInTerminal,
 9201        window: &mut Window,
 9202        cx: &mut Context<Self>,
 9203    ) {
 9204        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9205            let project_path = buffer.read(cx).project_path(cx)?;
 9206            let project = self.project.as_ref()?.read(cx);
 9207            let entry = project.entry_for_path(&project_path, cx)?;
 9208            let parent = match &entry.canonical_path {
 9209                Some(canonical_path) => canonical_path.to_path_buf(),
 9210                None => project.absolute_path(&project_path, cx)?,
 9211            }
 9212            .parent()?
 9213            .to_path_buf();
 9214            Some(parent)
 9215        }) {
 9216            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9217        }
 9218    }
 9219
 9220    fn set_breakpoint_context_menu(
 9221        &mut self,
 9222        display_row: DisplayRow,
 9223        position: Option<Anchor>,
 9224        clicked_point: gpui::Point<Pixels>,
 9225        window: &mut Window,
 9226        cx: &mut Context<Self>,
 9227    ) {
 9228        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9229            return;
 9230        }
 9231        let source = self
 9232            .buffer
 9233            .read(cx)
 9234            .snapshot(cx)
 9235            .anchor_before(Point::new(display_row.0, 0u32));
 9236
 9237        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9238
 9239        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9240            self,
 9241            source,
 9242            clicked_point,
 9243            context_menu,
 9244            window,
 9245            cx,
 9246        );
 9247    }
 9248
 9249    fn add_edit_breakpoint_block(
 9250        &mut self,
 9251        anchor: Anchor,
 9252        breakpoint: &Breakpoint,
 9253        edit_action: BreakpointPromptEditAction,
 9254        window: &mut Window,
 9255        cx: &mut Context<Self>,
 9256    ) {
 9257        let weak_editor = cx.weak_entity();
 9258        let bp_prompt = cx.new(|cx| {
 9259            BreakpointPromptEditor::new(
 9260                weak_editor,
 9261                anchor,
 9262                breakpoint.clone(),
 9263                edit_action,
 9264                window,
 9265                cx,
 9266            )
 9267        });
 9268
 9269        let height = bp_prompt.update(cx, |this, cx| {
 9270            this.prompt
 9271                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9272        });
 9273        let cloned_prompt = bp_prompt.clone();
 9274        let blocks = vec![BlockProperties {
 9275            style: BlockStyle::Sticky,
 9276            placement: BlockPlacement::Above(anchor),
 9277            height: Some(height),
 9278            render: Arc::new(move |cx| {
 9279                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9280                cloned_prompt.clone().into_any_element()
 9281            }),
 9282            priority: 0,
 9283        }];
 9284
 9285        let focus_handle = bp_prompt.focus_handle(cx);
 9286        window.focus(&focus_handle);
 9287
 9288        let block_ids = self.insert_blocks(blocks, None, cx);
 9289        bp_prompt.update(cx, |prompt, _| {
 9290            prompt.add_block_ids(block_ids);
 9291        });
 9292    }
 9293
 9294    pub(crate) fn breakpoint_at_row(
 9295        &self,
 9296        row: u32,
 9297        window: &mut Window,
 9298        cx: &mut Context<Self>,
 9299    ) -> Option<(Anchor, Breakpoint)> {
 9300        let snapshot = self.snapshot(window, cx);
 9301        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9302
 9303        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9304    }
 9305
 9306    pub(crate) fn breakpoint_at_anchor(
 9307        &self,
 9308        breakpoint_position: Anchor,
 9309        snapshot: &EditorSnapshot,
 9310        cx: &mut Context<Self>,
 9311    ) -> Option<(Anchor, Breakpoint)> {
 9312        let project = self.project.clone()?;
 9313
 9314        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9315            snapshot
 9316                .buffer_snapshot
 9317                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9318        })?;
 9319
 9320        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9321        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9322        let buffer_snapshot = buffer.read(cx).snapshot();
 9323
 9324        let row = buffer_snapshot
 9325            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9326            .row;
 9327
 9328        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9329        let anchor_end = snapshot
 9330            .buffer_snapshot
 9331            .anchor_after(Point::new(row, line_len));
 9332
 9333        let bp = self
 9334            .breakpoint_store
 9335            .as_ref()?
 9336            .read_with(cx, |breakpoint_store, cx| {
 9337                breakpoint_store
 9338                    .breakpoints(
 9339                        &buffer,
 9340                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9341                        &buffer_snapshot,
 9342                        cx,
 9343                    )
 9344                    .next()
 9345                    .and_then(|(anchor, bp)| {
 9346                        let breakpoint_row = buffer_snapshot
 9347                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9348                            .row;
 9349
 9350                        if breakpoint_row == row {
 9351                            snapshot
 9352                                .buffer_snapshot
 9353                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9354                                .map(|anchor| (anchor, bp.clone()))
 9355                        } else {
 9356                            None
 9357                        }
 9358                    })
 9359            });
 9360        bp
 9361    }
 9362
 9363    pub fn edit_log_breakpoint(
 9364        &mut self,
 9365        _: &EditLogBreakpoint,
 9366        window: &mut Window,
 9367        cx: &mut Context<Self>,
 9368    ) {
 9369        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9370            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9371                message: None,
 9372                state: BreakpointState::Enabled,
 9373                condition: None,
 9374                hit_condition: None,
 9375            });
 9376
 9377            self.add_edit_breakpoint_block(
 9378                anchor,
 9379                &breakpoint,
 9380                BreakpointPromptEditAction::Log,
 9381                window,
 9382                cx,
 9383            );
 9384        }
 9385    }
 9386
 9387    fn breakpoints_at_cursors(
 9388        &self,
 9389        window: &mut Window,
 9390        cx: &mut Context<Self>,
 9391    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9392        let snapshot = self.snapshot(window, cx);
 9393        let cursors = self
 9394            .selections
 9395            .disjoint_anchors()
 9396            .into_iter()
 9397            .map(|selection| {
 9398                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9399
 9400                let breakpoint_position = self
 9401                    .breakpoint_at_row(cursor_position.row, window, cx)
 9402                    .map(|bp| bp.0)
 9403                    .unwrap_or_else(|| {
 9404                        snapshot
 9405                            .display_snapshot
 9406                            .buffer_snapshot
 9407                            .anchor_after(Point::new(cursor_position.row, 0))
 9408                    });
 9409
 9410                let breakpoint = self
 9411                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9412                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9413
 9414                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9415            })
 9416            // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
 9417            .collect::<HashMap<Anchor, _>>();
 9418
 9419        cursors.into_iter().collect()
 9420    }
 9421
 9422    pub fn enable_breakpoint(
 9423        &mut self,
 9424        _: &crate::actions::EnableBreakpoint,
 9425        window: &mut Window,
 9426        cx: &mut Context<Self>,
 9427    ) {
 9428        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9429            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9430                continue;
 9431            };
 9432            self.edit_breakpoint_at_anchor(
 9433                anchor,
 9434                breakpoint,
 9435                BreakpointEditAction::InvertState,
 9436                cx,
 9437            );
 9438        }
 9439    }
 9440
 9441    pub fn disable_breakpoint(
 9442        &mut self,
 9443        _: &crate::actions::DisableBreakpoint,
 9444        window: &mut Window,
 9445        cx: &mut Context<Self>,
 9446    ) {
 9447        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9448            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9449                continue;
 9450            };
 9451            self.edit_breakpoint_at_anchor(
 9452                anchor,
 9453                breakpoint,
 9454                BreakpointEditAction::InvertState,
 9455                cx,
 9456            );
 9457        }
 9458    }
 9459
 9460    pub fn toggle_breakpoint(
 9461        &mut self,
 9462        _: &crate::actions::ToggleBreakpoint,
 9463        window: &mut Window,
 9464        cx: &mut Context<Self>,
 9465    ) {
 9466        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9467            if let Some(breakpoint) = breakpoint {
 9468                self.edit_breakpoint_at_anchor(
 9469                    anchor,
 9470                    breakpoint,
 9471                    BreakpointEditAction::Toggle,
 9472                    cx,
 9473                );
 9474            } else {
 9475                self.edit_breakpoint_at_anchor(
 9476                    anchor,
 9477                    Breakpoint::new_standard(),
 9478                    BreakpointEditAction::Toggle,
 9479                    cx,
 9480                );
 9481            }
 9482        }
 9483    }
 9484
 9485    pub fn edit_breakpoint_at_anchor(
 9486        &mut self,
 9487        breakpoint_position: Anchor,
 9488        breakpoint: Breakpoint,
 9489        edit_action: BreakpointEditAction,
 9490        cx: &mut Context<Self>,
 9491    ) {
 9492        let Some(breakpoint_store) = &self.breakpoint_store else {
 9493            return;
 9494        };
 9495
 9496        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9497            if breakpoint_position == Anchor::min() {
 9498                self.buffer()
 9499                    .read(cx)
 9500                    .excerpt_buffer_ids()
 9501                    .into_iter()
 9502                    .next()
 9503            } else {
 9504                None
 9505            }
 9506        }) else {
 9507            return;
 9508        };
 9509
 9510        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9511            return;
 9512        };
 9513
 9514        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9515            breakpoint_store.toggle_breakpoint(
 9516                buffer,
 9517                (breakpoint_position.text_anchor, breakpoint),
 9518                edit_action,
 9519                cx,
 9520            );
 9521        });
 9522
 9523        cx.notify();
 9524    }
 9525
 9526    #[cfg(any(test, feature = "test-support"))]
 9527    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9528        self.breakpoint_store.clone()
 9529    }
 9530
 9531    pub fn prepare_restore_change(
 9532        &self,
 9533        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9534        hunk: &MultiBufferDiffHunk,
 9535        cx: &mut App,
 9536    ) -> Option<()> {
 9537        if hunk.is_created_file() {
 9538            return None;
 9539        }
 9540        let buffer = self.buffer.read(cx);
 9541        let diff = buffer.diff_for(hunk.buffer_id)?;
 9542        let buffer = buffer.buffer(hunk.buffer_id)?;
 9543        let buffer = buffer.read(cx);
 9544        let original_text = diff
 9545            .read(cx)
 9546            .base_text()
 9547            .as_rope()
 9548            .slice(hunk.diff_base_byte_range.clone());
 9549        let buffer_snapshot = buffer.snapshot();
 9550        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9551        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9552            probe
 9553                .0
 9554                .start
 9555                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9556                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9557        }) {
 9558            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9559            Some(())
 9560        } else {
 9561            None
 9562        }
 9563    }
 9564
 9565    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9566        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9567    }
 9568
 9569    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9570        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9571    }
 9572
 9573    fn manipulate_lines<Fn>(
 9574        &mut self,
 9575        window: &mut Window,
 9576        cx: &mut Context<Self>,
 9577        mut callback: Fn,
 9578    ) where
 9579        Fn: FnMut(&mut Vec<&str>),
 9580    {
 9581        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9582
 9583        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9584        let buffer = self.buffer.read(cx).snapshot(cx);
 9585
 9586        let mut edits = Vec::new();
 9587
 9588        let selections = self.selections.all::<Point>(cx);
 9589        let mut selections = selections.iter().peekable();
 9590        let mut contiguous_row_selections = Vec::new();
 9591        let mut new_selections = Vec::new();
 9592        let mut added_lines = 0;
 9593        let mut removed_lines = 0;
 9594
 9595        while let Some(selection) = selections.next() {
 9596            let (start_row, end_row) = consume_contiguous_rows(
 9597                &mut contiguous_row_selections,
 9598                selection,
 9599                &display_map,
 9600                &mut selections,
 9601            );
 9602
 9603            let start_point = Point::new(start_row.0, 0);
 9604            let end_point = Point::new(
 9605                end_row.previous_row().0,
 9606                buffer.line_len(end_row.previous_row()),
 9607            );
 9608            let text = buffer
 9609                .text_for_range(start_point..end_point)
 9610                .collect::<String>();
 9611
 9612            let mut lines = text.split('\n').collect_vec();
 9613
 9614            let lines_before = lines.len();
 9615            callback(&mut lines);
 9616            let lines_after = lines.len();
 9617
 9618            edits.push((start_point..end_point, lines.join("\n")));
 9619
 9620            // Selections must change based on added and removed line count
 9621            let start_row =
 9622                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9623            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9624            new_selections.push(Selection {
 9625                id: selection.id,
 9626                start: start_row,
 9627                end: end_row,
 9628                goal: SelectionGoal::None,
 9629                reversed: selection.reversed,
 9630            });
 9631
 9632            if lines_after > lines_before {
 9633                added_lines += lines_after - lines_before;
 9634            } else if lines_before > lines_after {
 9635                removed_lines += lines_before - lines_after;
 9636            }
 9637        }
 9638
 9639        self.transact(window, cx, |this, window, cx| {
 9640            let buffer = this.buffer.update(cx, |buffer, cx| {
 9641                buffer.edit(edits, None, cx);
 9642                buffer.snapshot(cx)
 9643            });
 9644
 9645            // Recalculate offsets on newly edited buffer
 9646            let new_selections = new_selections
 9647                .iter()
 9648                .map(|s| {
 9649                    let start_point = Point::new(s.start.0, 0);
 9650                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9651                    Selection {
 9652                        id: s.id,
 9653                        start: buffer.point_to_offset(start_point),
 9654                        end: buffer.point_to_offset(end_point),
 9655                        goal: s.goal,
 9656                        reversed: s.reversed,
 9657                    }
 9658                })
 9659                .collect();
 9660
 9661            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9662                s.select(new_selections);
 9663            });
 9664
 9665            this.request_autoscroll(Autoscroll::fit(), cx);
 9666        });
 9667    }
 9668
 9669    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9670        self.manipulate_text(window, cx, |text| {
 9671            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9672            if has_upper_case_characters {
 9673                text.to_lowercase()
 9674            } else {
 9675                text.to_uppercase()
 9676            }
 9677        })
 9678    }
 9679
 9680    pub fn convert_to_upper_case(
 9681        &mut self,
 9682        _: &ConvertToUpperCase,
 9683        window: &mut Window,
 9684        cx: &mut Context<Self>,
 9685    ) {
 9686        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9687    }
 9688
 9689    pub fn convert_to_lower_case(
 9690        &mut self,
 9691        _: &ConvertToLowerCase,
 9692        window: &mut Window,
 9693        cx: &mut Context<Self>,
 9694    ) {
 9695        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9696    }
 9697
 9698    pub fn convert_to_title_case(
 9699        &mut self,
 9700        _: &ConvertToTitleCase,
 9701        window: &mut Window,
 9702        cx: &mut Context<Self>,
 9703    ) {
 9704        self.manipulate_text(window, cx, |text| {
 9705            text.split('\n')
 9706                .map(|line| line.to_case(Case::Title))
 9707                .join("\n")
 9708        })
 9709    }
 9710
 9711    pub fn convert_to_snake_case(
 9712        &mut self,
 9713        _: &ConvertToSnakeCase,
 9714        window: &mut Window,
 9715        cx: &mut Context<Self>,
 9716    ) {
 9717        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9718    }
 9719
 9720    pub fn convert_to_kebab_case(
 9721        &mut self,
 9722        _: &ConvertToKebabCase,
 9723        window: &mut Window,
 9724        cx: &mut Context<Self>,
 9725    ) {
 9726        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9727    }
 9728
 9729    pub fn convert_to_upper_camel_case(
 9730        &mut self,
 9731        _: &ConvertToUpperCamelCase,
 9732        window: &mut Window,
 9733        cx: &mut Context<Self>,
 9734    ) {
 9735        self.manipulate_text(window, cx, |text| {
 9736            text.split('\n')
 9737                .map(|line| line.to_case(Case::UpperCamel))
 9738                .join("\n")
 9739        })
 9740    }
 9741
 9742    pub fn convert_to_lower_camel_case(
 9743        &mut self,
 9744        _: &ConvertToLowerCamelCase,
 9745        window: &mut Window,
 9746        cx: &mut Context<Self>,
 9747    ) {
 9748        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9749    }
 9750
 9751    pub fn convert_to_opposite_case(
 9752        &mut self,
 9753        _: &ConvertToOppositeCase,
 9754        window: &mut Window,
 9755        cx: &mut Context<Self>,
 9756    ) {
 9757        self.manipulate_text(window, cx, |text| {
 9758            text.chars()
 9759                .fold(String::with_capacity(text.len()), |mut t, c| {
 9760                    if c.is_uppercase() {
 9761                        t.extend(c.to_lowercase());
 9762                    } else {
 9763                        t.extend(c.to_uppercase());
 9764                    }
 9765                    t
 9766                })
 9767        })
 9768    }
 9769
 9770    pub fn convert_to_rot13(
 9771        &mut self,
 9772        _: &ConvertToRot13,
 9773        window: &mut Window,
 9774        cx: &mut Context<Self>,
 9775    ) {
 9776        self.manipulate_text(window, cx, |text| {
 9777            text.chars()
 9778                .map(|c| match c {
 9779                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9780                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9781                    _ => c,
 9782                })
 9783                .collect()
 9784        })
 9785    }
 9786
 9787    pub fn convert_to_rot47(
 9788        &mut self,
 9789        _: &ConvertToRot47,
 9790        window: &mut Window,
 9791        cx: &mut Context<Self>,
 9792    ) {
 9793        self.manipulate_text(window, cx, |text| {
 9794            text.chars()
 9795                .map(|c| {
 9796                    let code_point = c as u32;
 9797                    if code_point >= 33 && code_point <= 126 {
 9798                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9799                    }
 9800                    c
 9801                })
 9802                .collect()
 9803        })
 9804    }
 9805
 9806    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9807    where
 9808        Fn: FnMut(&str) -> String,
 9809    {
 9810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9811        let buffer = self.buffer.read(cx).snapshot(cx);
 9812
 9813        let mut new_selections = Vec::new();
 9814        let mut edits = Vec::new();
 9815        let mut selection_adjustment = 0i32;
 9816
 9817        for selection in self.selections.all::<usize>(cx) {
 9818            let selection_is_empty = selection.is_empty();
 9819
 9820            let (start, end) = if selection_is_empty {
 9821                let word_range = movement::surrounding_word(
 9822                    &display_map,
 9823                    selection.start.to_display_point(&display_map),
 9824                );
 9825                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9826                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9827                (start, end)
 9828            } else {
 9829                (selection.start, selection.end)
 9830            };
 9831
 9832            let text = buffer.text_for_range(start..end).collect::<String>();
 9833            let old_length = text.len() as i32;
 9834            let text = callback(&text);
 9835
 9836            new_selections.push(Selection {
 9837                start: (start as i32 - selection_adjustment) as usize,
 9838                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9839                goal: SelectionGoal::None,
 9840                ..selection
 9841            });
 9842
 9843            selection_adjustment += old_length - text.len() as i32;
 9844
 9845            edits.push((start..end, text));
 9846        }
 9847
 9848        self.transact(window, cx, |this, window, cx| {
 9849            this.buffer.update(cx, |buffer, cx| {
 9850                buffer.edit(edits, None, cx);
 9851            });
 9852
 9853            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9854                s.select(new_selections);
 9855            });
 9856
 9857            this.request_autoscroll(Autoscroll::fit(), cx);
 9858        });
 9859    }
 9860
 9861    pub fn duplicate(
 9862        &mut self,
 9863        upwards: bool,
 9864        whole_lines: bool,
 9865        window: &mut Window,
 9866        cx: &mut Context<Self>,
 9867    ) {
 9868        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9869
 9870        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9871        let buffer = &display_map.buffer_snapshot;
 9872        let selections = self.selections.all::<Point>(cx);
 9873
 9874        let mut edits = Vec::new();
 9875        let mut selections_iter = selections.iter().peekable();
 9876        while let Some(selection) = selections_iter.next() {
 9877            let mut rows = selection.spanned_rows(false, &display_map);
 9878            // duplicate line-wise
 9879            if whole_lines || selection.start == selection.end {
 9880                // Avoid duplicating the same lines twice.
 9881                while let Some(next_selection) = selections_iter.peek() {
 9882                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9883                    if next_rows.start < rows.end {
 9884                        rows.end = next_rows.end;
 9885                        selections_iter.next().unwrap();
 9886                    } else {
 9887                        break;
 9888                    }
 9889                }
 9890
 9891                // Copy the text from the selected row region and splice it either at the start
 9892                // or end of the region.
 9893                let start = Point::new(rows.start.0, 0);
 9894                let end = Point::new(
 9895                    rows.end.previous_row().0,
 9896                    buffer.line_len(rows.end.previous_row()),
 9897                );
 9898                let text = buffer
 9899                    .text_for_range(start..end)
 9900                    .chain(Some("\n"))
 9901                    .collect::<String>();
 9902                let insert_location = if upwards {
 9903                    Point::new(rows.end.0, 0)
 9904                } else {
 9905                    start
 9906                };
 9907                edits.push((insert_location..insert_location, text));
 9908            } else {
 9909                // duplicate character-wise
 9910                let start = selection.start;
 9911                let end = selection.end;
 9912                let text = buffer.text_for_range(start..end).collect::<String>();
 9913                edits.push((selection.end..selection.end, text));
 9914            }
 9915        }
 9916
 9917        self.transact(window, cx, |this, _, cx| {
 9918            this.buffer.update(cx, |buffer, cx| {
 9919                buffer.edit(edits, None, cx);
 9920            });
 9921
 9922            this.request_autoscroll(Autoscroll::fit(), cx);
 9923        });
 9924    }
 9925
 9926    pub fn duplicate_line_up(
 9927        &mut self,
 9928        _: &DuplicateLineUp,
 9929        window: &mut Window,
 9930        cx: &mut Context<Self>,
 9931    ) {
 9932        self.duplicate(true, true, window, cx);
 9933    }
 9934
 9935    pub fn duplicate_line_down(
 9936        &mut self,
 9937        _: &DuplicateLineDown,
 9938        window: &mut Window,
 9939        cx: &mut Context<Self>,
 9940    ) {
 9941        self.duplicate(false, true, window, cx);
 9942    }
 9943
 9944    pub fn duplicate_selection(
 9945        &mut self,
 9946        _: &DuplicateSelection,
 9947        window: &mut Window,
 9948        cx: &mut Context<Self>,
 9949    ) {
 9950        self.duplicate(false, false, window, cx);
 9951    }
 9952
 9953    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9954        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9955
 9956        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9957        let buffer = self.buffer.read(cx).snapshot(cx);
 9958
 9959        let mut edits = Vec::new();
 9960        let mut unfold_ranges = Vec::new();
 9961        let mut refold_creases = Vec::new();
 9962
 9963        let selections = self.selections.all::<Point>(cx);
 9964        let mut selections = selections.iter().peekable();
 9965        let mut contiguous_row_selections = Vec::new();
 9966        let mut new_selections = Vec::new();
 9967
 9968        while let Some(selection) = selections.next() {
 9969            // Find all the selections that span a contiguous row range
 9970            let (start_row, end_row) = consume_contiguous_rows(
 9971                &mut contiguous_row_selections,
 9972                selection,
 9973                &display_map,
 9974                &mut selections,
 9975            );
 9976
 9977            // Move the text spanned by the row range to be before the line preceding the row range
 9978            if start_row.0 > 0 {
 9979                let range_to_move = Point::new(
 9980                    start_row.previous_row().0,
 9981                    buffer.line_len(start_row.previous_row()),
 9982                )
 9983                    ..Point::new(
 9984                        end_row.previous_row().0,
 9985                        buffer.line_len(end_row.previous_row()),
 9986                    );
 9987                let insertion_point = display_map
 9988                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9989                    .0;
 9990
 9991                // Don't move lines across excerpts
 9992                if buffer
 9993                    .excerpt_containing(insertion_point..range_to_move.end)
 9994                    .is_some()
 9995                {
 9996                    let text = buffer
 9997                        .text_for_range(range_to_move.clone())
 9998                        .flat_map(|s| s.chars())
 9999                        .skip(1)
10000                        .chain(['\n'])
10001                        .collect::<String>();
10002
10003                    edits.push((
10004                        buffer.anchor_after(range_to_move.start)
10005                            ..buffer.anchor_before(range_to_move.end),
10006                        String::new(),
10007                    ));
10008                    let insertion_anchor = buffer.anchor_after(insertion_point);
10009                    edits.push((insertion_anchor..insertion_anchor, text));
10010
10011                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10012
10013                    // Move selections up
10014                    new_selections.extend(contiguous_row_selections.drain(..).map(
10015                        |mut selection| {
10016                            selection.start.row -= row_delta;
10017                            selection.end.row -= row_delta;
10018                            selection
10019                        },
10020                    ));
10021
10022                    // Move folds up
10023                    unfold_ranges.push(range_to_move.clone());
10024                    for fold in display_map.folds_in_range(
10025                        buffer.anchor_before(range_to_move.start)
10026                            ..buffer.anchor_after(range_to_move.end),
10027                    ) {
10028                        let mut start = fold.range.start.to_point(&buffer);
10029                        let mut end = fold.range.end.to_point(&buffer);
10030                        start.row -= row_delta;
10031                        end.row -= row_delta;
10032                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10033                    }
10034                }
10035            }
10036
10037            // If we didn't move line(s), preserve the existing selections
10038            new_selections.append(&mut contiguous_row_selections);
10039        }
10040
10041        self.transact(window, cx, |this, window, cx| {
10042            this.unfold_ranges(&unfold_ranges, true, true, cx);
10043            this.buffer.update(cx, |buffer, cx| {
10044                for (range, text) in edits {
10045                    buffer.edit([(range, text)], None, cx);
10046                }
10047            });
10048            this.fold_creases(refold_creases, true, window, cx);
10049            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10050                s.select(new_selections);
10051            })
10052        });
10053    }
10054
10055    pub fn move_line_down(
10056        &mut self,
10057        _: &MoveLineDown,
10058        window: &mut Window,
10059        cx: &mut Context<Self>,
10060    ) {
10061        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10062
10063        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10064        let buffer = self.buffer.read(cx).snapshot(cx);
10065
10066        let mut edits = Vec::new();
10067        let mut unfold_ranges = Vec::new();
10068        let mut refold_creases = Vec::new();
10069
10070        let selections = self.selections.all::<Point>(cx);
10071        let mut selections = selections.iter().peekable();
10072        let mut contiguous_row_selections = Vec::new();
10073        let mut new_selections = Vec::new();
10074
10075        while let Some(selection) = selections.next() {
10076            // Find all the selections that span a contiguous row range
10077            let (start_row, end_row) = consume_contiguous_rows(
10078                &mut contiguous_row_selections,
10079                selection,
10080                &display_map,
10081                &mut selections,
10082            );
10083
10084            // Move the text spanned by the row range to be after the last line of the row range
10085            if end_row.0 <= buffer.max_point().row {
10086                let range_to_move =
10087                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10088                let insertion_point = display_map
10089                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10090                    .0;
10091
10092                // Don't move lines across excerpt boundaries
10093                if buffer
10094                    .excerpt_containing(range_to_move.start..insertion_point)
10095                    .is_some()
10096                {
10097                    let mut text = String::from("\n");
10098                    text.extend(buffer.text_for_range(range_to_move.clone()));
10099                    text.pop(); // Drop trailing newline
10100                    edits.push((
10101                        buffer.anchor_after(range_to_move.start)
10102                            ..buffer.anchor_before(range_to_move.end),
10103                        String::new(),
10104                    ));
10105                    let insertion_anchor = buffer.anchor_after(insertion_point);
10106                    edits.push((insertion_anchor..insertion_anchor, text));
10107
10108                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10109
10110                    // Move selections down
10111                    new_selections.extend(contiguous_row_selections.drain(..).map(
10112                        |mut selection| {
10113                            selection.start.row += row_delta;
10114                            selection.end.row += row_delta;
10115                            selection
10116                        },
10117                    ));
10118
10119                    // Move folds down
10120                    unfold_ranges.push(range_to_move.clone());
10121                    for fold in display_map.folds_in_range(
10122                        buffer.anchor_before(range_to_move.start)
10123                            ..buffer.anchor_after(range_to_move.end),
10124                    ) {
10125                        let mut start = fold.range.start.to_point(&buffer);
10126                        let mut end = fold.range.end.to_point(&buffer);
10127                        start.row += row_delta;
10128                        end.row += row_delta;
10129                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10130                    }
10131                }
10132            }
10133
10134            // If we didn't move line(s), preserve the existing selections
10135            new_selections.append(&mut contiguous_row_selections);
10136        }
10137
10138        self.transact(window, cx, |this, window, cx| {
10139            this.unfold_ranges(&unfold_ranges, true, true, cx);
10140            this.buffer.update(cx, |buffer, cx| {
10141                for (range, text) in edits {
10142                    buffer.edit([(range, text)], None, cx);
10143                }
10144            });
10145            this.fold_creases(refold_creases, true, window, cx);
10146            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10147                s.select(new_selections)
10148            });
10149        });
10150    }
10151
10152    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10153        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10154        let text_layout_details = &self.text_layout_details(window);
10155        self.transact(window, cx, |this, window, cx| {
10156            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10157                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10158                s.move_with(|display_map, selection| {
10159                    if !selection.is_empty() {
10160                        return;
10161                    }
10162
10163                    let mut head = selection.head();
10164                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10165                    if head.column() == display_map.line_len(head.row()) {
10166                        transpose_offset = display_map
10167                            .buffer_snapshot
10168                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10169                    }
10170
10171                    if transpose_offset == 0 {
10172                        return;
10173                    }
10174
10175                    *head.column_mut() += 1;
10176                    head = display_map.clip_point(head, Bias::Right);
10177                    let goal = SelectionGoal::HorizontalPosition(
10178                        display_map
10179                            .x_for_display_point(head, text_layout_details)
10180                            .into(),
10181                    );
10182                    selection.collapse_to(head, goal);
10183
10184                    let transpose_start = display_map
10185                        .buffer_snapshot
10186                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10187                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10188                        let transpose_end = display_map
10189                            .buffer_snapshot
10190                            .clip_offset(transpose_offset + 1, Bias::Right);
10191                        if let Some(ch) =
10192                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10193                        {
10194                            edits.push((transpose_start..transpose_offset, String::new()));
10195                            edits.push((transpose_end..transpose_end, ch.to_string()));
10196                        }
10197                    }
10198                });
10199                edits
10200            });
10201            this.buffer
10202                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10203            let selections = this.selections.all::<usize>(cx);
10204            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10205                s.select(selections);
10206            });
10207        });
10208    }
10209
10210    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10211        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10212        self.rewrap_impl(RewrapOptions::default(), cx)
10213    }
10214
10215    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10216        let buffer = self.buffer.read(cx).snapshot(cx);
10217        let selections = self.selections.all::<Point>(cx);
10218        let mut selections = selections.iter().peekable();
10219
10220        let mut edits = Vec::new();
10221        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10222
10223        while let Some(selection) = selections.next() {
10224            let mut start_row = selection.start.row;
10225            let mut end_row = selection.end.row;
10226
10227            // Skip selections that overlap with a range that has already been rewrapped.
10228            let selection_range = start_row..end_row;
10229            if rewrapped_row_ranges
10230                .iter()
10231                .any(|range| range.overlaps(&selection_range))
10232            {
10233                continue;
10234            }
10235
10236            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10237
10238            // Since not all lines in the selection may be at the same indent
10239            // level, choose the indent size that is the most common between all
10240            // of the lines.
10241            //
10242            // If there is a tie, we use the deepest indent.
10243            let (indent_size, indent_end) = {
10244                let mut indent_size_occurrences = HashMap::default();
10245                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10246
10247                for row in start_row..=end_row {
10248                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10249                    rows_by_indent_size.entry(indent).or_default().push(row);
10250                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10251                }
10252
10253                let indent_size = indent_size_occurrences
10254                    .into_iter()
10255                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10256                    .map(|(indent, _)| indent)
10257                    .unwrap_or_default();
10258                let row = rows_by_indent_size[&indent_size][0];
10259                let indent_end = Point::new(row, indent_size.len);
10260
10261                (indent_size, indent_end)
10262            };
10263
10264            let mut line_prefix = indent_size.chars().collect::<String>();
10265
10266            let mut inside_comment = false;
10267            if let Some(comment_prefix) =
10268                buffer
10269                    .language_scope_at(selection.head())
10270                    .and_then(|language| {
10271                        language
10272                            .line_comment_prefixes()
10273                            .iter()
10274                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10275                            .cloned()
10276                    })
10277            {
10278                line_prefix.push_str(&comment_prefix);
10279                inside_comment = true;
10280            }
10281
10282            let language_settings = buffer.language_settings_at(selection.head(), cx);
10283            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10284                RewrapBehavior::InComments => inside_comment,
10285                RewrapBehavior::InSelections => !selection.is_empty(),
10286                RewrapBehavior::Anywhere => true,
10287            };
10288
10289            let should_rewrap = options.override_language_settings
10290                || allow_rewrap_based_on_language
10291                || self.hard_wrap.is_some();
10292            if !should_rewrap {
10293                continue;
10294            }
10295
10296            if selection.is_empty() {
10297                'expand_upwards: while start_row > 0 {
10298                    let prev_row = start_row - 1;
10299                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10300                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10301                    {
10302                        start_row = prev_row;
10303                    } else {
10304                        break 'expand_upwards;
10305                    }
10306                }
10307
10308                'expand_downwards: while end_row < buffer.max_point().row {
10309                    let next_row = end_row + 1;
10310                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10311                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10312                    {
10313                        end_row = next_row;
10314                    } else {
10315                        break 'expand_downwards;
10316                    }
10317                }
10318            }
10319
10320            let start = Point::new(start_row, 0);
10321            let start_offset = start.to_offset(&buffer);
10322            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10323            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10324            let Some(lines_without_prefixes) = selection_text
10325                .lines()
10326                .map(|line| {
10327                    line.strip_prefix(&line_prefix)
10328                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10329                        .ok_or_else(|| {
10330                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10331                        })
10332                })
10333                .collect::<Result<Vec<_>, _>>()
10334                .log_err()
10335            else {
10336                continue;
10337            };
10338
10339            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10340                buffer
10341                    .language_settings_at(Point::new(start_row, 0), cx)
10342                    .preferred_line_length as usize
10343            });
10344            let wrapped_text = wrap_with_prefix(
10345                line_prefix,
10346                lines_without_prefixes.join("\n"),
10347                wrap_column,
10348                tab_size,
10349                options.preserve_existing_whitespace,
10350            );
10351
10352            // TODO: should always use char-based diff while still supporting cursor behavior that
10353            // matches vim.
10354            let mut diff_options = DiffOptions::default();
10355            if options.override_language_settings {
10356                diff_options.max_word_diff_len = 0;
10357                diff_options.max_word_diff_line_count = 0;
10358            } else {
10359                diff_options.max_word_diff_len = usize::MAX;
10360                diff_options.max_word_diff_line_count = usize::MAX;
10361            }
10362
10363            for (old_range, new_text) in
10364                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10365            {
10366                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10367                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10368                edits.push((edit_start..edit_end, new_text));
10369            }
10370
10371            rewrapped_row_ranges.push(start_row..=end_row);
10372        }
10373
10374        self.buffer
10375            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10376    }
10377
10378    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10379        let mut text = String::new();
10380        let buffer = self.buffer.read(cx).snapshot(cx);
10381        let mut selections = self.selections.all::<Point>(cx);
10382        let mut clipboard_selections = Vec::with_capacity(selections.len());
10383        {
10384            let max_point = buffer.max_point();
10385            let mut is_first = true;
10386            for selection in &mut selections {
10387                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10388                if is_entire_line {
10389                    selection.start = Point::new(selection.start.row, 0);
10390                    if !selection.is_empty() && selection.end.column == 0 {
10391                        selection.end = cmp::min(max_point, selection.end);
10392                    } else {
10393                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10394                    }
10395                    selection.goal = SelectionGoal::None;
10396                }
10397                if is_first {
10398                    is_first = false;
10399                } else {
10400                    text += "\n";
10401                }
10402                let mut len = 0;
10403                for chunk in buffer.text_for_range(selection.start..selection.end) {
10404                    text.push_str(chunk);
10405                    len += chunk.len();
10406                }
10407                clipboard_selections.push(ClipboardSelection {
10408                    len,
10409                    is_entire_line,
10410                    first_line_indent: buffer
10411                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10412                        .len,
10413                });
10414            }
10415        }
10416
10417        self.transact(window, cx, |this, window, cx| {
10418            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10419                s.select(selections);
10420            });
10421            this.insert("", window, cx);
10422        });
10423        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10424    }
10425
10426    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10427        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10428        let item = self.cut_common(window, cx);
10429        cx.write_to_clipboard(item);
10430    }
10431
10432    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10433        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10434        self.change_selections(None, window, cx, |s| {
10435            s.move_with(|snapshot, sel| {
10436                if sel.is_empty() {
10437                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10438                }
10439            });
10440        });
10441        let item = self.cut_common(window, cx);
10442        cx.set_global(KillRing(item))
10443    }
10444
10445    pub fn kill_ring_yank(
10446        &mut self,
10447        _: &KillRingYank,
10448        window: &mut Window,
10449        cx: &mut Context<Self>,
10450    ) {
10451        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10452        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10453            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10454                (kill_ring.text().to_string(), kill_ring.metadata_json())
10455            } else {
10456                return;
10457            }
10458        } else {
10459            return;
10460        };
10461        self.do_paste(&text, metadata, false, window, cx);
10462    }
10463
10464    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10465        self.do_copy(true, cx);
10466    }
10467
10468    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10469        self.do_copy(false, cx);
10470    }
10471
10472    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10473        let selections = self.selections.all::<Point>(cx);
10474        let buffer = self.buffer.read(cx).read(cx);
10475        let mut text = String::new();
10476
10477        let mut clipboard_selections = Vec::with_capacity(selections.len());
10478        {
10479            let max_point = buffer.max_point();
10480            let mut is_first = true;
10481            for selection in &selections {
10482                let mut start = selection.start;
10483                let mut end = selection.end;
10484                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10485                if is_entire_line {
10486                    start = Point::new(start.row, 0);
10487                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10488                }
10489
10490                let mut trimmed_selections = Vec::new();
10491                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10492                    let row = MultiBufferRow(start.row);
10493                    let first_indent = buffer.indent_size_for_line(row);
10494                    if first_indent.len == 0 || start.column > first_indent.len {
10495                        trimmed_selections.push(start..end);
10496                    } else {
10497                        trimmed_selections.push(
10498                            Point::new(row.0, first_indent.len)
10499                                ..Point::new(row.0, buffer.line_len(row)),
10500                        );
10501                        for row in start.row + 1..=end.row {
10502                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10503                            if row == end.row {
10504                                line_len = end.column;
10505                            }
10506                            if line_len == 0 {
10507                                trimmed_selections
10508                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10509                                continue;
10510                            }
10511                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10512                            if row_indent_size.len >= first_indent.len {
10513                                trimmed_selections.push(
10514                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10515                                );
10516                            } else {
10517                                trimmed_selections.clear();
10518                                trimmed_selections.push(start..end);
10519                                break;
10520                            }
10521                        }
10522                    }
10523                } else {
10524                    trimmed_selections.push(start..end);
10525                }
10526
10527                for trimmed_range in trimmed_selections {
10528                    if is_first {
10529                        is_first = false;
10530                    } else {
10531                        text += "\n";
10532                    }
10533                    let mut len = 0;
10534                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10535                        text.push_str(chunk);
10536                        len += chunk.len();
10537                    }
10538                    clipboard_selections.push(ClipboardSelection {
10539                        len,
10540                        is_entire_line,
10541                        first_line_indent: buffer
10542                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10543                            .len,
10544                    });
10545                }
10546            }
10547        }
10548
10549        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10550            text,
10551            clipboard_selections,
10552        ));
10553    }
10554
10555    pub fn do_paste(
10556        &mut self,
10557        text: &String,
10558        clipboard_selections: Option<Vec<ClipboardSelection>>,
10559        handle_entire_lines: bool,
10560        window: &mut Window,
10561        cx: &mut Context<Self>,
10562    ) {
10563        if self.read_only(cx) {
10564            return;
10565        }
10566
10567        let clipboard_text = Cow::Borrowed(text);
10568
10569        self.transact(window, cx, |this, window, cx| {
10570            if let Some(mut clipboard_selections) = clipboard_selections {
10571                let old_selections = this.selections.all::<usize>(cx);
10572                let all_selections_were_entire_line =
10573                    clipboard_selections.iter().all(|s| s.is_entire_line);
10574                let first_selection_indent_column =
10575                    clipboard_selections.first().map(|s| s.first_line_indent);
10576                if clipboard_selections.len() != old_selections.len() {
10577                    clipboard_selections.drain(..);
10578                }
10579                let cursor_offset = this.selections.last::<usize>(cx).head();
10580                let mut auto_indent_on_paste = true;
10581
10582                this.buffer.update(cx, |buffer, cx| {
10583                    let snapshot = buffer.read(cx);
10584                    auto_indent_on_paste = snapshot
10585                        .language_settings_at(cursor_offset, cx)
10586                        .auto_indent_on_paste;
10587
10588                    let mut start_offset = 0;
10589                    let mut edits = Vec::new();
10590                    let mut original_indent_columns = Vec::new();
10591                    for (ix, selection) in old_selections.iter().enumerate() {
10592                        let to_insert;
10593                        let entire_line;
10594                        let original_indent_column;
10595                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10596                            let end_offset = start_offset + clipboard_selection.len;
10597                            to_insert = &clipboard_text[start_offset..end_offset];
10598                            entire_line = clipboard_selection.is_entire_line;
10599                            start_offset = end_offset + 1;
10600                            original_indent_column = Some(clipboard_selection.first_line_indent);
10601                        } else {
10602                            to_insert = clipboard_text.as_str();
10603                            entire_line = all_selections_were_entire_line;
10604                            original_indent_column = first_selection_indent_column
10605                        }
10606
10607                        // If the corresponding selection was empty when this slice of the
10608                        // clipboard text was written, then the entire line containing the
10609                        // selection was copied. If this selection is also currently empty,
10610                        // then paste the line before the current line of the buffer.
10611                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10612                            let column = selection.start.to_point(&snapshot).column as usize;
10613                            let line_start = selection.start - column;
10614                            line_start..line_start
10615                        } else {
10616                            selection.range()
10617                        };
10618
10619                        edits.push((range, to_insert));
10620                        original_indent_columns.push(original_indent_column);
10621                    }
10622                    drop(snapshot);
10623
10624                    buffer.edit(
10625                        edits,
10626                        if auto_indent_on_paste {
10627                            Some(AutoindentMode::Block {
10628                                original_indent_columns,
10629                            })
10630                        } else {
10631                            None
10632                        },
10633                        cx,
10634                    );
10635                });
10636
10637                let selections = this.selections.all::<usize>(cx);
10638                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639                    s.select(selections)
10640                });
10641            } else {
10642                this.insert(&clipboard_text, window, cx);
10643            }
10644        });
10645    }
10646
10647    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10648        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10649        if let Some(item) = cx.read_from_clipboard() {
10650            let entries = item.entries();
10651
10652            match entries.first() {
10653                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10654                // of all the pasted entries.
10655                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10656                    .do_paste(
10657                        clipboard_string.text(),
10658                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10659                        true,
10660                        window,
10661                        cx,
10662                    ),
10663                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10664            }
10665        }
10666    }
10667
10668    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10669        if self.read_only(cx) {
10670            return;
10671        }
10672
10673        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10674
10675        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10676            if let Some((selections, _)) =
10677                self.selection_history.transaction(transaction_id).cloned()
10678            {
10679                self.change_selections(None, window, cx, |s| {
10680                    s.select_anchors(selections.to_vec());
10681                });
10682            } else {
10683                log::error!(
10684                    "No entry in selection_history found for undo. \
10685                     This may correspond to a bug where undo does not update the selection. \
10686                     If this is occurring, please add details to \
10687                     https://github.com/zed-industries/zed/issues/22692"
10688                );
10689            }
10690            self.request_autoscroll(Autoscroll::fit(), cx);
10691            self.unmark_text(window, cx);
10692            self.refresh_inline_completion(true, false, window, cx);
10693            cx.emit(EditorEvent::Edited { transaction_id });
10694            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10695        }
10696    }
10697
10698    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10699        if self.read_only(cx) {
10700            return;
10701        }
10702
10703        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10704
10705        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10706            if let Some((_, Some(selections))) =
10707                self.selection_history.transaction(transaction_id).cloned()
10708            {
10709                self.change_selections(None, window, cx, |s| {
10710                    s.select_anchors(selections.to_vec());
10711                });
10712            } else {
10713                log::error!(
10714                    "No entry in selection_history found for redo. \
10715                     This may correspond to a bug where undo does not update the selection. \
10716                     If this is occurring, please add details to \
10717                     https://github.com/zed-industries/zed/issues/22692"
10718                );
10719            }
10720            self.request_autoscroll(Autoscroll::fit(), cx);
10721            self.unmark_text(window, cx);
10722            self.refresh_inline_completion(true, false, window, cx);
10723            cx.emit(EditorEvent::Edited { transaction_id });
10724        }
10725    }
10726
10727    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10728        self.buffer
10729            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10730    }
10731
10732    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10733        self.buffer
10734            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10735    }
10736
10737    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10738        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10739        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10740            s.move_with(|map, selection| {
10741                let cursor = if selection.is_empty() {
10742                    movement::left(map, selection.start)
10743                } else {
10744                    selection.start
10745                };
10746                selection.collapse_to(cursor, SelectionGoal::None);
10747            });
10748        })
10749    }
10750
10751    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10752        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10753        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10754            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10755        })
10756    }
10757
10758    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10759        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10760        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10761            s.move_with(|map, selection| {
10762                let cursor = if selection.is_empty() {
10763                    movement::right(map, selection.end)
10764                } else {
10765                    selection.end
10766                };
10767                selection.collapse_to(cursor, SelectionGoal::None)
10768            });
10769        })
10770    }
10771
10772    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10773        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10774        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10775            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10776        })
10777    }
10778
10779    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10780        if self.take_rename(true, window, cx).is_some() {
10781            return;
10782        }
10783
10784        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10785            cx.propagate();
10786            return;
10787        }
10788
10789        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10790
10791        let text_layout_details = &self.text_layout_details(window);
10792        let selection_count = self.selections.count();
10793        let first_selection = self.selections.first_anchor();
10794
10795        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10796            s.move_with(|map, selection| {
10797                if !selection.is_empty() {
10798                    selection.goal = SelectionGoal::None;
10799                }
10800                let (cursor, goal) = movement::up(
10801                    map,
10802                    selection.start,
10803                    selection.goal,
10804                    false,
10805                    text_layout_details,
10806                );
10807                selection.collapse_to(cursor, goal);
10808            });
10809        });
10810
10811        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10812        {
10813            cx.propagate();
10814        }
10815    }
10816
10817    pub fn move_up_by_lines(
10818        &mut self,
10819        action: &MoveUpByLines,
10820        window: &mut Window,
10821        cx: &mut Context<Self>,
10822    ) {
10823        if self.take_rename(true, window, cx).is_some() {
10824            return;
10825        }
10826
10827        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10828            cx.propagate();
10829            return;
10830        }
10831
10832        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10833
10834        let text_layout_details = &self.text_layout_details(window);
10835
10836        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10837            s.move_with(|map, selection| {
10838                if !selection.is_empty() {
10839                    selection.goal = SelectionGoal::None;
10840                }
10841                let (cursor, goal) = movement::up_by_rows(
10842                    map,
10843                    selection.start,
10844                    action.lines,
10845                    selection.goal,
10846                    false,
10847                    text_layout_details,
10848                );
10849                selection.collapse_to(cursor, goal);
10850            });
10851        })
10852    }
10853
10854    pub fn move_down_by_lines(
10855        &mut self,
10856        action: &MoveDownByLines,
10857        window: &mut Window,
10858        cx: &mut Context<Self>,
10859    ) {
10860        if self.take_rename(true, window, cx).is_some() {
10861            return;
10862        }
10863
10864        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10865            cx.propagate();
10866            return;
10867        }
10868
10869        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10870
10871        let text_layout_details = &self.text_layout_details(window);
10872
10873        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10874            s.move_with(|map, selection| {
10875                if !selection.is_empty() {
10876                    selection.goal = SelectionGoal::None;
10877                }
10878                let (cursor, goal) = movement::down_by_rows(
10879                    map,
10880                    selection.start,
10881                    action.lines,
10882                    selection.goal,
10883                    false,
10884                    text_layout_details,
10885                );
10886                selection.collapse_to(cursor, goal);
10887            });
10888        })
10889    }
10890
10891    pub fn select_down_by_lines(
10892        &mut self,
10893        action: &SelectDownByLines,
10894        window: &mut Window,
10895        cx: &mut Context<Self>,
10896    ) {
10897        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10898        let text_layout_details = &self.text_layout_details(window);
10899        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900            s.move_heads_with(|map, head, goal| {
10901                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10902            })
10903        })
10904    }
10905
10906    pub fn select_up_by_lines(
10907        &mut self,
10908        action: &SelectUpByLines,
10909        window: &mut Window,
10910        cx: &mut Context<Self>,
10911    ) {
10912        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10913        let text_layout_details = &self.text_layout_details(window);
10914        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10915            s.move_heads_with(|map, head, goal| {
10916                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10917            })
10918        })
10919    }
10920
10921    pub fn select_page_up(
10922        &mut self,
10923        _: &SelectPageUp,
10924        window: &mut Window,
10925        cx: &mut Context<Self>,
10926    ) {
10927        let Some(row_count) = self.visible_row_count() else {
10928            return;
10929        };
10930
10931        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10932
10933        let text_layout_details = &self.text_layout_details(window);
10934
10935        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10936            s.move_heads_with(|map, head, goal| {
10937                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10938            })
10939        })
10940    }
10941
10942    pub fn move_page_up(
10943        &mut self,
10944        action: &MovePageUp,
10945        window: &mut Window,
10946        cx: &mut Context<Self>,
10947    ) {
10948        if self.take_rename(true, window, cx).is_some() {
10949            return;
10950        }
10951
10952        if self
10953            .context_menu
10954            .borrow_mut()
10955            .as_mut()
10956            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10957            .unwrap_or(false)
10958        {
10959            return;
10960        }
10961
10962        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10963            cx.propagate();
10964            return;
10965        }
10966
10967        let Some(row_count) = self.visible_row_count() else {
10968            return;
10969        };
10970
10971        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10972
10973        let autoscroll = if action.center_cursor {
10974            Autoscroll::center()
10975        } else {
10976            Autoscroll::fit()
10977        };
10978
10979        let text_layout_details = &self.text_layout_details(window);
10980
10981        self.change_selections(Some(autoscroll), window, cx, |s| {
10982            s.move_with(|map, selection| {
10983                if !selection.is_empty() {
10984                    selection.goal = SelectionGoal::None;
10985                }
10986                let (cursor, goal) = movement::up_by_rows(
10987                    map,
10988                    selection.end,
10989                    row_count,
10990                    selection.goal,
10991                    false,
10992                    text_layout_details,
10993                );
10994                selection.collapse_to(cursor, goal);
10995            });
10996        });
10997    }
10998
10999    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11000        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11001        let text_layout_details = &self.text_layout_details(window);
11002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11003            s.move_heads_with(|map, head, goal| {
11004                movement::up(map, head, goal, false, text_layout_details)
11005            })
11006        })
11007    }
11008
11009    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11010        self.take_rename(true, window, cx);
11011
11012        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11013            cx.propagate();
11014            return;
11015        }
11016
11017        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11018
11019        let text_layout_details = &self.text_layout_details(window);
11020        let selection_count = self.selections.count();
11021        let first_selection = self.selections.first_anchor();
11022
11023        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11024            s.move_with(|map, selection| {
11025                if !selection.is_empty() {
11026                    selection.goal = SelectionGoal::None;
11027                }
11028                let (cursor, goal) = movement::down(
11029                    map,
11030                    selection.end,
11031                    selection.goal,
11032                    false,
11033                    text_layout_details,
11034                );
11035                selection.collapse_to(cursor, goal);
11036            });
11037        });
11038
11039        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11040        {
11041            cx.propagate();
11042        }
11043    }
11044
11045    pub fn select_page_down(
11046        &mut self,
11047        _: &SelectPageDown,
11048        window: &mut Window,
11049        cx: &mut Context<Self>,
11050    ) {
11051        let Some(row_count) = self.visible_row_count() else {
11052            return;
11053        };
11054
11055        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11056
11057        let text_layout_details = &self.text_layout_details(window);
11058
11059        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060            s.move_heads_with(|map, head, goal| {
11061                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11062            })
11063        })
11064    }
11065
11066    pub fn move_page_down(
11067        &mut self,
11068        action: &MovePageDown,
11069        window: &mut Window,
11070        cx: &mut Context<Self>,
11071    ) {
11072        if self.take_rename(true, window, cx).is_some() {
11073            return;
11074        }
11075
11076        if self
11077            .context_menu
11078            .borrow_mut()
11079            .as_mut()
11080            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11081            .unwrap_or(false)
11082        {
11083            return;
11084        }
11085
11086        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11087            cx.propagate();
11088            return;
11089        }
11090
11091        let Some(row_count) = self.visible_row_count() else {
11092            return;
11093        };
11094
11095        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11096
11097        let autoscroll = if action.center_cursor {
11098            Autoscroll::center()
11099        } else {
11100            Autoscroll::fit()
11101        };
11102
11103        let text_layout_details = &self.text_layout_details(window);
11104        self.change_selections(Some(autoscroll), window, cx, |s| {
11105            s.move_with(|map, selection| {
11106                if !selection.is_empty() {
11107                    selection.goal = SelectionGoal::None;
11108                }
11109                let (cursor, goal) = movement::down_by_rows(
11110                    map,
11111                    selection.end,
11112                    row_count,
11113                    selection.goal,
11114                    false,
11115                    text_layout_details,
11116                );
11117                selection.collapse_to(cursor, goal);
11118            });
11119        });
11120    }
11121
11122    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11123        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11124        let text_layout_details = &self.text_layout_details(window);
11125        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11126            s.move_heads_with(|map, head, goal| {
11127                movement::down(map, head, goal, false, text_layout_details)
11128            })
11129        });
11130    }
11131
11132    pub fn context_menu_first(
11133        &mut self,
11134        _: &ContextMenuFirst,
11135        _window: &mut Window,
11136        cx: &mut Context<Self>,
11137    ) {
11138        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11139            context_menu.select_first(self.completion_provider.as_deref(), cx);
11140        }
11141    }
11142
11143    pub fn context_menu_prev(
11144        &mut self,
11145        _: &ContextMenuPrevious,
11146        _window: &mut Window,
11147        cx: &mut Context<Self>,
11148    ) {
11149        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11150            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11151        }
11152    }
11153
11154    pub fn context_menu_next(
11155        &mut self,
11156        _: &ContextMenuNext,
11157        _window: &mut Window,
11158        cx: &mut Context<Self>,
11159    ) {
11160        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11161            context_menu.select_next(self.completion_provider.as_deref(), cx);
11162        }
11163    }
11164
11165    pub fn context_menu_last(
11166        &mut self,
11167        _: &ContextMenuLast,
11168        _window: &mut Window,
11169        cx: &mut Context<Self>,
11170    ) {
11171        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11172            context_menu.select_last(self.completion_provider.as_deref(), cx);
11173        }
11174    }
11175
11176    pub fn move_to_previous_word_start(
11177        &mut self,
11178        _: &MoveToPreviousWordStart,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11183        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11184            s.move_cursors_with(|map, head, _| {
11185                (
11186                    movement::previous_word_start(map, head),
11187                    SelectionGoal::None,
11188                )
11189            });
11190        })
11191    }
11192
11193    pub fn move_to_previous_subword_start(
11194        &mut self,
11195        _: &MoveToPreviousSubwordStart,
11196        window: &mut Window,
11197        cx: &mut Context<Self>,
11198    ) {
11199        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11200        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11201            s.move_cursors_with(|map, head, _| {
11202                (
11203                    movement::previous_subword_start(map, head),
11204                    SelectionGoal::None,
11205                )
11206            });
11207        })
11208    }
11209
11210    pub fn select_to_previous_word_start(
11211        &mut self,
11212        _: &SelectToPreviousWordStart,
11213        window: &mut Window,
11214        cx: &mut Context<Self>,
11215    ) {
11216        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11217        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11218            s.move_heads_with(|map, head, _| {
11219                (
11220                    movement::previous_word_start(map, head),
11221                    SelectionGoal::None,
11222                )
11223            });
11224        })
11225    }
11226
11227    pub fn select_to_previous_subword_start(
11228        &mut self,
11229        _: &SelectToPreviousSubwordStart,
11230        window: &mut Window,
11231        cx: &mut Context<Self>,
11232    ) {
11233        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11234        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11235            s.move_heads_with(|map, head, _| {
11236                (
11237                    movement::previous_subword_start(map, head),
11238                    SelectionGoal::None,
11239                )
11240            });
11241        })
11242    }
11243
11244    pub fn delete_to_previous_word_start(
11245        &mut self,
11246        action: &DeleteToPreviousWordStart,
11247        window: &mut Window,
11248        cx: &mut Context<Self>,
11249    ) {
11250        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11251        self.transact(window, cx, |this, window, cx| {
11252            this.select_autoclose_pair(window, cx);
11253            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11254                s.move_with(|map, selection| {
11255                    if selection.is_empty() {
11256                        let cursor = if action.ignore_newlines {
11257                            movement::previous_word_start(map, selection.head())
11258                        } else {
11259                            movement::previous_word_start_or_newline(map, selection.head())
11260                        };
11261                        selection.set_head(cursor, SelectionGoal::None);
11262                    }
11263                });
11264            });
11265            this.insert("", window, cx);
11266        });
11267    }
11268
11269    pub fn delete_to_previous_subword_start(
11270        &mut self,
11271        _: &DeleteToPreviousSubwordStart,
11272        window: &mut Window,
11273        cx: &mut Context<Self>,
11274    ) {
11275        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11276        self.transact(window, cx, |this, window, cx| {
11277            this.select_autoclose_pair(window, cx);
11278            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11279                s.move_with(|map, selection| {
11280                    if selection.is_empty() {
11281                        let cursor = movement::previous_subword_start(map, selection.head());
11282                        selection.set_head(cursor, SelectionGoal::None);
11283                    }
11284                });
11285            });
11286            this.insert("", window, cx);
11287        });
11288    }
11289
11290    pub fn move_to_next_word_end(
11291        &mut self,
11292        _: &MoveToNextWordEnd,
11293        window: &mut Window,
11294        cx: &mut Context<Self>,
11295    ) {
11296        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11297        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11298            s.move_cursors_with(|map, head, _| {
11299                (movement::next_word_end(map, head), SelectionGoal::None)
11300            });
11301        })
11302    }
11303
11304    pub fn move_to_next_subword_end(
11305        &mut self,
11306        _: &MoveToNextSubwordEnd,
11307        window: &mut Window,
11308        cx: &mut Context<Self>,
11309    ) {
11310        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11311        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11312            s.move_cursors_with(|map, head, _| {
11313                (movement::next_subword_end(map, head), SelectionGoal::None)
11314            });
11315        })
11316    }
11317
11318    pub fn select_to_next_word_end(
11319        &mut self,
11320        _: &SelectToNextWordEnd,
11321        window: &mut Window,
11322        cx: &mut Context<Self>,
11323    ) {
11324        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11325        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326            s.move_heads_with(|map, head, _| {
11327                (movement::next_word_end(map, head), SelectionGoal::None)
11328            });
11329        })
11330    }
11331
11332    pub fn select_to_next_subword_end(
11333        &mut self,
11334        _: &SelectToNextSubwordEnd,
11335        window: &mut Window,
11336        cx: &mut Context<Self>,
11337    ) {
11338        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11339        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11340            s.move_heads_with(|map, head, _| {
11341                (movement::next_subword_end(map, head), SelectionGoal::None)
11342            });
11343        })
11344    }
11345
11346    pub fn delete_to_next_word_end(
11347        &mut self,
11348        action: &DeleteToNextWordEnd,
11349        window: &mut Window,
11350        cx: &mut Context<Self>,
11351    ) {
11352        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11353        self.transact(window, cx, |this, window, cx| {
11354            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11355                s.move_with(|map, selection| {
11356                    if selection.is_empty() {
11357                        let cursor = if action.ignore_newlines {
11358                            movement::next_word_end(map, selection.head())
11359                        } else {
11360                            movement::next_word_end_or_newline(map, selection.head())
11361                        };
11362                        selection.set_head(cursor, SelectionGoal::None);
11363                    }
11364                });
11365            });
11366            this.insert("", window, cx);
11367        });
11368    }
11369
11370    pub fn delete_to_next_subword_end(
11371        &mut self,
11372        _: &DeleteToNextSubwordEnd,
11373        window: &mut Window,
11374        cx: &mut Context<Self>,
11375    ) {
11376        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11377        self.transact(window, cx, |this, window, cx| {
11378            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11379                s.move_with(|map, selection| {
11380                    if selection.is_empty() {
11381                        let cursor = movement::next_subword_end(map, selection.head());
11382                        selection.set_head(cursor, SelectionGoal::None);
11383                    }
11384                });
11385            });
11386            this.insert("", window, cx);
11387        });
11388    }
11389
11390    pub fn move_to_beginning_of_line(
11391        &mut self,
11392        action: &MoveToBeginningOfLine,
11393        window: &mut Window,
11394        cx: &mut Context<Self>,
11395    ) {
11396        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11397        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11398            s.move_cursors_with(|map, head, _| {
11399                (
11400                    movement::indented_line_beginning(
11401                        map,
11402                        head,
11403                        action.stop_at_soft_wraps,
11404                        action.stop_at_indent,
11405                    ),
11406                    SelectionGoal::None,
11407                )
11408            });
11409        })
11410    }
11411
11412    pub fn select_to_beginning_of_line(
11413        &mut self,
11414        action: &SelectToBeginningOfLine,
11415        window: &mut Window,
11416        cx: &mut Context<Self>,
11417    ) {
11418        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11419        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11420            s.move_heads_with(|map, head, _| {
11421                (
11422                    movement::indented_line_beginning(
11423                        map,
11424                        head,
11425                        action.stop_at_soft_wraps,
11426                        action.stop_at_indent,
11427                    ),
11428                    SelectionGoal::None,
11429                )
11430            });
11431        });
11432    }
11433
11434    pub fn delete_to_beginning_of_line(
11435        &mut self,
11436        action: &DeleteToBeginningOfLine,
11437        window: &mut Window,
11438        cx: &mut Context<Self>,
11439    ) {
11440        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11441        self.transact(window, cx, |this, window, cx| {
11442            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11443                s.move_with(|_, selection| {
11444                    selection.reversed = true;
11445                });
11446            });
11447
11448            this.select_to_beginning_of_line(
11449                &SelectToBeginningOfLine {
11450                    stop_at_soft_wraps: false,
11451                    stop_at_indent: action.stop_at_indent,
11452                },
11453                window,
11454                cx,
11455            );
11456            this.backspace(&Backspace, window, cx);
11457        });
11458    }
11459
11460    pub fn move_to_end_of_line(
11461        &mut self,
11462        action: &MoveToEndOfLine,
11463        window: &mut Window,
11464        cx: &mut Context<Self>,
11465    ) {
11466        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11467        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11468            s.move_cursors_with(|map, head, _| {
11469                (
11470                    movement::line_end(map, head, action.stop_at_soft_wraps),
11471                    SelectionGoal::None,
11472                )
11473            });
11474        })
11475    }
11476
11477    pub fn select_to_end_of_line(
11478        &mut self,
11479        action: &SelectToEndOfLine,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482    ) {
11483        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11484        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11485            s.move_heads_with(|map, head, _| {
11486                (
11487                    movement::line_end(map, head, action.stop_at_soft_wraps),
11488                    SelectionGoal::None,
11489                )
11490            });
11491        })
11492    }
11493
11494    pub fn delete_to_end_of_line(
11495        &mut self,
11496        _: &DeleteToEndOfLine,
11497        window: &mut Window,
11498        cx: &mut Context<Self>,
11499    ) {
11500        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11501        self.transact(window, cx, |this, window, cx| {
11502            this.select_to_end_of_line(
11503                &SelectToEndOfLine {
11504                    stop_at_soft_wraps: false,
11505                },
11506                window,
11507                cx,
11508            );
11509            this.delete(&Delete, window, cx);
11510        });
11511    }
11512
11513    pub fn cut_to_end_of_line(
11514        &mut self,
11515        _: &CutToEndOfLine,
11516        window: &mut Window,
11517        cx: &mut Context<Self>,
11518    ) {
11519        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11520        self.transact(window, cx, |this, window, cx| {
11521            this.select_to_end_of_line(
11522                &SelectToEndOfLine {
11523                    stop_at_soft_wraps: false,
11524                },
11525                window,
11526                cx,
11527            );
11528            this.cut(&Cut, window, cx);
11529        });
11530    }
11531
11532    pub fn move_to_start_of_paragraph(
11533        &mut self,
11534        _: &MoveToStartOfParagraph,
11535        window: &mut Window,
11536        cx: &mut Context<Self>,
11537    ) {
11538        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11539            cx.propagate();
11540            return;
11541        }
11542        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11543        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11544            s.move_with(|map, selection| {
11545                selection.collapse_to(
11546                    movement::start_of_paragraph(map, selection.head(), 1),
11547                    SelectionGoal::None,
11548                )
11549            });
11550        })
11551    }
11552
11553    pub fn move_to_end_of_paragraph(
11554        &mut self,
11555        _: &MoveToEndOfParagraph,
11556        window: &mut Window,
11557        cx: &mut Context<Self>,
11558    ) {
11559        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11560            cx.propagate();
11561            return;
11562        }
11563        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11564        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11565            s.move_with(|map, selection| {
11566                selection.collapse_to(
11567                    movement::end_of_paragraph(map, selection.head(), 1),
11568                    SelectionGoal::None,
11569                )
11570            });
11571        })
11572    }
11573
11574    pub fn select_to_start_of_paragraph(
11575        &mut self,
11576        _: &SelectToStartOfParagraph,
11577        window: &mut Window,
11578        cx: &mut Context<Self>,
11579    ) {
11580        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11581            cx.propagate();
11582            return;
11583        }
11584        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11585        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11586            s.move_heads_with(|map, head, _| {
11587                (
11588                    movement::start_of_paragraph(map, head, 1),
11589                    SelectionGoal::None,
11590                )
11591            });
11592        })
11593    }
11594
11595    pub fn select_to_end_of_paragraph(
11596        &mut self,
11597        _: &SelectToEndOfParagraph,
11598        window: &mut Window,
11599        cx: &mut Context<Self>,
11600    ) {
11601        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11602            cx.propagate();
11603            return;
11604        }
11605        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11606        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11607            s.move_heads_with(|map, head, _| {
11608                (
11609                    movement::end_of_paragraph(map, head, 1),
11610                    SelectionGoal::None,
11611                )
11612            });
11613        })
11614    }
11615
11616    pub fn move_to_start_of_excerpt(
11617        &mut self,
11618        _: &MoveToStartOfExcerpt,
11619        window: &mut Window,
11620        cx: &mut Context<Self>,
11621    ) {
11622        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11623            cx.propagate();
11624            return;
11625        }
11626        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11627        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11628            s.move_with(|map, selection| {
11629                selection.collapse_to(
11630                    movement::start_of_excerpt(
11631                        map,
11632                        selection.head(),
11633                        workspace::searchable::Direction::Prev,
11634                    ),
11635                    SelectionGoal::None,
11636                )
11637            });
11638        })
11639    }
11640
11641    pub fn move_to_start_of_next_excerpt(
11642        &mut self,
11643        _: &MoveToStartOfNextExcerpt,
11644        window: &mut Window,
11645        cx: &mut Context<Self>,
11646    ) {
11647        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11648            cx.propagate();
11649            return;
11650        }
11651
11652        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11653            s.move_with(|map, selection| {
11654                selection.collapse_to(
11655                    movement::start_of_excerpt(
11656                        map,
11657                        selection.head(),
11658                        workspace::searchable::Direction::Next,
11659                    ),
11660                    SelectionGoal::None,
11661                )
11662            });
11663        })
11664    }
11665
11666    pub fn move_to_end_of_excerpt(
11667        &mut self,
11668        _: &MoveToEndOfExcerpt,
11669        window: &mut Window,
11670        cx: &mut Context<Self>,
11671    ) {
11672        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11673            cx.propagate();
11674            return;
11675        }
11676        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11677        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11678            s.move_with(|map, selection| {
11679                selection.collapse_to(
11680                    movement::end_of_excerpt(
11681                        map,
11682                        selection.head(),
11683                        workspace::searchable::Direction::Next,
11684                    ),
11685                    SelectionGoal::None,
11686                )
11687            });
11688        })
11689    }
11690
11691    pub fn move_to_end_of_previous_excerpt(
11692        &mut self,
11693        _: &MoveToEndOfPreviousExcerpt,
11694        window: &mut Window,
11695        cx: &mut Context<Self>,
11696    ) {
11697        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11698            cx.propagate();
11699            return;
11700        }
11701        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11702        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11703            s.move_with(|map, selection| {
11704                selection.collapse_to(
11705                    movement::end_of_excerpt(
11706                        map,
11707                        selection.head(),
11708                        workspace::searchable::Direction::Prev,
11709                    ),
11710                    SelectionGoal::None,
11711                )
11712            });
11713        })
11714    }
11715
11716    pub fn select_to_start_of_excerpt(
11717        &mut self,
11718        _: &SelectToStartOfExcerpt,
11719        window: &mut Window,
11720        cx: &mut Context<Self>,
11721    ) {
11722        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11723            cx.propagate();
11724            return;
11725        }
11726        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11727        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11728            s.move_heads_with(|map, head, _| {
11729                (
11730                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11731                    SelectionGoal::None,
11732                )
11733            });
11734        })
11735    }
11736
11737    pub fn select_to_start_of_next_excerpt(
11738        &mut self,
11739        _: &SelectToStartOfNextExcerpt,
11740        window: &mut Window,
11741        cx: &mut Context<Self>,
11742    ) {
11743        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11744            cx.propagate();
11745            return;
11746        }
11747        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11749            s.move_heads_with(|map, head, _| {
11750                (
11751                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11752                    SelectionGoal::None,
11753                )
11754            });
11755        })
11756    }
11757
11758    pub fn select_to_end_of_excerpt(
11759        &mut self,
11760        _: &SelectToEndOfExcerpt,
11761        window: &mut Window,
11762        cx: &mut Context<Self>,
11763    ) {
11764        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11765            cx.propagate();
11766            return;
11767        }
11768        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11769        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11770            s.move_heads_with(|map, head, _| {
11771                (
11772                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11773                    SelectionGoal::None,
11774                )
11775            });
11776        })
11777    }
11778
11779    pub fn select_to_end_of_previous_excerpt(
11780        &mut self,
11781        _: &SelectToEndOfPreviousExcerpt,
11782        window: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11786            cx.propagate();
11787            return;
11788        }
11789        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11790        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11791            s.move_heads_with(|map, head, _| {
11792                (
11793                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11794                    SelectionGoal::None,
11795                )
11796            });
11797        })
11798    }
11799
11800    pub fn move_to_beginning(
11801        &mut self,
11802        _: &MoveToBeginning,
11803        window: &mut Window,
11804        cx: &mut Context<Self>,
11805    ) {
11806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11807            cx.propagate();
11808            return;
11809        }
11810        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11811        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11812            s.select_ranges(vec![0..0]);
11813        });
11814    }
11815
11816    pub fn select_to_beginning(
11817        &mut self,
11818        _: &SelectToBeginning,
11819        window: &mut Window,
11820        cx: &mut Context<Self>,
11821    ) {
11822        let mut selection = self.selections.last::<Point>(cx);
11823        selection.set_head(Point::zero(), SelectionGoal::None);
11824        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11825        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11826            s.select(vec![selection]);
11827        });
11828    }
11829
11830    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11831        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11832            cx.propagate();
11833            return;
11834        }
11835        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11836        let cursor = self.buffer.read(cx).read(cx).len();
11837        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11838            s.select_ranges(vec![cursor..cursor])
11839        });
11840    }
11841
11842    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11843        self.nav_history = nav_history;
11844    }
11845
11846    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11847        self.nav_history.as_ref()
11848    }
11849
11850    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11851        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11852    }
11853
11854    fn push_to_nav_history(
11855        &mut self,
11856        cursor_anchor: Anchor,
11857        new_position: Option<Point>,
11858        is_deactivate: bool,
11859        cx: &mut Context<Self>,
11860    ) {
11861        if let Some(nav_history) = self.nav_history.as_mut() {
11862            let buffer = self.buffer.read(cx).read(cx);
11863            let cursor_position = cursor_anchor.to_point(&buffer);
11864            let scroll_state = self.scroll_manager.anchor();
11865            let scroll_top_row = scroll_state.top_row(&buffer);
11866            drop(buffer);
11867
11868            if let Some(new_position) = new_position {
11869                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11870                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11871                    return;
11872                }
11873            }
11874
11875            nav_history.push(
11876                Some(NavigationData {
11877                    cursor_anchor,
11878                    cursor_position,
11879                    scroll_anchor: scroll_state,
11880                    scroll_top_row,
11881                }),
11882                cx,
11883            );
11884            cx.emit(EditorEvent::PushedToNavHistory {
11885                anchor: cursor_anchor,
11886                is_deactivate,
11887            })
11888        }
11889    }
11890
11891    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11892        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11893        let buffer = self.buffer.read(cx).snapshot(cx);
11894        let mut selection = self.selections.first::<usize>(cx);
11895        selection.set_head(buffer.len(), SelectionGoal::None);
11896        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11897            s.select(vec![selection]);
11898        });
11899    }
11900
11901    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11902        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11903        let end = self.buffer.read(cx).read(cx).len();
11904        self.change_selections(None, window, cx, |s| {
11905            s.select_ranges(vec![0..end]);
11906        });
11907    }
11908
11909    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11910        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11911        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11912        let mut selections = self.selections.all::<Point>(cx);
11913        let max_point = display_map.buffer_snapshot.max_point();
11914        for selection in &mut selections {
11915            let rows = selection.spanned_rows(true, &display_map);
11916            selection.start = Point::new(rows.start.0, 0);
11917            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11918            selection.reversed = false;
11919        }
11920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11921            s.select(selections);
11922        });
11923    }
11924
11925    pub fn split_selection_into_lines(
11926        &mut self,
11927        _: &SplitSelectionIntoLines,
11928        window: &mut Window,
11929        cx: &mut Context<Self>,
11930    ) {
11931        let selections = self
11932            .selections
11933            .all::<Point>(cx)
11934            .into_iter()
11935            .map(|selection| selection.start..selection.end)
11936            .collect::<Vec<_>>();
11937        self.unfold_ranges(&selections, true, true, cx);
11938
11939        let mut new_selection_ranges = Vec::new();
11940        {
11941            let buffer = self.buffer.read(cx).read(cx);
11942            for selection in selections {
11943                for row in selection.start.row..selection.end.row {
11944                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11945                    new_selection_ranges.push(cursor..cursor);
11946                }
11947
11948                let is_multiline_selection = selection.start.row != selection.end.row;
11949                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11950                // so this action feels more ergonomic when paired with other selection operations
11951                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11952                if !should_skip_last {
11953                    new_selection_ranges.push(selection.end..selection.end);
11954                }
11955            }
11956        }
11957        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11958            s.select_ranges(new_selection_ranges);
11959        });
11960    }
11961
11962    pub fn add_selection_above(
11963        &mut self,
11964        _: &AddSelectionAbove,
11965        window: &mut Window,
11966        cx: &mut Context<Self>,
11967    ) {
11968        self.add_selection(true, window, cx);
11969    }
11970
11971    pub fn add_selection_below(
11972        &mut self,
11973        _: &AddSelectionBelow,
11974        window: &mut Window,
11975        cx: &mut Context<Self>,
11976    ) {
11977        self.add_selection(false, window, cx);
11978    }
11979
11980    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11981        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11982
11983        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11984        let mut selections = self.selections.all::<Point>(cx);
11985        let text_layout_details = self.text_layout_details(window);
11986        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11987            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11988            let range = oldest_selection.display_range(&display_map).sorted();
11989
11990            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11991            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11992            let positions = start_x.min(end_x)..start_x.max(end_x);
11993
11994            selections.clear();
11995            let mut stack = Vec::new();
11996            for row in range.start.row().0..=range.end.row().0 {
11997                if let Some(selection) = self.selections.build_columnar_selection(
11998                    &display_map,
11999                    DisplayRow(row),
12000                    &positions,
12001                    oldest_selection.reversed,
12002                    &text_layout_details,
12003                ) {
12004                    stack.push(selection.id);
12005                    selections.push(selection);
12006                }
12007            }
12008
12009            if above {
12010                stack.reverse();
12011            }
12012
12013            AddSelectionsState { above, stack }
12014        });
12015
12016        let last_added_selection = *state.stack.last().unwrap();
12017        let mut new_selections = Vec::new();
12018        if above == state.above {
12019            let end_row = if above {
12020                DisplayRow(0)
12021            } else {
12022                display_map.max_point().row()
12023            };
12024
12025            'outer: for selection in selections {
12026                if selection.id == last_added_selection {
12027                    let range = selection.display_range(&display_map).sorted();
12028                    debug_assert_eq!(range.start.row(), range.end.row());
12029                    let mut row = range.start.row();
12030                    let positions =
12031                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12032                            px(start)..px(end)
12033                        } else {
12034                            let start_x =
12035                                display_map.x_for_display_point(range.start, &text_layout_details);
12036                            let end_x =
12037                                display_map.x_for_display_point(range.end, &text_layout_details);
12038                            start_x.min(end_x)..start_x.max(end_x)
12039                        };
12040
12041                    while row != end_row {
12042                        if above {
12043                            row.0 -= 1;
12044                        } else {
12045                            row.0 += 1;
12046                        }
12047
12048                        if let Some(new_selection) = self.selections.build_columnar_selection(
12049                            &display_map,
12050                            row,
12051                            &positions,
12052                            selection.reversed,
12053                            &text_layout_details,
12054                        ) {
12055                            state.stack.push(new_selection.id);
12056                            if above {
12057                                new_selections.push(new_selection);
12058                                new_selections.push(selection);
12059                            } else {
12060                                new_selections.push(selection);
12061                                new_selections.push(new_selection);
12062                            }
12063
12064                            continue 'outer;
12065                        }
12066                    }
12067                }
12068
12069                new_selections.push(selection);
12070            }
12071        } else {
12072            new_selections = selections;
12073            new_selections.retain(|s| s.id != last_added_selection);
12074            state.stack.pop();
12075        }
12076
12077        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12078            s.select(new_selections);
12079        });
12080        if state.stack.len() > 1 {
12081            self.add_selections_state = Some(state);
12082        }
12083    }
12084
12085    fn select_match_ranges(
12086        &mut self,
12087        range: Range<usize>,
12088        reversed: bool,
12089        replace_newest: bool,
12090        auto_scroll: Option<Autoscroll>,
12091        window: &mut Window,
12092        cx: &mut Context<Editor>,
12093    ) {
12094        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12095        self.change_selections(auto_scroll, window, cx, |s| {
12096            if replace_newest {
12097                s.delete(s.newest_anchor().id);
12098            }
12099            if reversed {
12100                s.insert_range(range.end..range.start);
12101            } else {
12102                s.insert_range(range);
12103            }
12104        });
12105    }
12106
12107    pub fn select_next_match_internal(
12108        &mut self,
12109        display_map: &DisplaySnapshot,
12110        replace_newest: bool,
12111        autoscroll: Option<Autoscroll>,
12112        window: &mut Window,
12113        cx: &mut Context<Self>,
12114    ) -> Result<()> {
12115        let buffer = &display_map.buffer_snapshot;
12116        let mut selections = self.selections.all::<usize>(cx);
12117        if let Some(mut select_next_state) = self.select_next_state.take() {
12118            let query = &select_next_state.query;
12119            if !select_next_state.done {
12120                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12121                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12122                let mut next_selected_range = None;
12123
12124                let bytes_after_last_selection =
12125                    buffer.bytes_in_range(last_selection.end..buffer.len());
12126                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12127                let query_matches = query
12128                    .stream_find_iter(bytes_after_last_selection)
12129                    .map(|result| (last_selection.end, result))
12130                    .chain(
12131                        query
12132                            .stream_find_iter(bytes_before_first_selection)
12133                            .map(|result| (0, result)),
12134                    );
12135
12136                for (start_offset, query_match) in query_matches {
12137                    let query_match = query_match.unwrap(); // can only fail due to I/O
12138                    let offset_range =
12139                        start_offset + query_match.start()..start_offset + query_match.end();
12140                    let display_range = offset_range.start.to_display_point(display_map)
12141                        ..offset_range.end.to_display_point(display_map);
12142
12143                    if !select_next_state.wordwise
12144                        || (!movement::is_inside_word(display_map, display_range.start)
12145                            && !movement::is_inside_word(display_map, display_range.end))
12146                    {
12147                        // TODO: This is n^2, because we might check all the selections
12148                        if !selections
12149                            .iter()
12150                            .any(|selection| selection.range().overlaps(&offset_range))
12151                        {
12152                            next_selected_range = Some(offset_range);
12153                            break;
12154                        }
12155                    }
12156                }
12157
12158                if let Some(next_selected_range) = next_selected_range {
12159                    self.select_match_ranges(
12160                        next_selected_range,
12161                        last_selection.reversed,
12162                        replace_newest,
12163                        autoscroll,
12164                        window,
12165                        cx,
12166                    );
12167                } else {
12168                    select_next_state.done = true;
12169                }
12170            }
12171
12172            self.select_next_state = Some(select_next_state);
12173        } else {
12174            let mut only_carets = true;
12175            let mut same_text_selected = true;
12176            let mut selected_text = None;
12177
12178            let mut selections_iter = selections.iter().peekable();
12179            while let Some(selection) = selections_iter.next() {
12180                if selection.start != selection.end {
12181                    only_carets = false;
12182                }
12183
12184                if same_text_selected {
12185                    if selected_text.is_none() {
12186                        selected_text =
12187                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12188                    }
12189
12190                    if let Some(next_selection) = selections_iter.peek() {
12191                        if next_selection.range().len() == selection.range().len() {
12192                            let next_selected_text = buffer
12193                                .text_for_range(next_selection.range())
12194                                .collect::<String>();
12195                            if Some(next_selected_text) != selected_text {
12196                                same_text_selected = false;
12197                                selected_text = None;
12198                            }
12199                        } else {
12200                            same_text_selected = false;
12201                            selected_text = None;
12202                        }
12203                    }
12204                }
12205            }
12206
12207            if only_carets {
12208                for selection in &mut selections {
12209                    let word_range = movement::surrounding_word(
12210                        display_map,
12211                        selection.start.to_display_point(display_map),
12212                    );
12213                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12214                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12215                    selection.goal = SelectionGoal::None;
12216                    selection.reversed = false;
12217                    self.select_match_ranges(
12218                        selection.start..selection.end,
12219                        selection.reversed,
12220                        replace_newest,
12221                        autoscroll,
12222                        window,
12223                        cx,
12224                    );
12225                }
12226
12227                if selections.len() == 1 {
12228                    let selection = selections
12229                        .last()
12230                        .expect("ensured that there's only one selection");
12231                    let query = buffer
12232                        .text_for_range(selection.start..selection.end)
12233                        .collect::<String>();
12234                    let is_empty = query.is_empty();
12235                    let select_state = SelectNextState {
12236                        query: AhoCorasick::new(&[query])?,
12237                        wordwise: true,
12238                        done: is_empty,
12239                    };
12240                    self.select_next_state = Some(select_state);
12241                } else {
12242                    self.select_next_state = None;
12243                }
12244            } else if let Some(selected_text) = selected_text {
12245                self.select_next_state = Some(SelectNextState {
12246                    query: AhoCorasick::new(&[selected_text])?,
12247                    wordwise: false,
12248                    done: false,
12249                });
12250                self.select_next_match_internal(
12251                    display_map,
12252                    replace_newest,
12253                    autoscroll,
12254                    window,
12255                    cx,
12256                )?;
12257            }
12258        }
12259        Ok(())
12260    }
12261
12262    pub fn select_all_matches(
12263        &mut self,
12264        _action: &SelectAllMatches,
12265        window: &mut Window,
12266        cx: &mut Context<Self>,
12267    ) -> Result<()> {
12268        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12269
12270        self.push_to_selection_history();
12271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12272
12273        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12274        let Some(select_next_state) = self.select_next_state.as_mut() else {
12275            return Ok(());
12276        };
12277        if select_next_state.done {
12278            return Ok(());
12279        }
12280
12281        let mut new_selections = Vec::new();
12282
12283        let reversed = self.selections.oldest::<usize>(cx).reversed;
12284        let buffer = &display_map.buffer_snapshot;
12285        let query_matches = select_next_state
12286            .query
12287            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12288
12289        for query_match in query_matches.into_iter() {
12290            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12291            let offset_range = if reversed {
12292                query_match.end()..query_match.start()
12293            } else {
12294                query_match.start()..query_match.end()
12295            };
12296            let display_range = offset_range.start.to_display_point(&display_map)
12297                ..offset_range.end.to_display_point(&display_map);
12298
12299            if !select_next_state.wordwise
12300                || (!movement::is_inside_word(&display_map, display_range.start)
12301                    && !movement::is_inside_word(&display_map, display_range.end))
12302            {
12303                new_selections.push(offset_range.start..offset_range.end);
12304            }
12305        }
12306
12307        select_next_state.done = true;
12308        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12309        self.change_selections(None, window, cx, |selections| {
12310            selections.select_ranges(new_selections)
12311        });
12312
12313        Ok(())
12314    }
12315
12316    pub fn select_next(
12317        &mut self,
12318        action: &SelectNext,
12319        window: &mut Window,
12320        cx: &mut Context<Self>,
12321    ) -> Result<()> {
12322        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12323        self.push_to_selection_history();
12324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12325        self.select_next_match_internal(
12326            &display_map,
12327            action.replace_newest,
12328            Some(Autoscroll::newest()),
12329            window,
12330            cx,
12331        )?;
12332        Ok(())
12333    }
12334
12335    pub fn select_previous(
12336        &mut self,
12337        action: &SelectPrevious,
12338        window: &mut Window,
12339        cx: &mut Context<Self>,
12340    ) -> Result<()> {
12341        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12342        self.push_to_selection_history();
12343        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12344        let buffer = &display_map.buffer_snapshot;
12345        let mut selections = self.selections.all::<usize>(cx);
12346        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12347            let query = &select_prev_state.query;
12348            if !select_prev_state.done {
12349                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12350                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12351                let mut next_selected_range = None;
12352                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12353                let bytes_before_last_selection =
12354                    buffer.reversed_bytes_in_range(0..last_selection.start);
12355                let bytes_after_first_selection =
12356                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12357                let query_matches = query
12358                    .stream_find_iter(bytes_before_last_selection)
12359                    .map(|result| (last_selection.start, result))
12360                    .chain(
12361                        query
12362                            .stream_find_iter(bytes_after_first_selection)
12363                            .map(|result| (buffer.len(), result)),
12364                    );
12365                for (end_offset, query_match) in query_matches {
12366                    let query_match = query_match.unwrap(); // can only fail due to I/O
12367                    let offset_range =
12368                        end_offset - query_match.end()..end_offset - query_match.start();
12369                    let display_range = offset_range.start.to_display_point(&display_map)
12370                        ..offset_range.end.to_display_point(&display_map);
12371
12372                    if !select_prev_state.wordwise
12373                        || (!movement::is_inside_word(&display_map, display_range.start)
12374                            && !movement::is_inside_word(&display_map, display_range.end))
12375                    {
12376                        next_selected_range = Some(offset_range);
12377                        break;
12378                    }
12379                }
12380
12381                if let Some(next_selected_range) = next_selected_range {
12382                    self.select_match_ranges(
12383                        next_selected_range,
12384                        last_selection.reversed,
12385                        action.replace_newest,
12386                        Some(Autoscroll::newest()),
12387                        window,
12388                        cx,
12389                    );
12390                } else {
12391                    select_prev_state.done = true;
12392                }
12393            }
12394
12395            self.select_prev_state = Some(select_prev_state);
12396        } else {
12397            let mut only_carets = true;
12398            let mut same_text_selected = true;
12399            let mut selected_text = None;
12400
12401            let mut selections_iter = selections.iter().peekable();
12402            while let Some(selection) = selections_iter.next() {
12403                if selection.start != selection.end {
12404                    only_carets = false;
12405                }
12406
12407                if same_text_selected {
12408                    if selected_text.is_none() {
12409                        selected_text =
12410                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12411                    }
12412
12413                    if let Some(next_selection) = selections_iter.peek() {
12414                        if next_selection.range().len() == selection.range().len() {
12415                            let next_selected_text = buffer
12416                                .text_for_range(next_selection.range())
12417                                .collect::<String>();
12418                            if Some(next_selected_text) != selected_text {
12419                                same_text_selected = false;
12420                                selected_text = None;
12421                            }
12422                        } else {
12423                            same_text_selected = false;
12424                            selected_text = None;
12425                        }
12426                    }
12427                }
12428            }
12429
12430            if only_carets {
12431                for selection in &mut selections {
12432                    let word_range = movement::surrounding_word(
12433                        &display_map,
12434                        selection.start.to_display_point(&display_map),
12435                    );
12436                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12437                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12438                    selection.goal = SelectionGoal::None;
12439                    selection.reversed = false;
12440                    self.select_match_ranges(
12441                        selection.start..selection.end,
12442                        selection.reversed,
12443                        action.replace_newest,
12444                        Some(Autoscroll::newest()),
12445                        window,
12446                        cx,
12447                    );
12448                }
12449                if selections.len() == 1 {
12450                    let selection = selections
12451                        .last()
12452                        .expect("ensured that there's only one selection");
12453                    let query = buffer
12454                        .text_for_range(selection.start..selection.end)
12455                        .collect::<String>();
12456                    let is_empty = query.is_empty();
12457                    let select_state = SelectNextState {
12458                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12459                        wordwise: true,
12460                        done: is_empty,
12461                    };
12462                    self.select_prev_state = Some(select_state);
12463                } else {
12464                    self.select_prev_state = None;
12465                }
12466            } else if let Some(selected_text) = selected_text {
12467                self.select_prev_state = Some(SelectNextState {
12468                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12469                    wordwise: false,
12470                    done: false,
12471                });
12472                self.select_previous(action, window, cx)?;
12473            }
12474        }
12475        Ok(())
12476    }
12477
12478    pub fn find_next_match(
12479        &mut self,
12480        _: &FindNextMatch,
12481        window: &mut Window,
12482        cx: &mut Context<Self>,
12483    ) -> Result<()> {
12484        let selections = self.selections.disjoint_anchors();
12485        match selections.first() {
12486            Some(first) if selections.len() >= 2 => {
12487                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12488                    s.select_ranges([first.range()]);
12489                });
12490            }
12491            _ => self.select_next(
12492                &SelectNext {
12493                    replace_newest: true,
12494                },
12495                window,
12496                cx,
12497            )?,
12498        }
12499        Ok(())
12500    }
12501
12502    pub fn find_previous_match(
12503        &mut self,
12504        _: &FindPreviousMatch,
12505        window: &mut Window,
12506        cx: &mut Context<Self>,
12507    ) -> Result<()> {
12508        let selections = self.selections.disjoint_anchors();
12509        match selections.last() {
12510            Some(last) if selections.len() >= 2 => {
12511                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12512                    s.select_ranges([last.range()]);
12513                });
12514            }
12515            _ => self.select_previous(
12516                &SelectPrevious {
12517                    replace_newest: true,
12518                },
12519                window,
12520                cx,
12521            )?,
12522        }
12523        Ok(())
12524    }
12525
12526    pub fn toggle_comments(
12527        &mut self,
12528        action: &ToggleComments,
12529        window: &mut Window,
12530        cx: &mut Context<Self>,
12531    ) {
12532        if self.read_only(cx) {
12533            return;
12534        }
12535        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12536        let text_layout_details = &self.text_layout_details(window);
12537        self.transact(window, cx, |this, window, cx| {
12538            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12539            let mut edits = Vec::new();
12540            let mut selection_edit_ranges = Vec::new();
12541            let mut last_toggled_row = None;
12542            let snapshot = this.buffer.read(cx).read(cx);
12543            let empty_str: Arc<str> = Arc::default();
12544            let mut suffixes_inserted = Vec::new();
12545            let ignore_indent = action.ignore_indent;
12546
12547            fn comment_prefix_range(
12548                snapshot: &MultiBufferSnapshot,
12549                row: MultiBufferRow,
12550                comment_prefix: &str,
12551                comment_prefix_whitespace: &str,
12552                ignore_indent: bool,
12553            ) -> Range<Point> {
12554                let indent_size = if ignore_indent {
12555                    0
12556                } else {
12557                    snapshot.indent_size_for_line(row).len
12558                };
12559
12560                let start = Point::new(row.0, indent_size);
12561
12562                let mut line_bytes = snapshot
12563                    .bytes_in_range(start..snapshot.max_point())
12564                    .flatten()
12565                    .copied();
12566
12567                // If this line currently begins with the line comment prefix, then record
12568                // the range containing the prefix.
12569                if line_bytes
12570                    .by_ref()
12571                    .take(comment_prefix.len())
12572                    .eq(comment_prefix.bytes())
12573                {
12574                    // Include any whitespace that matches the comment prefix.
12575                    let matching_whitespace_len = line_bytes
12576                        .zip(comment_prefix_whitespace.bytes())
12577                        .take_while(|(a, b)| a == b)
12578                        .count() as u32;
12579                    let end = Point::new(
12580                        start.row,
12581                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12582                    );
12583                    start..end
12584                } else {
12585                    start..start
12586                }
12587            }
12588
12589            fn comment_suffix_range(
12590                snapshot: &MultiBufferSnapshot,
12591                row: MultiBufferRow,
12592                comment_suffix: &str,
12593                comment_suffix_has_leading_space: bool,
12594            ) -> Range<Point> {
12595                let end = Point::new(row.0, snapshot.line_len(row));
12596                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12597
12598                let mut line_end_bytes = snapshot
12599                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12600                    .flatten()
12601                    .copied();
12602
12603                let leading_space_len = if suffix_start_column > 0
12604                    && line_end_bytes.next() == Some(b' ')
12605                    && comment_suffix_has_leading_space
12606                {
12607                    1
12608                } else {
12609                    0
12610                };
12611
12612                // If this line currently begins with the line comment prefix, then record
12613                // the range containing the prefix.
12614                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12615                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12616                    start..end
12617                } else {
12618                    end..end
12619                }
12620            }
12621
12622            // TODO: Handle selections that cross excerpts
12623            for selection in &mut selections {
12624                let start_column = snapshot
12625                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12626                    .len;
12627                let language = if let Some(language) =
12628                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12629                {
12630                    language
12631                } else {
12632                    continue;
12633                };
12634
12635                selection_edit_ranges.clear();
12636
12637                // If multiple selections contain a given row, avoid processing that
12638                // row more than once.
12639                let mut start_row = MultiBufferRow(selection.start.row);
12640                if last_toggled_row == Some(start_row) {
12641                    start_row = start_row.next_row();
12642                }
12643                let end_row =
12644                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12645                        MultiBufferRow(selection.end.row - 1)
12646                    } else {
12647                        MultiBufferRow(selection.end.row)
12648                    };
12649                last_toggled_row = Some(end_row);
12650
12651                if start_row > end_row {
12652                    continue;
12653                }
12654
12655                // If the language has line comments, toggle those.
12656                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12657
12658                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12659                if ignore_indent {
12660                    full_comment_prefixes = full_comment_prefixes
12661                        .into_iter()
12662                        .map(|s| Arc::from(s.trim_end()))
12663                        .collect();
12664                }
12665
12666                if !full_comment_prefixes.is_empty() {
12667                    let first_prefix = full_comment_prefixes
12668                        .first()
12669                        .expect("prefixes is non-empty");
12670                    let prefix_trimmed_lengths = full_comment_prefixes
12671                        .iter()
12672                        .map(|p| p.trim_end_matches(' ').len())
12673                        .collect::<SmallVec<[usize; 4]>>();
12674
12675                    let mut all_selection_lines_are_comments = true;
12676
12677                    for row in start_row.0..=end_row.0 {
12678                        let row = MultiBufferRow(row);
12679                        if start_row < end_row && snapshot.is_line_blank(row) {
12680                            continue;
12681                        }
12682
12683                        let prefix_range = full_comment_prefixes
12684                            .iter()
12685                            .zip(prefix_trimmed_lengths.iter().copied())
12686                            .map(|(prefix, trimmed_prefix_len)| {
12687                                comment_prefix_range(
12688                                    snapshot.deref(),
12689                                    row,
12690                                    &prefix[..trimmed_prefix_len],
12691                                    &prefix[trimmed_prefix_len..],
12692                                    ignore_indent,
12693                                )
12694                            })
12695                            .max_by_key(|range| range.end.column - range.start.column)
12696                            .expect("prefixes is non-empty");
12697
12698                        if prefix_range.is_empty() {
12699                            all_selection_lines_are_comments = false;
12700                        }
12701
12702                        selection_edit_ranges.push(prefix_range);
12703                    }
12704
12705                    if all_selection_lines_are_comments {
12706                        edits.extend(
12707                            selection_edit_ranges
12708                                .iter()
12709                                .cloned()
12710                                .map(|range| (range, empty_str.clone())),
12711                        );
12712                    } else {
12713                        let min_column = selection_edit_ranges
12714                            .iter()
12715                            .map(|range| range.start.column)
12716                            .min()
12717                            .unwrap_or(0);
12718                        edits.extend(selection_edit_ranges.iter().map(|range| {
12719                            let position = Point::new(range.start.row, min_column);
12720                            (position..position, first_prefix.clone())
12721                        }));
12722                    }
12723                } else if let Some((full_comment_prefix, comment_suffix)) =
12724                    language.block_comment_delimiters()
12725                {
12726                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12727                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12728                    let prefix_range = comment_prefix_range(
12729                        snapshot.deref(),
12730                        start_row,
12731                        comment_prefix,
12732                        comment_prefix_whitespace,
12733                        ignore_indent,
12734                    );
12735                    let suffix_range = comment_suffix_range(
12736                        snapshot.deref(),
12737                        end_row,
12738                        comment_suffix.trim_start_matches(' '),
12739                        comment_suffix.starts_with(' '),
12740                    );
12741
12742                    if prefix_range.is_empty() || suffix_range.is_empty() {
12743                        edits.push((
12744                            prefix_range.start..prefix_range.start,
12745                            full_comment_prefix.clone(),
12746                        ));
12747                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12748                        suffixes_inserted.push((end_row, comment_suffix.len()));
12749                    } else {
12750                        edits.push((prefix_range, empty_str.clone()));
12751                        edits.push((suffix_range, empty_str.clone()));
12752                    }
12753                } else {
12754                    continue;
12755                }
12756            }
12757
12758            drop(snapshot);
12759            this.buffer.update(cx, |buffer, cx| {
12760                buffer.edit(edits, None, cx);
12761            });
12762
12763            // Adjust selections so that they end before any comment suffixes that
12764            // were inserted.
12765            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12766            let mut selections = this.selections.all::<Point>(cx);
12767            let snapshot = this.buffer.read(cx).read(cx);
12768            for selection in &mut selections {
12769                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12770                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12771                        Ordering::Less => {
12772                            suffixes_inserted.next();
12773                            continue;
12774                        }
12775                        Ordering::Greater => break,
12776                        Ordering::Equal => {
12777                            if selection.end.column == snapshot.line_len(row) {
12778                                if selection.is_empty() {
12779                                    selection.start.column -= suffix_len as u32;
12780                                }
12781                                selection.end.column -= suffix_len as u32;
12782                            }
12783                            break;
12784                        }
12785                    }
12786                }
12787            }
12788
12789            drop(snapshot);
12790            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12791                s.select(selections)
12792            });
12793
12794            let selections = this.selections.all::<Point>(cx);
12795            let selections_on_single_row = selections.windows(2).all(|selections| {
12796                selections[0].start.row == selections[1].start.row
12797                    && selections[0].end.row == selections[1].end.row
12798                    && selections[0].start.row == selections[0].end.row
12799            });
12800            let selections_selecting = selections
12801                .iter()
12802                .any(|selection| selection.start != selection.end);
12803            let advance_downwards = action.advance_downwards
12804                && selections_on_single_row
12805                && !selections_selecting
12806                && !matches!(this.mode, EditorMode::SingleLine { .. });
12807
12808            if advance_downwards {
12809                let snapshot = this.buffer.read(cx).snapshot(cx);
12810
12811                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12812                    s.move_cursors_with(|display_snapshot, display_point, _| {
12813                        let mut point = display_point.to_point(display_snapshot);
12814                        point.row += 1;
12815                        point = snapshot.clip_point(point, Bias::Left);
12816                        let display_point = point.to_display_point(display_snapshot);
12817                        let goal = SelectionGoal::HorizontalPosition(
12818                            display_snapshot
12819                                .x_for_display_point(display_point, text_layout_details)
12820                                .into(),
12821                        );
12822                        (display_point, goal)
12823                    })
12824                });
12825            }
12826        });
12827    }
12828
12829    pub fn select_enclosing_symbol(
12830        &mut self,
12831        _: &SelectEnclosingSymbol,
12832        window: &mut Window,
12833        cx: &mut Context<Self>,
12834    ) {
12835        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12836
12837        let buffer = self.buffer.read(cx).snapshot(cx);
12838        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12839
12840        fn update_selection(
12841            selection: &Selection<usize>,
12842            buffer_snap: &MultiBufferSnapshot,
12843        ) -> Option<Selection<usize>> {
12844            let cursor = selection.head();
12845            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12846            for symbol in symbols.iter().rev() {
12847                let start = symbol.range.start.to_offset(buffer_snap);
12848                let end = symbol.range.end.to_offset(buffer_snap);
12849                let new_range = start..end;
12850                if start < selection.start || end > selection.end {
12851                    return Some(Selection {
12852                        id: selection.id,
12853                        start: new_range.start,
12854                        end: new_range.end,
12855                        goal: SelectionGoal::None,
12856                        reversed: selection.reversed,
12857                    });
12858                }
12859            }
12860            None
12861        }
12862
12863        let mut selected_larger_symbol = false;
12864        let new_selections = old_selections
12865            .iter()
12866            .map(|selection| match update_selection(selection, &buffer) {
12867                Some(new_selection) => {
12868                    if new_selection.range() != selection.range() {
12869                        selected_larger_symbol = true;
12870                    }
12871                    new_selection
12872                }
12873                None => selection.clone(),
12874            })
12875            .collect::<Vec<_>>();
12876
12877        if selected_larger_symbol {
12878            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12879                s.select(new_selections);
12880            });
12881        }
12882    }
12883
12884    pub fn select_larger_syntax_node(
12885        &mut self,
12886        _: &SelectLargerSyntaxNode,
12887        window: &mut Window,
12888        cx: &mut Context<Self>,
12889    ) {
12890        let Some(visible_row_count) = self.visible_row_count() else {
12891            return;
12892        };
12893        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12894        if old_selections.is_empty() {
12895            return;
12896        }
12897
12898        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12899
12900        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12901        let buffer = self.buffer.read(cx).snapshot(cx);
12902
12903        let mut selected_larger_node = false;
12904        let mut new_selections = old_selections
12905            .iter()
12906            .map(|selection| {
12907                let old_range = selection.start..selection.end;
12908
12909                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12910                    // manually select word at selection
12911                    if ["string_content", "inline"].contains(&node.kind()) {
12912                        let word_range = {
12913                            let display_point = buffer
12914                                .offset_to_point(old_range.start)
12915                                .to_display_point(&display_map);
12916                            let Range { start, end } =
12917                                movement::surrounding_word(&display_map, display_point);
12918                            start.to_point(&display_map).to_offset(&buffer)
12919                                ..end.to_point(&display_map).to_offset(&buffer)
12920                        };
12921                        // ignore if word is already selected
12922                        if !word_range.is_empty() && old_range != word_range {
12923                            let last_word_range = {
12924                                let display_point = buffer
12925                                    .offset_to_point(old_range.end)
12926                                    .to_display_point(&display_map);
12927                                let Range { start, end } =
12928                                    movement::surrounding_word(&display_map, display_point);
12929                                start.to_point(&display_map).to_offset(&buffer)
12930                                    ..end.to_point(&display_map).to_offset(&buffer)
12931                            };
12932                            // only select word if start and end point belongs to same word
12933                            if word_range == last_word_range {
12934                                selected_larger_node = true;
12935                                return Selection {
12936                                    id: selection.id,
12937                                    start: word_range.start,
12938                                    end: word_range.end,
12939                                    goal: SelectionGoal::None,
12940                                    reversed: selection.reversed,
12941                                };
12942                            }
12943                        }
12944                    }
12945                }
12946
12947                let mut new_range = old_range.clone();
12948                while let Some((_node, containing_range)) =
12949                    buffer.syntax_ancestor(new_range.clone())
12950                {
12951                    new_range = match containing_range {
12952                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12953                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12954                    };
12955                    if !display_map.intersects_fold(new_range.start)
12956                        && !display_map.intersects_fold(new_range.end)
12957                    {
12958                        break;
12959                    }
12960                }
12961
12962                selected_larger_node |= new_range != old_range;
12963                Selection {
12964                    id: selection.id,
12965                    start: new_range.start,
12966                    end: new_range.end,
12967                    goal: SelectionGoal::None,
12968                    reversed: selection.reversed,
12969                }
12970            })
12971            .collect::<Vec<_>>();
12972
12973        if !selected_larger_node {
12974            return; // don't put this call in the history
12975        }
12976
12977        // scroll based on transformation done to the last selection created by the user
12978        let (last_old, last_new) = old_selections
12979            .last()
12980            .zip(new_selections.last().cloned())
12981            .expect("old_selections isn't empty");
12982
12983        // revert selection
12984        let is_selection_reversed = {
12985            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12986            new_selections.last_mut().expect("checked above").reversed =
12987                should_newest_selection_be_reversed;
12988            should_newest_selection_be_reversed
12989        };
12990
12991        if selected_larger_node {
12992            self.select_syntax_node_history.disable_clearing = true;
12993            self.change_selections(None, window, cx, |s| {
12994                s.select(new_selections.clone());
12995            });
12996            self.select_syntax_node_history.disable_clearing = false;
12997        }
12998
12999        let start_row = last_new.start.to_display_point(&display_map).row().0;
13000        let end_row = last_new.end.to_display_point(&display_map).row().0;
13001        let selection_height = end_row - start_row + 1;
13002        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13003
13004        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13005        let scroll_behavior = if fits_on_the_screen {
13006            self.request_autoscroll(Autoscroll::fit(), cx);
13007            SelectSyntaxNodeScrollBehavior::FitSelection
13008        } else if is_selection_reversed {
13009            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13010            SelectSyntaxNodeScrollBehavior::CursorTop
13011        } else {
13012            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13013            SelectSyntaxNodeScrollBehavior::CursorBottom
13014        };
13015
13016        self.select_syntax_node_history.push((
13017            old_selections,
13018            scroll_behavior,
13019            is_selection_reversed,
13020        ));
13021    }
13022
13023    pub fn select_smaller_syntax_node(
13024        &mut self,
13025        _: &SelectSmallerSyntaxNode,
13026        window: &mut Window,
13027        cx: &mut Context<Self>,
13028    ) {
13029        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13030
13031        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13032            self.select_syntax_node_history.pop()
13033        {
13034            if let Some(selection) = selections.last_mut() {
13035                selection.reversed = is_selection_reversed;
13036            }
13037
13038            self.select_syntax_node_history.disable_clearing = true;
13039            self.change_selections(None, window, cx, |s| {
13040                s.select(selections.to_vec());
13041            });
13042            self.select_syntax_node_history.disable_clearing = false;
13043
13044            match scroll_behavior {
13045                SelectSyntaxNodeScrollBehavior::CursorTop => {
13046                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13047                }
13048                SelectSyntaxNodeScrollBehavior::FitSelection => {
13049                    self.request_autoscroll(Autoscroll::fit(), cx);
13050                }
13051                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13052                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13053                }
13054            }
13055        }
13056    }
13057
13058    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13059        if !EditorSettings::get_global(cx).gutter.runnables {
13060            self.clear_tasks();
13061            return Task::ready(());
13062        }
13063        let project = self.project.as_ref().map(Entity::downgrade);
13064        let task_sources = self.lsp_task_sources(cx);
13065        cx.spawn_in(window, async move |editor, cx| {
13066            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13067            let Some(project) = project.and_then(|p| p.upgrade()) else {
13068                return;
13069            };
13070            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13071                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13072            }) else {
13073                return;
13074            };
13075
13076            let hide_runnables = project
13077                .update(cx, |project, cx| {
13078                    // Do not display any test indicators in non-dev server remote projects.
13079                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13080                })
13081                .unwrap_or(true);
13082            if hide_runnables {
13083                return;
13084            }
13085            let new_rows =
13086                cx.background_spawn({
13087                    let snapshot = display_snapshot.clone();
13088                    async move {
13089                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13090                    }
13091                })
13092                    .await;
13093            let Ok(lsp_tasks) =
13094                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13095            else {
13096                return;
13097            };
13098            let lsp_tasks = lsp_tasks.await;
13099
13100            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13101                lsp_tasks
13102                    .into_iter()
13103                    .flat_map(|(kind, tasks)| {
13104                        tasks.into_iter().filter_map(move |(location, task)| {
13105                            Some((kind.clone(), location?, task))
13106                        })
13107                    })
13108                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13109                        let buffer = location.target.buffer;
13110                        let buffer_snapshot = buffer.read(cx).snapshot();
13111                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13112                            |(excerpt_id, snapshot, _)| {
13113                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13114                                    display_snapshot
13115                                        .buffer_snapshot
13116                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13117                                } else {
13118                                    None
13119                                }
13120                            },
13121                        );
13122                        if let Some(offset) = offset {
13123                            let task_buffer_range =
13124                                location.target.range.to_point(&buffer_snapshot);
13125                            let context_buffer_range =
13126                                task_buffer_range.to_offset(&buffer_snapshot);
13127                            let context_range = BufferOffset(context_buffer_range.start)
13128                                ..BufferOffset(context_buffer_range.end);
13129
13130                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13131                                .or_insert_with(|| RunnableTasks {
13132                                    templates: Vec::new(),
13133                                    offset,
13134                                    column: task_buffer_range.start.column,
13135                                    extra_variables: HashMap::default(),
13136                                    context_range,
13137                                })
13138                                .templates
13139                                .push((kind, task.original_task().clone()));
13140                        }
13141
13142                        acc
13143                    })
13144            }) else {
13145                return;
13146            };
13147
13148            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13149            editor
13150                .update(cx, |editor, _| {
13151                    editor.clear_tasks();
13152                    for (key, mut value) in rows {
13153                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13154                            value.templates.extend(lsp_tasks.templates);
13155                        }
13156
13157                        editor.insert_tasks(key, value);
13158                    }
13159                    for (key, value) in lsp_tasks_by_rows {
13160                        editor.insert_tasks(key, value);
13161                    }
13162                })
13163                .ok();
13164        })
13165    }
13166    fn fetch_runnable_ranges(
13167        snapshot: &DisplaySnapshot,
13168        range: Range<Anchor>,
13169    ) -> Vec<language::RunnableRange> {
13170        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13171    }
13172
13173    fn runnable_rows(
13174        project: Entity<Project>,
13175        snapshot: DisplaySnapshot,
13176        runnable_ranges: Vec<RunnableRange>,
13177        mut cx: AsyncWindowContext,
13178    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13179        runnable_ranges
13180            .into_iter()
13181            .filter_map(|mut runnable| {
13182                let tasks = cx
13183                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13184                    .ok()?;
13185                if tasks.is_empty() {
13186                    return None;
13187                }
13188
13189                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13190
13191                let row = snapshot
13192                    .buffer_snapshot
13193                    .buffer_line_for_row(MultiBufferRow(point.row))?
13194                    .1
13195                    .start
13196                    .row;
13197
13198                let context_range =
13199                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13200                Some((
13201                    (runnable.buffer_id, row),
13202                    RunnableTasks {
13203                        templates: tasks,
13204                        offset: snapshot
13205                            .buffer_snapshot
13206                            .anchor_before(runnable.run_range.start),
13207                        context_range,
13208                        column: point.column,
13209                        extra_variables: runnable.extra_captures,
13210                    },
13211                ))
13212            })
13213            .collect()
13214    }
13215
13216    fn templates_with_tags(
13217        project: &Entity<Project>,
13218        runnable: &mut Runnable,
13219        cx: &mut App,
13220    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13221        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13222            let (worktree_id, file) = project
13223                .buffer_for_id(runnable.buffer, cx)
13224                .and_then(|buffer| buffer.read(cx).file())
13225                .map(|file| (file.worktree_id(cx), file.clone()))
13226                .unzip();
13227
13228            (
13229                project.task_store().read(cx).task_inventory().cloned(),
13230                worktree_id,
13231                file,
13232            )
13233        });
13234
13235        let mut templates_with_tags = mem::take(&mut runnable.tags)
13236            .into_iter()
13237            .flat_map(|RunnableTag(tag)| {
13238                inventory
13239                    .as_ref()
13240                    .into_iter()
13241                    .flat_map(|inventory| {
13242                        inventory.read(cx).list_tasks(
13243                            file.clone(),
13244                            Some(runnable.language.clone()),
13245                            worktree_id,
13246                            cx,
13247                        )
13248                    })
13249                    .filter(move |(_, template)| {
13250                        template.tags.iter().any(|source_tag| source_tag == &tag)
13251                    })
13252            })
13253            .sorted_by_key(|(kind, _)| kind.to_owned())
13254            .collect::<Vec<_>>();
13255        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13256            // Strongest source wins; if we have worktree tag binding, prefer that to
13257            // global and language bindings;
13258            // if we have a global binding, prefer that to language binding.
13259            let first_mismatch = templates_with_tags
13260                .iter()
13261                .position(|(tag_source, _)| tag_source != leading_tag_source);
13262            if let Some(index) = first_mismatch {
13263                templates_with_tags.truncate(index);
13264            }
13265        }
13266
13267        templates_with_tags
13268    }
13269
13270    pub fn move_to_enclosing_bracket(
13271        &mut self,
13272        _: &MoveToEnclosingBracket,
13273        window: &mut Window,
13274        cx: &mut Context<Self>,
13275    ) {
13276        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13277        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13278            s.move_offsets_with(|snapshot, selection| {
13279                let Some(enclosing_bracket_ranges) =
13280                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13281                else {
13282                    return;
13283                };
13284
13285                let mut best_length = usize::MAX;
13286                let mut best_inside = false;
13287                let mut best_in_bracket_range = false;
13288                let mut best_destination = None;
13289                for (open, close) in enclosing_bracket_ranges {
13290                    let close = close.to_inclusive();
13291                    let length = close.end() - open.start;
13292                    let inside = selection.start >= open.end && selection.end <= *close.start();
13293                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13294                        || close.contains(&selection.head());
13295
13296                    // If best is next to a bracket and current isn't, skip
13297                    if !in_bracket_range && best_in_bracket_range {
13298                        continue;
13299                    }
13300
13301                    // Prefer smaller lengths unless best is inside and current isn't
13302                    if length > best_length && (best_inside || !inside) {
13303                        continue;
13304                    }
13305
13306                    best_length = length;
13307                    best_inside = inside;
13308                    best_in_bracket_range = in_bracket_range;
13309                    best_destination = Some(
13310                        if close.contains(&selection.start) && close.contains(&selection.end) {
13311                            if inside { open.end } else { open.start }
13312                        } else if inside {
13313                            *close.start()
13314                        } else {
13315                            *close.end()
13316                        },
13317                    );
13318                }
13319
13320                if let Some(destination) = best_destination {
13321                    selection.collapse_to(destination, SelectionGoal::None);
13322                }
13323            })
13324        });
13325    }
13326
13327    pub fn undo_selection(
13328        &mut self,
13329        _: &UndoSelection,
13330        window: &mut Window,
13331        cx: &mut Context<Self>,
13332    ) {
13333        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13334        self.end_selection(window, cx);
13335        self.selection_history.mode = SelectionHistoryMode::Undoing;
13336        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13337            self.change_selections(None, window, cx, |s| {
13338                s.select_anchors(entry.selections.to_vec())
13339            });
13340            self.select_next_state = entry.select_next_state;
13341            self.select_prev_state = entry.select_prev_state;
13342            self.add_selections_state = entry.add_selections_state;
13343            self.request_autoscroll(Autoscroll::newest(), cx);
13344        }
13345        self.selection_history.mode = SelectionHistoryMode::Normal;
13346    }
13347
13348    pub fn redo_selection(
13349        &mut self,
13350        _: &RedoSelection,
13351        window: &mut Window,
13352        cx: &mut Context<Self>,
13353    ) {
13354        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13355        self.end_selection(window, cx);
13356        self.selection_history.mode = SelectionHistoryMode::Redoing;
13357        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13358            self.change_selections(None, window, cx, |s| {
13359                s.select_anchors(entry.selections.to_vec())
13360            });
13361            self.select_next_state = entry.select_next_state;
13362            self.select_prev_state = entry.select_prev_state;
13363            self.add_selections_state = entry.add_selections_state;
13364            self.request_autoscroll(Autoscroll::newest(), cx);
13365        }
13366        self.selection_history.mode = SelectionHistoryMode::Normal;
13367    }
13368
13369    pub fn expand_excerpts(
13370        &mut self,
13371        action: &ExpandExcerpts,
13372        _: &mut Window,
13373        cx: &mut Context<Self>,
13374    ) {
13375        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13376    }
13377
13378    pub fn expand_excerpts_down(
13379        &mut self,
13380        action: &ExpandExcerptsDown,
13381        _: &mut Window,
13382        cx: &mut Context<Self>,
13383    ) {
13384        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13385    }
13386
13387    pub fn expand_excerpts_up(
13388        &mut self,
13389        action: &ExpandExcerptsUp,
13390        _: &mut Window,
13391        cx: &mut Context<Self>,
13392    ) {
13393        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13394    }
13395
13396    pub fn expand_excerpts_for_direction(
13397        &mut self,
13398        lines: u32,
13399        direction: ExpandExcerptDirection,
13400
13401        cx: &mut Context<Self>,
13402    ) {
13403        let selections = self.selections.disjoint_anchors();
13404
13405        let lines = if lines == 0 {
13406            EditorSettings::get_global(cx).expand_excerpt_lines
13407        } else {
13408            lines
13409        };
13410
13411        self.buffer.update(cx, |buffer, cx| {
13412            let snapshot = buffer.snapshot(cx);
13413            let mut excerpt_ids = selections
13414                .iter()
13415                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13416                .collect::<Vec<_>>();
13417            excerpt_ids.sort();
13418            excerpt_ids.dedup();
13419            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13420        })
13421    }
13422
13423    pub fn expand_excerpt(
13424        &mut self,
13425        excerpt: ExcerptId,
13426        direction: ExpandExcerptDirection,
13427        window: &mut Window,
13428        cx: &mut Context<Self>,
13429    ) {
13430        let current_scroll_position = self.scroll_position(cx);
13431        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13432        let mut should_scroll_up = false;
13433
13434        if direction == ExpandExcerptDirection::Down {
13435            let multi_buffer = self.buffer.read(cx);
13436            let snapshot = multi_buffer.snapshot(cx);
13437            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13438                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13439                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13440                        let buffer_snapshot = buffer.read(cx).snapshot();
13441                        let excerpt_end_row =
13442                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13443                        let last_row = buffer_snapshot.max_point().row;
13444                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13445                        should_scroll_up = lines_below >= lines_to_expand;
13446                    }
13447                }
13448            }
13449        }
13450
13451        self.buffer.update(cx, |buffer, cx| {
13452            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13453        });
13454
13455        if should_scroll_up {
13456            let new_scroll_position =
13457                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13458            self.set_scroll_position(new_scroll_position, window, cx);
13459        }
13460    }
13461
13462    pub fn go_to_singleton_buffer_point(
13463        &mut self,
13464        point: Point,
13465        window: &mut Window,
13466        cx: &mut Context<Self>,
13467    ) {
13468        self.go_to_singleton_buffer_range(point..point, window, cx);
13469    }
13470
13471    pub fn go_to_singleton_buffer_range(
13472        &mut self,
13473        range: Range<Point>,
13474        window: &mut Window,
13475        cx: &mut Context<Self>,
13476    ) {
13477        let multibuffer = self.buffer().read(cx);
13478        let Some(buffer) = multibuffer.as_singleton() else {
13479            return;
13480        };
13481        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13482            return;
13483        };
13484        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13485            return;
13486        };
13487        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13488            s.select_anchor_ranges([start..end])
13489        });
13490    }
13491
13492    pub fn go_to_diagnostic(
13493        &mut self,
13494        _: &GoToDiagnostic,
13495        window: &mut Window,
13496        cx: &mut Context<Self>,
13497    ) {
13498        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13499        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13500    }
13501
13502    pub fn go_to_prev_diagnostic(
13503        &mut self,
13504        _: &GoToPreviousDiagnostic,
13505        window: &mut Window,
13506        cx: &mut Context<Self>,
13507    ) {
13508        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13509        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13510    }
13511
13512    pub fn go_to_diagnostic_impl(
13513        &mut self,
13514        direction: Direction,
13515        window: &mut Window,
13516        cx: &mut Context<Self>,
13517    ) {
13518        let buffer = self.buffer.read(cx).snapshot(cx);
13519        let selection = self.selections.newest::<usize>(cx);
13520
13521        let mut active_group_id = None;
13522        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13523            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13524                active_group_id = Some(active_group.group_id);
13525            }
13526        }
13527
13528        fn filtered(
13529            snapshot: EditorSnapshot,
13530            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13531        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13532            diagnostics
13533                .filter(|entry| entry.range.start != entry.range.end)
13534                .filter(|entry| !entry.diagnostic.is_unnecessary)
13535                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13536        }
13537
13538        let snapshot = self.snapshot(window, cx);
13539        let before = filtered(
13540            snapshot.clone(),
13541            buffer
13542                .diagnostics_in_range(0..selection.start)
13543                .filter(|entry| entry.range.start <= selection.start),
13544        );
13545        let after = filtered(
13546            snapshot,
13547            buffer
13548                .diagnostics_in_range(selection.start..buffer.len())
13549                .filter(|entry| entry.range.start >= selection.start),
13550        );
13551
13552        let mut found: Option<DiagnosticEntry<usize>> = None;
13553        if direction == Direction::Prev {
13554            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13555            {
13556                for diagnostic in prev_diagnostics.into_iter().rev() {
13557                    if diagnostic.range.start != selection.start
13558                        || active_group_id
13559                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13560                    {
13561                        found = Some(diagnostic);
13562                        break 'outer;
13563                    }
13564                }
13565            }
13566        } else {
13567            for diagnostic in after.chain(before) {
13568                if diagnostic.range.start != selection.start
13569                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13570                {
13571                    found = Some(diagnostic);
13572                    break;
13573                }
13574            }
13575        }
13576        let Some(next_diagnostic) = found else {
13577            return;
13578        };
13579
13580        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13581            return;
13582        };
13583        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13584            s.select_ranges(vec![
13585                next_diagnostic.range.start..next_diagnostic.range.start,
13586            ])
13587        });
13588        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13589        self.refresh_inline_completion(false, true, window, cx);
13590    }
13591
13592    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13593        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13594        let snapshot = self.snapshot(window, cx);
13595        let selection = self.selections.newest::<Point>(cx);
13596        self.go_to_hunk_before_or_after_position(
13597            &snapshot,
13598            selection.head(),
13599            Direction::Next,
13600            window,
13601            cx,
13602        );
13603    }
13604
13605    pub fn go_to_hunk_before_or_after_position(
13606        &mut self,
13607        snapshot: &EditorSnapshot,
13608        position: Point,
13609        direction: Direction,
13610        window: &mut Window,
13611        cx: &mut Context<Editor>,
13612    ) {
13613        let row = if direction == Direction::Next {
13614            self.hunk_after_position(snapshot, position)
13615                .map(|hunk| hunk.row_range.start)
13616        } else {
13617            self.hunk_before_position(snapshot, position)
13618        };
13619
13620        if let Some(row) = row {
13621            let destination = Point::new(row.0, 0);
13622            let autoscroll = Autoscroll::center();
13623
13624            self.unfold_ranges(&[destination..destination], false, false, cx);
13625            self.change_selections(Some(autoscroll), window, cx, |s| {
13626                s.select_ranges([destination..destination]);
13627            });
13628        }
13629    }
13630
13631    fn hunk_after_position(
13632        &mut self,
13633        snapshot: &EditorSnapshot,
13634        position: Point,
13635    ) -> Option<MultiBufferDiffHunk> {
13636        snapshot
13637            .buffer_snapshot
13638            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13639            .find(|hunk| hunk.row_range.start.0 > position.row)
13640            .or_else(|| {
13641                snapshot
13642                    .buffer_snapshot
13643                    .diff_hunks_in_range(Point::zero()..position)
13644                    .find(|hunk| hunk.row_range.end.0 < position.row)
13645            })
13646    }
13647
13648    fn go_to_prev_hunk(
13649        &mut self,
13650        _: &GoToPreviousHunk,
13651        window: &mut Window,
13652        cx: &mut Context<Self>,
13653    ) {
13654        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13655        let snapshot = self.snapshot(window, cx);
13656        let selection = self.selections.newest::<Point>(cx);
13657        self.go_to_hunk_before_or_after_position(
13658            &snapshot,
13659            selection.head(),
13660            Direction::Prev,
13661            window,
13662            cx,
13663        );
13664    }
13665
13666    fn hunk_before_position(
13667        &mut self,
13668        snapshot: &EditorSnapshot,
13669        position: Point,
13670    ) -> Option<MultiBufferRow> {
13671        snapshot
13672            .buffer_snapshot
13673            .diff_hunk_before(position)
13674            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13675    }
13676
13677    fn go_to_next_change(
13678        &mut self,
13679        _: &GoToNextChange,
13680        window: &mut Window,
13681        cx: &mut Context<Self>,
13682    ) {
13683        if let Some(selections) = self
13684            .change_list
13685            .next_change(1, Direction::Next)
13686            .map(|s| s.to_vec())
13687        {
13688            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13689                let map = s.display_map();
13690                s.select_display_ranges(selections.iter().map(|a| {
13691                    let point = a.to_display_point(&map);
13692                    point..point
13693                }))
13694            })
13695        }
13696    }
13697
13698    fn go_to_previous_change(
13699        &mut self,
13700        _: &GoToPreviousChange,
13701        window: &mut Window,
13702        cx: &mut Context<Self>,
13703    ) {
13704        if let Some(selections) = self
13705            .change_list
13706            .next_change(1, Direction::Prev)
13707            .map(|s| s.to_vec())
13708        {
13709            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13710                let map = s.display_map();
13711                s.select_display_ranges(selections.iter().map(|a| {
13712                    let point = a.to_display_point(&map);
13713                    point..point
13714                }))
13715            })
13716        }
13717    }
13718
13719    fn go_to_line<T: 'static>(
13720        &mut self,
13721        position: Anchor,
13722        highlight_color: Option<Hsla>,
13723        window: &mut Window,
13724        cx: &mut Context<Self>,
13725    ) {
13726        let snapshot = self.snapshot(window, cx).display_snapshot;
13727        let position = position.to_point(&snapshot.buffer_snapshot);
13728        let start = snapshot
13729            .buffer_snapshot
13730            .clip_point(Point::new(position.row, 0), Bias::Left);
13731        let end = start + Point::new(1, 0);
13732        let start = snapshot.buffer_snapshot.anchor_before(start);
13733        let end = snapshot.buffer_snapshot.anchor_before(end);
13734
13735        self.highlight_rows::<T>(
13736            start..end,
13737            highlight_color
13738                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13739            Default::default(),
13740            cx,
13741        );
13742        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13743    }
13744
13745    pub fn go_to_definition(
13746        &mut self,
13747        _: &GoToDefinition,
13748        window: &mut Window,
13749        cx: &mut Context<Self>,
13750    ) -> Task<Result<Navigated>> {
13751        let definition =
13752            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13753        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13754        cx.spawn_in(window, async move |editor, cx| {
13755            if definition.await? == Navigated::Yes {
13756                return Ok(Navigated::Yes);
13757            }
13758            match fallback_strategy {
13759                GoToDefinitionFallback::None => Ok(Navigated::No),
13760                GoToDefinitionFallback::FindAllReferences => {
13761                    match editor.update_in(cx, |editor, window, cx| {
13762                        editor.find_all_references(&FindAllReferences, window, cx)
13763                    })? {
13764                        Some(references) => references.await,
13765                        None => Ok(Navigated::No),
13766                    }
13767                }
13768            }
13769        })
13770    }
13771
13772    pub fn go_to_declaration(
13773        &mut self,
13774        _: &GoToDeclaration,
13775        window: &mut Window,
13776        cx: &mut Context<Self>,
13777    ) -> Task<Result<Navigated>> {
13778        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13779    }
13780
13781    pub fn go_to_declaration_split(
13782        &mut self,
13783        _: &GoToDeclaration,
13784        window: &mut Window,
13785        cx: &mut Context<Self>,
13786    ) -> Task<Result<Navigated>> {
13787        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13788    }
13789
13790    pub fn go_to_implementation(
13791        &mut self,
13792        _: &GoToImplementation,
13793        window: &mut Window,
13794        cx: &mut Context<Self>,
13795    ) -> Task<Result<Navigated>> {
13796        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13797    }
13798
13799    pub fn go_to_implementation_split(
13800        &mut self,
13801        _: &GoToImplementationSplit,
13802        window: &mut Window,
13803        cx: &mut Context<Self>,
13804    ) -> Task<Result<Navigated>> {
13805        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13806    }
13807
13808    pub fn go_to_type_definition(
13809        &mut self,
13810        _: &GoToTypeDefinition,
13811        window: &mut Window,
13812        cx: &mut Context<Self>,
13813    ) -> Task<Result<Navigated>> {
13814        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13815    }
13816
13817    pub fn go_to_definition_split(
13818        &mut self,
13819        _: &GoToDefinitionSplit,
13820        window: &mut Window,
13821        cx: &mut Context<Self>,
13822    ) -> Task<Result<Navigated>> {
13823        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13824    }
13825
13826    pub fn go_to_type_definition_split(
13827        &mut self,
13828        _: &GoToTypeDefinitionSplit,
13829        window: &mut Window,
13830        cx: &mut Context<Self>,
13831    ) -> Task<Result<Navigated>> {
13832        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13833    }
13834
13835    fn go_to_definition_of_kind(
13836        &mut self,
13837        kind: GotoDefinitionKind,
13838        split: bool,
13839        window: &mut Window,
13840        cx: &mut Context<Self>,
13841    ) -> Task<Result<Navigated>> {
13842        let Some(provider) = self.semantics_provider.clone() else {
13843            return Task::ready(Ok(Navigated::No));
13844        };
13845        let head = self.selections.newest::<usize>(cx).head();
13846        let buffer = self.buffer.read(cx);
13847        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13848            text_anchor
13849        } else {
13850            return Task::ready(Ok(Navigated::No));
13851        };
13852
13853        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13854            return Task::ready(Ok(Navigated::No));
13855        };
13856
13857        cx.spawn_in(window, async move |editor, cx| {
13858            let definitions = definitions.await?;
13859            let navigated = editor
13860                .update_in(cx, |editor, window, cx| {
13861                    editor.navigate_to_hover_links(
13862                        Some(kind),
13863                        definitions
13864                            .into_iter()
13865                            .filter(|location| {
13866                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13867                            })
13868                            .map(HoverLink::Text)
13869                            .collect::<Vec<_>>(),
13870                        split,
13871                        window,
13872                        cx,
13873                    )
13874                })?
13875                .await?;
13876            anyhow::Ok(navigated)
13877        })
13878    }
13879
13880    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13881        let selection = self.selections.newest_anchor();
13882        let head = selection.head();
13883        let tail = selection.tail();
13884
13885        let Some((buffer, start_position)) =
13886            self.buffer.read(cx).text_anchor_for_position(head, cx)
13887        else {
13888            return;
13889        };
13890
13891        let end_position = if head != tail {
13892            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13893                return;
13894            };
13895            Some(pos)
13896        } else {
13897            None
13898        };
13899
13900        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13901            let url = if let Some(end_pos) = end_position {
13902                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13903            } else {
13904                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13905            };
13906
13907            if let Some(url) = url {
13908                editor.update(cx, |_, cx| {
13909                    cx.open_url(&url);
13910                })
13911            } else {
13912                Ok(())
13913            }
13914        });
13915
13916        url_finder.detach();
13917    }
13918
13919    pub fn open_selected_filename(
13920        &mut self,
13921        _: &OpenSelectedFilename,
13922        window: &mut Window,
13923        cx: &mut Context<Self>,
13924    ) {
13925        let Some(workspace) = self.workspace() else {
13926            return;
13927        };
13928
13929        let position = self.selections.newest_anchor().head();
13930
13931        let Some((buffer, buffer_position)) =
13932            self.buffer.read(cx).text_anchor_for_position(position, cx)
13933        else {
13934            return;
13935        };
13936
13937        let project = self.project.clone();
13938
13939        cx.spawn_in(window, async move |_, cx| {
13940            let result = find_file(&buffer, project, buffer_position, cx).await;
13941
13942            if let Some((_, path)) = result {
13943                workspace
13944                    .update_in(cx, |workspace, window, cx| {
13945                        workspace.open_resolved_path(path, window, cx)
13946                    })?
13947                    .await?;
13948            }
13949            anyhow::Ok(())
13950        })
13951        .detach();
13952    }
13953
13954    pub(crate) fn navigate_to_hover_links(
13955        &mut self,
13956        kind: Option<GotoDefinitionKind>,
13957        mut definitions: Vec<HoverLink>,
13958        split: bool,
13959        window: &mut Window,
13960        cx: &mut Context<Editor>,
13961    ) -> Task<Result<Navigated>> {
13962        // If there is one definition, just open it directly
13963        if definitions.len() == 1 {
13964            let definition = definitions.pop().unwrap();
13965
13966            enum TargetTaskResult {
13967                Location(Option<Location>),
13968                AlreadyNavigated,
13969            }
13970
13971            let target_task = match definition {
13972                HoverLink::Text(link) => {
13973                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13974                }
13975                HoverLink::InlayHint(lsp_location, server_id) => {
13976                    let computation =
13977                        self.compute_target_location(lsp_location, server_id, window, cx);
13978                    cx.background_spawn(async move {
13979                        let location = computation.await?;
13980                        Ok(TargetTaskResult::Location(location))
13981                    })
13982                }
13983                HoverLink::Url(url) => {
13984                    cx.open_url(&url);
13985                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13986                }
13987                HoverLink::File(path) => {
13988                    if let Some(workspace) = self.workspace() {
13989                        cx.spawn_in(window, async move |_, cx| {
13990                            workspace
13991                                .update_in(cx, |workspace, window, cx| {
13992                                    workspace.open_resolved_path(path, window, cx)
13993                                })?
13994                                .await
13995                                .map(|_| TargetTaskResult::AlreadyNavigated)
13996                        })
13997                    } else {
13998                        Task::ready(Ok(TargetTaskResult::Location(None)))
13999                    }
14000                }
14001            };
14002            cx.spawn_in(window, async move |editor, cx| {
14003                let target = match target_task.await.context("target resolution task")? {
14004                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14005                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14006                    TargetTaskResult::Location(Some(target)) => target,
14007                };
14008
14009                editor.update_in(cx, |editor, window, cx| {
14010                    let Some(workspace) = editor.workspace() else {
14011                        return Navigated::No;
14012                    };
14013                    let pane = workspace.read(cx).active_pane().clone();
14014
14015                    let range = target.range.to_point(target.buffer.read(cx));
14016                    let range = editor.range_for_match(&range);
14017                    let range = collapse_multiline_range(range);
14018
14019                    if !split
14020                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14021                    {
14022                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14023                    } else {
14024                        window.defer(cx, move |window, cx| {
14025                            let target_editor: Entity<Self> =
14026                                workspace.update(cx, |workspace, cx| {
14027                                    let pane = if split {
14028                                        workspace.adjacent_pane(window, cx)
14029                                    } else {
14030                                        workspace.active_pane().clone()
14031                                    };
14032
14033                                    workspace.open_project_item(
14034                                        pane,
14035                                        target.buffer.clone(),
14036                                        true,
14037                                        true,
14038                                        window,
14039                                        cx,
14040                                    )
14041                                });
14042                            target_editor.update(cx, |target_editor, cx| {
14043                                // When selecting a definition in a different buffer, disable the nav history
14044                                // to avoid creating a history entry at the previous cursor location.
14045                                pane.update(cx, |pane, _| pane.disable_history());
14046                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14047                                pane.update(cx, |pane, _| pane.enable_history());
14048                            });
14049                        });
14050                    }
14051                    Navigated::Yes
14052                })
14053            })
14054        } else if !definitions.is_empty() {
14055            cx.spawn_in(window, async move |editor, cx| {
14056                let (title, location_tasks, workspace) = editor
14057                    .update_in(cx, |editor, window, cx| {
14058                        let tab_kind = match kind {
14059                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14060                            _ => "Definitions",
14061                        };
14062                        let title = definitions
14063                            .iter()
14064                            .find_map(|definition| match definition {
14065                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14066                                    let buffer = origin.buffer.read(cx);
14067                                    format!(
14068                                        "{} for {}",
14069                                        tab_kind,
14070                                        buffer
14071                                            .text_for_range(origin.range.clone())
14072                                            .collect::<String>()
14073                                    )
14074                                }),
14075                                HoverLink::InlayHint(_, _) => None,
14076                                HoverLink::Url(_) => None,
14077                                HoverLink::File(_) => None,
14078                            })
14079                            .unwrap_or(tab_kind.to_string());
14080                        let location_tasks = definitions
14081                            .into_iter()
14082                            .map(|definition| match definition {
14083                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14084                                HoverLink::InlayHint(lsp_location, server_id) => editor
14085                                    .compute_target_location(lsp_location, server_id, window, cx),
14086                                HoverLink::Url(_) => Task::ready(Ok(None)),
14087                                HoverLink::File(_) => Task::ready(Ok(None)),
14088                            })
14089                            .collect::<Vec<_>>();
14090                        (title, location_tasks, editor.workspace().clone())
14091                    })
14092                    .context("location tasks preparation")?;
14093
14094                let locations = future::join_all(location_tasks)
14095                    .await
14096                    .into_iter()
14097                    .filter_map(|location| location.transpose())
14098                    .collect::<Result<_>>()
14099                    .context("location tasks")?;
14100
14101                let Some(workspace) = workspace else {
14102                    return Ok(Navigated::No);
14103                };
14104                let opened = workspace
14105                    .update_in(cx, |workspace, window, cx| {
14106                        Self::open_locations_in_multibuffer(
14107                            workspace,
14108                            locations,
14109                            title,
14110                            split,
14111                            MultibufferSelectionMode::First,
14112                            window,
14113                            cx,
14114                        )
14115                    })
14116                    .ok();
14117
14118                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14119            })
14120        } else {
14121            Task::ready(Ok(Navigated::No))
14122        }
14123    }
14124
14125    fn compute_target_location(
14126        &self,
14127        lsp_location: lsp::Location,
14128        server_id: LanguageServerId,
14129        window: &mut Window,
14130        cx: &mut Context<Self>,
14131    ) -> Task<anyhow::Result<Option<Location>>> {
14132        let Some(project) = self.project.clone() else {
14133            return Task::ready(Ok(None));
14134        };
14135
14136        cx.spawn_in(window, async move |editor, cx| {
14137            let location_task = editor.update(cx, |_, cx| {
14138                project.update(cx, |project, cx| {
14139                    let language_server_name = project
14140                        .language_server_statuses(cx)
14141                        .find(|(id, _)| server_id == *id)
14142                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14143                    language_server_name.map(|language_server_name| {
14144                        project.open_local_buffer_via_lsp(
14145                            lsp_location.uri.clone(),
14146                            server_id,
14147                            language_server_name,
14148                            cx,
14149                        )
14150                    })
14151                })
14152            })?;
14153            let location = match location_task {
14154                Some(task) => Some({
14155                    let target_buffer_handle = task.await.context("open local buffer")?;
14156                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14157                        let target_start = target_buffer
14158                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14159                        let target_end = target_buffer
14160                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14161                        target_buffer.anchor_after(target_start)
14162                            ..target_buffer.anchor_before(target_end)
14163                    })?;
14164                    Location {
14165                        buffer: target_buffer_handle,
14166                        range,
14167                    }
14168                }),
14169                None => None,
14170            };
14171            Ok(location)
14172        })
14173    }
14174
14175    pub fn find_all_references(
14176        &mut self,
14177        _: &FindAllReferences,
14178        window: &mut Window,
14179        cx: &mut Context<Self>,
14180    ) -> Option<Task<Result<Navigated>>> {
14181        let selection = self.selections.newest::<usize>(cx);
14182        let multi_buffer = self.buffer.read(cx);
14183        let head = selection.head();
14184
14185        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14186        let head_anchor = multi_buffer_snapshot.anchor_at(
14187            head,
14188            if head < selection.tail() {
14189                Bias::Right
14190            } else {
14191                Bias::Left
14192            },
14193        );
14194
14195        match self
14196            .find_all_references_task_sources
14197            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14198        {
14199            Ok(_) => {
14200                log::info!(
14201                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14202                );
14203                return None;
14204            }
14205            Err(i) => {
14206                self.find_all_references_task_sources.insert(i, head_anchor);
14207            }
14208        }
14209
14210        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14211        let workspace = self.workspace()?;
14212        let project = workspace.read(cx).project().clone();
14213        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14214        Some(cx.spawn_in(window, async move |editor, cx| {
14215            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14216                if let Ok(i) = editor
14217                    .find_all_references_task_sources
14218                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14219                {
14220                    editor.find_all_references_task_sources.remove(i);
14221                }
14222            });
14223
14224            let locations = references.await?;
14225            if locations.is_empty() {
14226                return anyhow::Ok(Navigated::No);
14227            }
14228
14229            workspace.update_in(cx, |workspace, window, cx| {
14230                let title = locations
14231                    .first()
14232                    .as_ref()
14233                    .map(|location| {
14234                        let buffer = location.buffer.read(cx);
14235                        format!(
14236                            "References to `{}`",
14237                            buffer
14238                                .text_for_range(location.range.clone())
14239                                .collect::<String>()
14240                        )
14241                    })
14242                    .unwrap();
14243                Self::open_locations_in_multibuffer(
14244                    workspace,
14245                    locations,
14246                    title,
14247                    false,
14248                    MultibufferSelectionMode::First,
14249                    window,
14250                    cx,
14251                );
14252                Navigated::Yes
14253            })
14254        }))
14255    }
14256
14257    /// Opens a multibuffer with the given project locations in it
14258    pub fn open_locations_in_multibuffer(
14259        workspace: &mut Workspace,
14260        mut locations: Vec<Location>,
14261        title: String,
14262        split: bool,
14263        multibuffer_selection_mode: MultibufferSelectionMode,
14264        window: &mut Window,
14265        cx: &mut Context<Workspace>,
14266    ) {
14267        // If there are multiple definitions, open them in a multibuffer
14268        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14269        let mut locations = locations.into_iter().peekable();
14270        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14271        let capability = workspace.project().read(cx).capability();
14272
14273        let excerpt_buffer = cx.new(|cx| {
14274            let mut multibuffer = MultiBuffer::new(capability);
14275            while let Some(location) = locations.next() {
14276                let buffer = location.buffer.read(cx);
14277                let mut ranges_for_buffer = Vec::new();
14278                let range = location.range.to_point(buffer);
14279                ranges_for_buffer.push(range.clone());
14280
14281                while let Some(next_location) = locations.peek() {
14282                    if next_location.buffer == location.buffer {
14283                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14284                        locations.next();
14285                    } else {
14286                        break;
14287                    }
14288                }
14289
14290                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14291                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14292                    PathKey::for_buffer(&location.buffer, cx),
14293                    location.buffer.clone(),
14294                    ranges_for_buffer,
14295                    DEFAULT_MULTIBUFFER_CONTEXT,
14296                    cx,
14297                );
14298                ranges.extend(new_ranges)
14299            }
14300
14301            multibuffer.with_title(title)
14302        });
14303
14304        let editor = cx.new(|cx| {
14305            Editor::for_multibuffer(
14306                excerpt_buffer,
14307                Some(workspace.project().clone()),
14308                window,
14309                cx,
14310            )
14311        });
14312        editor.update(cx, |editor, cx| {
14313            match multibuffer_selection_mode {
14314                MultibufferSelectionMode::First => {
14315                    if let Some(first_range) = ranges.first() {
14316                        editor.change_selections(None, window, cx, |selections| {
14317                            selections.clear_disjoint();
14318                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14319                        });
14320                    }
14321                    editor.highlight_background::<Self>(
14322                        &ranges,
14323                        |theme| theme.editor_highlighted_line_background,
14324                        cx,
14325                    );
14326                }
14327                MultibufferSelectionMode::All => {
14328                    editor.change_selections(None, window, cx, |selections| {
14329                        selections.clear_disjoint();
14330                        selections.select_anchor_ranges(ranges);
14331                    });
14332                }
14333            }
14334            editor.register_buffers_with_language_servers(cx);
14335        });
14336
14337        let item = Box::new(editor);
14338        let item_id = item.item_id();
14339
14340        if split {
14341            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14342        } else {
14343            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14344                let (preview_item_id, preview_item_idx) =
14345                    workspace.active_pane().update(cx, |pane, _| {
14346                        (pane.preview_item_id(), pane.preview_item_idx())
14347                    });
14348
14349                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14350
14351                if let Some(preview_item_id) = preview_item_id {
14352                    workspace.active_pane().update(cx, |pane, cx| {
14353                        pane.remove_item(preview_item_id, false, false, window, cx);
14354                    });
14355                }
14356            } else {
14357                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14358            }
14359        }
14360        workspace.active_pane().update(cx, |pane, cx| {
14361            pane.set_preview_item_id(Some(item_id), cx);
14362        });
14363    }
14364
14365    pub fn rename(
14366        &mut self,
14367        _: &Rename,
14368        window: &mut Window,
14369        cx: &mut Context<Self>,
14370    ) -> Option<Task<Result<()>>> {
14371        use language::ToOffset as _;
14372
14373        let provider = self.semantics_provider.clone()?;
14374        let selection = self.selections.newest_anchor().clone();
14375        let (cursor_buffer, cursor_buffer_position) = self
14376            .buffer
14377            .read(cx)
14378            .text_anchor_for_position(selection.head(), cx)?;
14379        let (tail_buffer, cursor_buffer_position_end) = self
14380            .buffer
14381            .read(cx)
14382            .text_anchor_for_position(selection.tail(), cx)?;
14383        if tail_buffer != cursor_buffer {
14384            return None;
14385        }
14386
14387        let snapshot = cursor_buffer.read(cx).snapshot();
14388        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14389        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14390        let prepare_rename = provider
14391            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14392            .unwrap_or_else(|| Task::ready(Ok(None)));
14393        drop(snapshot);
14394
14395        Some(cx.spawn_in(window, async move |this, cx| {
14396            let rename_range = if let Some(range) = prepare_rename.await? {
14397                Some(range)
14398            } else {
14399                this.update(cx, |this, cx| {
14400                    let buffer = this.buffer.read(cx).snapshot(cx);
14401                    let mut buffer_highlights = this
14402                        .document_highlights_for_position(selection.head(), &buffer)
14403                        .filter(|highlight| {
14404                            highlight.start.excerpt_id == selection.head().excerpt_id
14405                                && highlight.end.excerpt_id == selection.head().excerpt_id
14406                        });
14407                    buffer_highlights
14408                        .next()
14409                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14410                })?
14411            };
14412            if let Some(rename_range) = rename_range {
14413                this.update_in(cx, |this, window, cx| {
14414                    let snapshot = cursor_buffer.read(cx).snapshot();
14415                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14416                    let cursor_offset_in_rename_range =
14417                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14418                    let cursor_offset_in_rename_range_end =
14419                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14420
14421                    this.take_rename(false, window, cx);
14422                    let buffer = this.buffer.read(cx).read(cx);
14423                    let cursor_offset = selection.head().to_offset(&buffer);
14424                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14425                    let rename_end = rename_start + rename_buffer_range.len();
14426                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14427                    let mut old_highlight_id = None;
14428                    let old_name: Arc<str> = buffer
14429                        .chunks(rename_start..rename_end, true)
14430                        .map(|chunk| {
14431                            if old_highlight_id.is_none() {
14432                                old_highlight_id = chunk.syntax_highlight_id;
14433                            }
14434                            chunk.text
14435                        })
14436                        .collect::<String>()
14437                        .into();
14438
14439                    drop(buffer);
14440
14441                    // Position the selection in the rename editor so that it matches the current selection.
14442                    this.show_local_selections = false;
14443                    let rename_editor = cx.new(|cx| {
14444                        let mut editor = Editor::single_line(window, cx);
14445                        editor.buffer.update(cx, |buffer, cx| {
14446                            buffer.edit([(0..0, old_name.clone())], None, cx)
14447                        });
14448                        let rename_selection_range = match cursor_offset_in_rename_range
14449                            .cmp(&cursor_offset_in_rename_range_end)
14450                        {
14451                            Ordering::Equal => {
14452                                editor.select_all(&SelectAll, window, cx);
14453                                return editor;
14454                            }
14455                            Ordering::Less => {
14456                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14457                            }
14458                            Ordering::Greater => {
14459                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14460                            }
14461                        };
14462                        if rename_selection_range.end > old_name.len() {
14463                            editor.select_all(&SelectAll, window, cx);
14464                        } else {
14465                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14466                                s.select_ranges([rename_selection_range]);
14467                            });
14468                        }
14469                        editor
14470                    });
14471                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14472                        if e == &EditorEvent::Focused {
14473                            cx.emit(EditorEvent::FocusedIn)
14474                        }
14475                    })
14476                    .detach();
14477
14478                    let write_highlights =
14479                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14480                    let read_highlights =
14481                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14482                    let ranges = write_highlights
14483                        .iter()
14484                        .flat_map(|(_, ranges)| ranges.iter())
14485                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14486                        .cloned()
14487                        .collect();
14488
14489                    this.highlight_text::<Rename>(
14490                        ranges,
14491                        HighlightStyle {
14492                            fade_out: Some(0.6),
14493                            ..Default::default()
14494                        },
14495                        cx,
14496                    );
14497                    let rename_focus_handle = rename_editor.focus_handle(cx);
14498                    window.focus(&rename_focus_handle);
14499                    let block_id = this.insert_blocks(
14500                        [BlockProperties {
14501                            style: BlockStyle::Flex,
14502                            placement: BlockPlacement::Below(range.start),
14503                            height: Some(1),
14504                            render: Arc::new({
14505                                let rename_editor = rename_editor.clone();
14506                                move |cx: &mut BlockContext| {
14507                                    let mut text_style = cx.editor_style.text.clone();
14508                                    if let Some(highlight_style) = old_highlight_id
14509                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14510                                    {
14511                                        text_style = text_style.highlight(highlight_style);
14512                                    }
14513                                    div()
14514                                        .block_mouse_down()
14515                                        .pl(cx.anchor_x)
14516                                        .child(EditorElement::new(
14517                                            &rename_editor,
14518                                            EditorStyle {
14519                                                background: cx.theme().system().transparent,
14520                                                local_player: cx.editor_style.local_player,
14521                                                text: text_style,
14522                                                scrollbar_width: cx.editor_style.scrollbar_width,
14523                                                syntax: cx.editor_style.syntax.clone(),
14524                                                status: cx.editor_style.status.clone(),
14525                                                inlay_hints_style: HighlightStyle {
14526                                                    font_weight: Some(FontWeight::BOLD),
14527                                                    ..make_inlay_hints_style(cx.app)
14528                                                },
14529                                                inline_completion_styles: make_suggestion_styles(
14530                                                    cx.app,
14531                                                ),
14532                                                ..EditorStyle::default()
14533                                            },
14534                                        ))
14535                                        .into_any_element()
14536                                }
14537                            }),
14538                            priority: 0,
14539                        }],
14540                        Some(Autoscroll::fit()),
14541                        cx,
14542                    )[0];
14543                    this.pending_rename = Some(RenameState {
14544                        range,
14545                        old_name,
14546                        editor: rename_editor,
14547                        block_id,
14548                    });
14549                })?;
14550            }
14551
14552            Ok(())
14553        }))
14554    }
14555
14556    pub fn confirm_rename(
14557        &mut self,
14558        _: &ConfirmRename,
14559        window: &mut Window,
14560        cx: &mut Context<Self>,
14561    ) -> Option<Task<Result<()>>> {
14562        let rename = self.take_rename(false, window, cx)?;
14563        let workspace = self.workspace()?.downgrade();
14564        let (buffer, start) = self
14565            .buffer
14566            .read(cx)
14567            .text_anchor_for_position(rename.range.start, cx)?;
14568        let (end_buffer, _) = self
14569            .buffer
14570            .read(cx)
14571            .text_anchor_for_position(rename.range.end, cx)?;
14572        if buffer != end_buffer {
14573            return None;
14574        }
14575
14576        let old_name = rename.old_name;
14577        let new_name = rename.editor.read(cx).text(cx);
14578
14579        let rename = self.semantics_provider.as_ref()?.perform_rename(
14580            &buffer,
14581            start,
14582            new_name.clone(),
14583            cx,
14584        )?;
14585
14586        Some(cx.spawn_in(window, async move |editor, cx| {
14587            let project_transaction = rename.await?;
14588            Self::open_project_transaction(
14589                &editor,
14590                workspace,
14591                project_transaction,
14592                format!("Rename: {}{}", old_name, new_name),
14593                cx,
14594            )
14595            .await?;
14596
14597            editor.update(cx, |editor, cx| {
14598                editor.refresh_document_highlights(cx);
14599            })?;
14600            Ok(())
14601        }))
14602    }
14603
14604    fn take_rename(
14605        &mut self,
14606        moving_cursor: bool,
14607        window: &mut Window,
14608        cx: &mut Context<Self>,
14609    ) -> Option<RenameState> {
14610        let rename = self.pending_rename.take()?;
14611        if rename.editor.focus_handle(cx).is_focused(window) {
14612            window.focus(&self.focus_handle);
14613        }
14614
14615        self.remove_blocks(
14616            [rename.block_id].into_iter().collect(),
14617            Some(Autoscroll::fit()),
14618            cx,
14619        );
14620        self.clear_highlights::<Rename>(cx);
14621        self.show_local_selections = true;
14622
14623        if moving_cursor {
14624            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14625                editor.selections.newest::<usize>(cx).head()
14626            });
14627
14628            // Update the selection to match the position of the selection inside
14629            // the rename editor.
14630            let snapshot = self.buffer.read(cx).read(cx);
14631            let rename_range = rename.range.to_offset(&snapshot);
14632            let cursor_in_editor = snapshot
14633                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14634                .min(rename_range.end);
14635            drop(snapshot);
14636
14637            self.change_selections(None, window, cx, |s| {
14638                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14639            });
14640        } else {
14641            self.refresh_document_highlights(cx);
14642        }
14643
14644        Some(rename)
14645    }
14646
14647    pub fn pending_rename(&self) -> Option<&RenameState> {
14648        self.pending_rename.as_ref()
14649    }
14650
14651    fn format(
14652        &mut self,
14653        _: &Format,
14654        window: &mut Window,
14655        cx: &mut Context<Self>,
14656    ) -> Option<Task<Result<()>>> {
14657        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14658
14659        let project = match &self.project {
14660            Some(project) => project.clone(),
14661            None => return None,
14662        };
14663
14664        Some(self.perform_format(
14665            project,
14666            FormatTrigger::Manual,
14667            FormatTarget::Buffers,
14668            window,
14669            cx,
14670        ))
14671    }
14672
14673    fn format_selections(
14674        &mut self,
14675        _: &FormatSelections,
14676        window: &mut Window,
14677        cx: &mut Context<Self>,
14678    ) -> Option<Task<Result<()>>> {
14679        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14680
14681        let project = match &self.project {
14682            Some(project) => project.clone(),
14683            None => return None,
14684        };
14685
14686        let ranges = self
14687            .selections
14688            .all_adjusted(cx)
14689            .into_iter()
14690            .map(|selection| selection.range())
14691            .collect_vec();
14692
14693        Some(self.perform_format(
14694            project,
14695            FormatTrigger::Manual,
14696            FormatTarget::Ranges(ranges),
14697            window,
14698            cx,
14699        ))
14700    }
14701
14702    fn perform_format(
14703        &mut self,
14704        project: Entity<Project>,
14705        trigger: FormatTrigger,
14706        target: FormatTarget,
14707        window: &mut Window,
14708        cx: &mut Context<Self>,
14709    ) -> Task<Result<()>> {
14710        let buffer = self.buffer.clone();
14711        let (buffers, target) = match target {
14712            FormatTarget::Buffers => {
14713                let mut buffers = buffer.read(cx).all_buffers();
14714                if trigger == FormatTrigger::Save {
14715                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14716                }
14717                (buffers, LspFormatTarget::Buffers)
14718            }
14719            FormatTarget::Ranges(selection_ranges) => {
14720                let multi_buffer = buffer.read(cx);
14721                let snapshot = multi_buffer.read(cx);
14722                let mut buffers = HashSet::default();
14723                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14724                    BTreeMap::new();
14725                for selection_range in selection_ranges {
14726                    for (buffer, buffer_range, _) in
14727                        snapshot.range_to_buffer_ranges(selection_range)
14728                    {
14729                        let buffer_id = buffer.remote_id();
14730                        let start = buffer.anchor_before(buffer_range.start);
14731                        let end = buffer.anchor_after(buffer_range.end);
14732                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14733                        buffer_id_to_ranges
14734                            .entry(buffer_id)
14735                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14736                            .or_insert_with(|| vec![start..end]);
14737                    }
14738                }
14739                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14740            }
14741        };
14742
14743        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14744        let selections_prev = transaction_id_prev
14745            .and_then(|transaction_id_prev| {
14746                // default to selections as they were after the last edit, if we have them,
14747                // instead of how they are now.
14748                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14749                // will take you back to where you made the last edit, instead of staying where you scrolled
14750                self.selection_history
14751                    .transaction(transaction_id_prev)
14752                    .map(|t| t.0.clone())
14753            })
14754            .unwrap_or_else(|| {
14755                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14756                self.selections.disjoint_anchors()
14757            });
14758
14759        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14760        let format = project.update(cx, |project, cx| {
14761            project.format(buffers, target, true, trigger, cx)
14762        });
14763
14764        cx.spawn_in(window, async move |editor, cx| {
14765            let transaction = futures::select_biased! {
14766                transaction = format.log_err().fuse() => transaction,
14767                () = timeout => {
14768                    log::warn!("timed out waiting for formatting");
14769                    None
14770                }
14771            };
14772
14773            buffer
14774                .update(cx, |buffer, cx| {
14775                    if let Some(transaction) = transaction {
14776                        if !buffer.is_singleton() {
14777                            buffer.push_transaction(&transaction.0, cx);
14778                        }
14779                    }
14780                    cx.notify();
14781                })
14782                .ok();
14783
14784            if let Some(transaction_id_now) =
14785                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14786            {
14787                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14788                if has_new_transaction {
14789                    _ = editor.update(cx, |editor, _| {
14790                        editor
14791                            .selection_history
14792                            .insert_transaction(transaction_id_now, selections_prev);
14793                    });
14794                }
14795            }
14796
14797            Ok(())
14798        })
14799    }
14800
14801    fn organize_imports(
14802        &mut self,
14803        _: &OrganizeImports,
14804        window: &mut Window,
14805        cx: &mut Context<Self>,
14806    ) -> Option<Task<Result<()>>> {
14807        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14808        let project = match &self.project {
14809            Some(project) => project.clone(),
14810            None => return None,
14811        };
14812        Some(self.perform_code_action_kind(
14813            project,
14814            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14815            window,
14816            cx,
14817        ))
14818    }
14819
14820    fn perform_code_action_kind(
14821        &mut self,
14822        project: Entity<Project>,
14823        kind: CodeActionKind,
14824        window: &mut Window,
14825        cx: &mut Context<Self>,
14826    ) -> Task<Result<()>> {
14827        let buffer = self.buffer.clone();
14828        let buffers = buffer.read(cx).all_buffers();
14829        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14830        let apply_action = project.update(cx, |project, cx| {
14831            project.apply_code_action_kind(buffers, kind, true, cx)
14832        });
14833        cx.spawn_in(window, async move |_, cx| {
14834            let transaction = futures::select_biased! {
14835                () = timeout => {
14836                    log::warn!("timed out waiting for executing code action");
14837                    None
14838                }
14839                transaction = apply_action.log_err().fuse() => transaction,
14840            };
14841            buffer
14842                .update(cx, |buffer, cx| {
14843                    // check if we need this
14844                    if let Some(transaction) = transaction {
14845                        if !buffer.is_singleton() {
14846                            buffer.push_transaction(&transaction.0, cx);
14847                        }
14848                    }
14849                    cx.notify();
14850                })
14851                .ok();
14852            Ok(())
14853        })
14854    }
14855
14856    fn restart_language_server(
14857        &mut self,
14858        _: &RestartLanguageServer,
14859        _: &mut Window,
14860        cx: &mut Context<Self>,
14861    ) {
14862        if let Some(project) = self.project.clone() {
14863            self.buffer.update(cx, |multi_buffer, cx| {
14864                project.update(cx, |project, cx| {
14865                    project.restart_language_servers_for_buffers(
14866                        multi_buffer.all_buffers().into_iter().collect(),
14867                        cx,
14868                    );
14869                });
14870            })
14871        }
14872    }
14873
14874    fn stop_language_server(
14875        &mut self,
14876        _: &StopLanguageServer,
14877        _: &mut Window,
14878        cx: &mut Context<Self>,
14879    ) {
14880        if let Some(project) = self.project.clone() {
14881            self.buffer.update(cx, |multi_buffer, cx| {
14882                project.update(cx, |project, cx| {
14883                    project.stop_language_servers_for_buffers(
14884                        multi_buffer.all_buffers().into_iter().collect(),
14885                        cx,
14886                    );
14887                    cx.emit(project::Event::RefreshInlayHints);
14888                });
14889            });
14890        }
14891    }
14892
14893    fn cancel_language_server_work(
14894        workspace: &mut Workspace,
14895        _: &actions::CancelLanguageServerWork,
14896        _: &mut Window,
14897        cx: &mut Context<Workspace>,
14898    ) {
14899        let project = workspace.project();
14900        let buffers = workspace
14901            .active_item(cx)
14902            .and_then(|item| item.act_as::<Editor>(cx))
14903            .map_or(HashSet::default(), |editor| {
14904                editor.read(cx).buffer.read(cx).all_buffers()
14905            });
14906        project.update(cx, |project, cx| {
14907            project.cancel_language_server_work_for_buffers(buffers, cx);
14908        });
14909    }
14910
14911    fn show_character_palette(
14912        &mut self,
14913        _: &ShowCharacterPalette,
14914        window: &mut Window,
14915        _: &mut Context<Self>,
14916    ) {
14917        window.show_character_palette();
14918    }
14919
14920    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14921        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14922            let buffer = self.buffer.read(cx).snapshot(cx);
14923            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14924            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14925            let is_valid = buffer
14926                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14927                .any(|entry| {
14928                    entry.diagnostic.is_primary
14929                        && !entry.range.is_empty()
14930                        && entry.range.start == primary_range_start
14931                        && entry.diagnostic.message == active_diagnostics.active_message
14932                });
14933
14934            if !is_valid {
14935                self.dismiss_diagnostics(cx);
14936            }
14937        }
14938    }
14939
14940    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14941        match &self.active_diagnostics {
14942            ActiveDiagnostic::Group(group) => Some(group),
14943            _ => None,
14944        }
14945    }
14946
14947    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14948        self.dismiss_diagnostics(cx);
14949        self.active_diagnostics = ActiveDiagnostic::All;
14950    }
14951
14952    fn activate_diagnostics(
14953        &mut self,
14954        buffer_id: BufferId,
14955        diagnostic: DiagnosticEntry<usize>,
14956        window: &mut Window,
14957        cx: &mut Context<Self>,
14958    ) {
14959        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14960            return;
14961        }
14962        self.dismiss_diagnostics(cx);
14963        let snapshot = self.snapshot(window, cx);
14964        let buffer = self.buffer.read(cx).snapshot(cx);
14965        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
14966            return;
14967        };
14968
14969        let diagnostic_group = buffer
14970            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14971            .collect::<Vec<_>>();
14972
14973        let blocks =
14974            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
14975
14976        let blocks = self.display_map.update(cx, |display_map, cx| {
14977            display_map.insert_blocks(blocks, cx).into_iter().collect()
14978        });
14979        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14980            active_range: buffer.anchor_before(diagnostic.range.start)
14981                ..buffer.anchor_after(diagnostic.range.end),
14982            active_message: diagnostic.diagnostic.message.clone(),
14983            group_id: diagnostic.diagnostic.group_id,
14984            blocks,
14985        });
14986        cx.notify();
14987    }
14988
14989    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14990        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14991            return;
14992        };
14993
14994        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14995        if let ActiveDiagnostic::Group(group) = prev {
14996            self.display_map.update(cx, |display_map, cx| {
14997                display_map.remove_blocks(group.blocks, cx);
14998            });
14999            cx.notify();
15000        }
15001    }
15002
15003    /// Disable inline diagnostics rendering for this editor.
15004    pub fn disable_inline_diagnostics(&mut self) {
15005        self.inline_diagnostics_enabled = false;
15006        self.inline_diagnostics_update = Task::ready(());
15007        self.inline_diagnostics.clear();
15008    }
15009
15010    pub fn inline_diagnostics_enabled(&self) -> bool {
15011        self.inline_diagnostics_enabled
15012    }
15013
15014    pub fn show_inline_diagnostics(&self) -> bool {
15015        self.show_inline_diagnostics
15016    }
15017
15018    pub fn toggle_inline_diagnostics(
15019        &mut self,
15020        _: &ToggleInlineDiagnostics,
15021        window: &mut Window,
15022        cx: &mut Context<Editor>,
15023    ) {
15024        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15025        self.refresh_inline_diagnostics(false, window, cx);
15026    }
15027
15028    fn refresh_inline_diagnostics(
15029        &mut self,
15030        debounce: bool,
15031        window: &mut Window,
15032        cx: &mut Context<Self>,
15033    ) {
15034        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15035            self.inline_diagnostics_update = Task::ready(());
15036            self.inline_diagnostics.clear();
15037            return;
15038        }
15039
15040        let debounce_ms = ProjectSettings::get_global(cx)
15041            .diagnostics
15042            .inline
15043            .update_debounce_ms;
15044        let debounce = if debounce && debounce_ms > 0 {
15045            Some(Duration::from_millis(debounce_ms))
15046        } else {
15047            None
15048        };
15049        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15050            let editor = editor.upgrade().unwrap();
15051
15052            if let Some(debounce) = debounce {
15053                cx.background_executor().timer(debounce).await;
15054            }
15055            let Some(snapshot) = editor
15056                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15057                .ok()
15058            else {
15059                return;
15060            };
15061
15062            let new_inline_diagnostics = cx
15063                .background_spawn(async move {
15064                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15065                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15066                        let message = diagnostic_entry
15067                            .diagnostic
15068                            .message
15069                            .split_once('\n')
15070                            .map(|(line, _)| line)
15071                            .map(SharedString::new)
15072                            .unwrap_or_else(|| {
15073                                SharedString::from(diagnostic_entry.diagnostic.message)
15074                            });
15075                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15076                        let (Ok(i) | Err(i)) = inline_diagnostics
15077                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15078                        inline_diagnostics.insert(
15079                            i,
15080                            (
15081                                start_anchor,
15082                                InlineDiagnostic {
15083                                    message,
15084                                    group_id: diagnostic_entry.diagnostic.group_id,
15085                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15086                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15087                                    severity: diagnostic_entry.diagnostic.severity,
15088                                },
15089                            ),
15090                        );
15091                    }
15092                    inline_diagnostics
15093                })
15094                .await;
15095
15096            editor
15097                .update(cx, |editor, cx| {
15098                    editor.inline_diagnostics = new_inline_diagnostics;
15099                    cx.notify();
15100                })
15101                .ok();
15102        });
15103    }
15104
15105    pub fn set_selections_from_remote(
15106        &mut self,
15107        selections: Vec<Selection<Anchor>>,
15108        pending_selection: Option<Selection<Anchor>>,
15109        window: &mut Window,
15110        cx: &mut Context<Self>,
15111    ) {
15112        let old_cursor_position = self.selections.newest_anchor().head();
15113        self.selections.change_with(cx, |s| {
15114            s.select_anchors(selections);
15115            if let Some(pending_selection) = pending_selection {
15116                s.set_pending(pending_selection, SelectMode::Character);
15117            } else {
15118                s.clear_pending();
15119            }
15120        });
15121        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15122    }
15123
15124    fn push_to_selection_history(&mut self) {
15125        self.selection_history.push(SelectionHistoryEntry {
15126            selections: self.selections.disjoint_anchors(),
15127            select_next_state: self.select_next_state.clone(),
15128            select_prev_state: self.select_prev_state.clone(),
15129            add_selections_state: self.add_selections_state.clone(),
15130        });
15131    }
15132
15133    pub fn transact(
15134        &mut self,
15135        window: &mut Window,
15136        cx: &mut Context<Self>,
15137        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15138    ) -> Option<TransactionId> {
15139        self.start_transaction_at(Instant::now(), window, cx);
15140        update(self, window, cx);
15141        self.end_transaction_at(Instant::now(), cx)
15142    }
15143
15144    pub fn start_transaction_at(
15145        &mut self,
15146        now: Instant,
15147        window: &mut Window,
15148        cx: &mut Context<Self>,
15149    ) {
15150        self.end_selection(window, cx);
15151        if let Some(tx_id) = self
15152            .buffer
15153            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15154        {
15155            self.selection_history
15156                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15157            cx.emit(EditorEvent::TransactionBegun {
15158                transaction_id: tx_id,
15159            })
15160        }
15161    }
15162
15163    pub fn end_transaction_at(
15164        &mut self,
15165        now: Instant,
15166        cx: &mut Context<Self>,
15167    ) -> Option<TransactionId> {
15168        if let Some(transaction_id) = self
15169            .buffer
15170            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15171        {
15172            if let Some((_, end_selections)) =
15173                self.selection_history.transaction_mut(transaction_id)
15174            {
15175                *end_selections = Some(self.selections.disjoint_anchors());
15176            } else {
15177                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15178            }
15179
15180            cx.emit(EditorEvent::Edited { transaction_id });
15181            Some(transaction_id)
15182        } else {
15183            None
15184        }
15185    }
15186
15187    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15188        if self.selection_mark_mode {
15189            self.change_selections(None, window, cx, |s| {
15190                s.move_with(|_, sel| {
15191                    sel.collapse_to(sel.head(), SelectionGoal::None);
15192                });
15193            })
15194        }
15195        self.selection_mark_mode = true;
15196        cx.notify();
15197    }
15198
15199    pub fn swap_selection_ends(
15200        &mut self,
15201        _: &actions::SwapSelectionEnds,
15202        window: &mut Window,
15203        cx: &mut Context<Self>,
15204    ) {
15205        self.change_selections(None, window, cx, |s| {
15206            s.move_with(|_, sel| {
15207                if sel.start != sel.end {
15208                    sel.reversed = !sel.reversed
15209                }
15210            });
15211        });
15212        self.request_autoscroll(Autoscroll::newest(), cx);
15213        cx.notify();
15214    }
15215
15216    pub fn toggle_fold(
15217        &mut self,
15218        _: &actions::ToggleFold,
15219        window: &mut Window,
15220        cx: &mut Context<Self>,
15221    ) {
15222        if self.is_singleton(cx) {
15223            let selection = self.selections.newest::<Point>(cx);
15224
15225            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15226            let range = if selection.is_empty() {
15227                let point = selection.head().to_display_point(&display_map);
15228                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15229                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15230                    .to_point(&display_map);
15231                start..end
15232            } else {
15233                selection.range()
15234            };
15235            if display_map.folds_in_range(range).next().is_some() {
15236                self.unfold_lines(&Default::default(), window, cx)
15237            } else {
15238                self.fold(&Default::default(), window, cx)
15239            }
15240        } else {
15241            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15242            let buffer_ids: HashSet<_> = self
15243                .selections
15244                .disjoint_anchor_ranges()
15245                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15246                .collect();
15247
15248            let should_unfold = buffer_ids
15249                .iter()
15250                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15251
15252            for buffer_id in buffer_ids {
15253                if should_unfold {
15254                    self.unfold_buffer(buffer_id, cx);
15255                } else {
15256                    self.fold_buffer(buffer_id, cx);
15257                }
15258            }
15259        }
15260    }
15261
15262    pub fn toggle_fold_recursive(
15263        &mut self,
15264        _: &actions::ToggleFoldRecursive,
15265        window: &mut Window,
15266        cx: &mut Context<Self>,
15267    ) {
15268        let selection = self.selections.newest::<Point>(cx);
15269
15270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15271        let range = if selection.is_empty() {
15272            let point = selection.head().to_display_point(&display_map);
15273            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15274            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15275                .to_point(&display_map);
15276            start..end
15277        } else {
15278            selection.range()
15279        };
15280        if display_map.folds_in_range(range).next().is_some() {
15281            self.unfold_recursive(&Default::default(), window, cx)
15282        } else {
15283            self.fold_recursive(&Default::default(), window, cx)
15284        }
15285    }
15286
15287    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15288        if self.is_singleton(cx) {
15289            let mut to_fold = Vec::new();
15290            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15291            let selections = self.selections.all_adjusted(cx);
15292
15293            for selection in selections {
15294                let range = selection.range().sorted();
15295                let buffer_start_row = range.start.row;
15296
15297                if range.start.row != range.end.row {
15298                    let mut found = false;
15299                    let mut row = range.start.row;
15300                    while row <= range.end.row {
15301                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15302                        {
15303                            found = true;
15304                            row = crease.range().end.row + 1;
15305                            to_fold.push(crease);
15306                        } else {
15307                            row += 1
15308                        }
15309                    }
15310                    if found {
15311                        continue;
15312                    }
15313                }
15314
15315                for row in (0..=range.start.row).rev() {
15316                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15317                        if crease.range().end.row >= buffer_start_row {
15318                            to_fold.push(crease);
15319                            if row <= range.start.row {
15320                                break;
15321                            }
15322                        }
15323                    }
15324                }
15325            }
15326
15327            self.fold_creases(to_fold, true, window, cx);
15328        } else {
15329            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15330            let buffer_ids = self
15331                .selections
15332                .disjoint_anchor_ranges()
15333                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15334                .collect::<HashSet<_>>();
15335            for buffer_id in buffer_ids {
15336                self.fold_buffer(buffer_id, cx);
15337            }
15338        }
15339    }
15340
15341    fn fold_at_level(
15342        &mut self,
15343        fold_at: &FoldAtLevel,
15344        window: &mut Window,
15345        cx: &mut Context<Self>,
15346    ) {
15347        if !self.buffer.read(cx).is_singleton() {
15348            return;
15349        }
15350
15351        let fold_at_level = fold_at.0;
15352        let snapshot = self.buffer.read(cx).snapshot(cx);
15353        let mut to_fold = Vec::new();
15354        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15355
15356        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15357            while start_row < end_row {
15358                match self
15359                    .snapshot(window, cx)
15360                    .crease_for_buffer_row(MultiBufferRow(start_row))
15361                {
15362                    Some(crease) => {
15363                        let nested_start_row = crease.range().start.row + 1;
15364                        let nested_end_row = crease.range().end.row;
15365
15366                        if current_level < fold_at_level {
15367                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15368                        } else if current_level == fold_at_level {
15369                            to_fold.push(crease);
15370                        }
15371
15372                        start_row = nested_end_row + 1;
15373                    }
15374                    None => start_row += 1,
15375                }
15376            }
15377        }
15378
15379        self.fold_creases(to_fold, true, window, cx);
15380    }
15381
15382    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15383        if self.buffer.read(cx).is_singleton() {
15384            let mut fold_ranges = Vec::new();
15385            let snapshot = self.buffer.read(cx).snapshot(cx);
15386
15387            for row in 0..snapshot.max_row().0 {
15388                if let Some(foldable_range) = self
15389                    .snapshot(window, cx)
15390                    .crease_for_buffer_row(MultiBufferRow(row))
15391                {
15392                    fold_ranges.push(foldable_range);
15393                }
15394            }
15395
15396            self.fold_creases(fold_ranges, true, window, cx);
15397        } else {
15398            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15399                editor
15400                    .update_in(cx, |editor, _, cx| {
15401                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15402                            editor.fold_buffer(buffer_id, cx);
15403                        }
15404                    })
15405                    .ok();
15406            });
15407        }
15408    }
15409
15410    pub fn fold_function_bodies(
15411        &mut self,
15412        _: &actions::FoldFunctionBodies,
15413        window: &mut Window,
15414        cx: &mut Context<Self>,
15415    ) {
15416        let snapshot = self.buffer.read(cx).snapshot(cx);
15417
15418        let ranges = snapshot
15419            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15420            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15421            .collect::<Vec<_>>();
15422
15423        let creases = ranges
15424            .into_iter()
15425            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15426            .collect();
15427
15428        self.fold_creases(creases, true, window, cx);
15429    }
15430
15431    pub fn fold_recursive(
15432        &mut self,
15433        _: &actions::FoldRecursive,
15434        window: &mut Window,
15435        cx: &mut Context<Self>,
15436    ) {
15437        let mut to_fold = Vec::new();
15438        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15439        let selections = self.selections.all_adjusted(cx);
15440
15441        for selection in selections {
15442            let range = selection.range().sorted();
15443            let buffer_start_row = range.start.row;
15444
15445            if range.start.row != range.end.row {
15446                let mut found = false;
15447                for row in range.start.row..=range.end.row {
15448                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15449                        found = true;
15450                        to_fold.push(crease);
15451                    }
15452                }
15453                if found {
15454                    continue;
15455                }
15456            }
15457
15458            for row in (0..=range.start.row).rev() {
15459                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15460                    if crease.range().end.row >= buffer_start_row {
15461                        to_fold.push(crease);
15462                    } else {
15463                        break;
15464                    }
15465                }
15466            }
15467        }
15468
15469        self.fold_creases(to_fold, true, window, cx);
15470    }
15471
15472    pub fn fold_at(
15473        &mut self,
15474        buffer_row: MultiBufferRow,
15475        window: &mut Window,
15476        cx: &mut Context<Self>,
15477    ) {
15478        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15479
15480        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15481            let autoscroll = self
15482                .selections
15483                .all::<Point>(cx)
15484                .iter()
15485                .any(|selection| crease.range().overlaps(&selection.range()));
15486
15487            self.fold_creases(vec![crease], autoscroll, window, cx);
15488        }
15489    }
15490
15491    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15492        if self.is_singleton(cx) {
15493            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15494            let buffer = &display_map.buffer_snapshot;
15495            let selections = self.selections.all::<Point>(cx);
15496            let ranges = selections
15497                .iter()
15498                .map(|s| {
15499                    let range = s.display_range(&display_map).sorted();
15500                    let mut start = range.start.to_point(&display_map);
15501                    let mut end = range.end.to_point(&display_map);
15502                    start.column = 0;
15503                    end.column = buffer.line_len(MultiBufferRow(end.row));
15504                    start..end
15505                })
15506                .collect::<Vec<_>>();
15507
15508            self.unfold_ranges(&ranges, true, true, cx);
15509        } else {
15510            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15511            let buffer_ids = self
15512                .selections
15513                .disjoint_anchor_ranges()
15514                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15515                .collect::<HashSet<_>>();
15516            for buffer_id in buffer_ids {
15517                self.unfold_buffer(buffer_id, cx);
15518            }
15519        }
15520    }
15521
15522    pub fn unfold_recursive(
15523        &mut self,
15524        _: &UnfoldRecursive,
15525        _window: &mut Window,
15526        cx: &mut Context<Self>,
15527    ) {
15528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15529        let selections = self.selections.all::<Point>(cx);
15530        let ranges = selections
15531            .iter()
15532            .map(|s| {
15533                let mut range = s.display_range(&display_map).sorted();
15534                *range.start.column_mut() = 0;
15535                *range.end.column_mut() = display_map.line_len(range.end.row());
15536                let start = range.start.to_point(&display_map);
15537                let end = range.end.to_point(&display_map);
15538                start..end
15539            })
15540            .collect::<Vec<_>>();
15541
15542        self.unfold_ranges(&ranges, true, true, cx);
15543    }
15544
15545    pub fn unfold_at(
15546        &mut self,
15547        buffer_row: MultiBufferRow,
15548        _window: &mut Window,
15549        cx: &mut Context<Self>,
15550    ) {
15551        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15552
15553        let intersection_range = Point::new(buffer_row.0, 0)
15554            ..Point::new(
15555                buffer_row.0,
15556                display_map.buffer_snapshot.line_len(buffer_row),
15557            );
15558
15559        let autoscroll = self
15560            .selections
15561            .all::<Point>(cx)
15562            .iter()
15563            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15564
15565        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15566    }
15567
15568    pub fn unfold_all(
15569        &mut self,
15570        _: &actions::UnfoldAll,
15571        _window: &mut Window,
15572        cx: &mut Context<Self>,
15573    ) {
15574        if self.buffer.read(cx).is_singleton() {
15575            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15576            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15577        } else {
15578            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15579                editor
15580                    .update(cx, |editor, cx| {
15581                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15582                            editor.unfold_buffer(buffer_id, cx);
15583                        }
15584                    })
15585                    .ok();
15586            });
15587        }
15588    }
15589
15590    pub fn fold_selected_ranges(
15591        &mut self,
15592        _: &FoldSelectedRanges,
15593        window: &mut Window,
15594        cx: &mut Context<Self>,
15595    ) {
15596        let selections = self.selections.all_adjusted(cx);
15597        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15598        let ranges = selections
15599            .into_iter()
15600            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15601            .collect::<Vec<_>>();
15602        self.fold_creases(ranges, true, window, cx);
15603    }
15604
15605    pub fn fold_ranges<T: ToOffset + Clone>(
15606        &mut self,
15607        ranges: Vec<Range<T>>,
15608        auto_scroll: bool,
15609        window: &mut Window,
15610        cx: &mut Context<Self>,
15611    ) {
15612        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15613        let ranges = ranges
15614            .into_iter()
15615            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15616            .collect::<Vec<_>>();
15617        self.fold_creases(ranges, auto_scroll, window, cx);
15618    }
15619
15620    pub fn fold_creases<T: ToOffset + Clone>(
15621        &mut self,
15622        creases: Vec<Crease<T>>,
15623        auto_scroll: bool,
15624        _window: &mut Window,
15625        cx: &mut Context<Self>,
15626    ) {
15627        if creases.is_empty() {
15628            return;
15629        }
15630
15631        let mut buffers_affected = HashSet::default();
15632        let multi_buffer = self.buffer().read(cx);
15633        for crease in &creases {
15634            if let Some((_, buffer, _)) =
15635                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15636            {
15637                buffers_affected.insert(buffer.read(cx).remote_id());
15638            };
15639        }
15640
15641        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15642
15643        if auto_scroll {
15644            self.request_autoscroll(Autoscroll::fit(), cx);
15645        }
15646
15647        cx.notify();
15648
15649        self.scrollbar_marker_state.dirty = true;
15650        self.folds_did_change(cx);
15651    }
15652
15653    /// Removes any folds whose ranges intersect any of the given ranges.
15654    pub fn unfold_ranges<T: ToOffset + Clone>(
15655        &mut self,
15656        ranges: &[Range<T>],
15657        inclusive: bool,
15658        auto_scroll: bool,
15659        cx: &mut Context<Self>,
15660    ) {
15661        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15662            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15663        });
15664        self.folds_did_change(cx);
15665    }
15666
15667    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15668        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15669            return;
15670        }
15671        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15672        self.display_map.update(cx, |display_map, cx| {
15673            display_map.fold_buffers([buffer_id], cx)
15674        });
15675        cx.emit(EditorEvent::BufferFoldToggled {
15676            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15677            folded: true,
15678        });
15679        cx.notify();
15680    }
15681
15682    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15683        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15684            return;
15685        }
15686        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15687        self.display_map.update(cx, |display_map, cx| {
15688            display_map.unfold_buffers([buffer_id], cx);
15689        });
15690        cx.emit(EditorEvent::BufferFoldToggled {
15691            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15692            folded: false,
15693        });
15694        cx.notify();
15695    }
15696
15697    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15698        self.display_map.read(cx).is_buffer_folded(buffer)
15699    }
15700
15701    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15702        self.display_map.read(cx).folded_buffers()
15703    }
15704
15705    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15706        self.display_map.update(cx, |display_map, cx| {
15707            display_map.disable_header_for_buffer(buffer_id, cx);
15708        });
15709        cx.notify();
15710    }
15711
15712    /// Removes any folds with the given ranges.
15713    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15714        &mut self,
15715        ranges: &[Range<T>],
15716        type_id: TypeId,
15717        auto_scroll: bool,
15718        cx: &mut Context<Self>,
15719    ) {
15720        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15721            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15722        });
15723        self.folds_did_change(cx);
15724    }
15725
15726    fn remove_folds_with<T: ToOffset + Clone>(
15727        &mut self,
15728        ranges: &[Range<T>],
15729        auto_scroll: bool,
15730        cx: &mut Context<Self>,
15731        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15732    ) {
15733        if ranges.is_empty() {
15734            return;
15735        }
15736
15737        let mut buffers_affected = HashSet::default();
15738        let multi_buffer = self.buffer().read(cx);
15739        for range in ranges {
15740            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15741                buffers_affected.insert(buffer.read(cx).remote_id());
15742            };
15743        }
15744
15745        self.display_map.update(cx, update);
15746
15747        if auto_scroll {
15748            self.request_autoscroll(Autoscroll::fit(), cx);
15749        }
15750
15751        cx.notify();
15752        self.scrollbar_marker_state.dirty = true;
15753        self.active_indent_guides_state.dirty = true;
15754    }
15755
15756    pub fn update_fold_widths(
15757        &mut self,
15758        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15759        cx: &mut Context<Self>,
15760    ) -> bool {
15761        self.display_map
15762            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15763    }
15764
15765    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15766        self.display_map.read(cx).fold_placeholder.clone()
15767    }
15768
15769    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15770        self.buffer.update(cx, |buffer, cx| {
15771            buffer.set_all_diff_hunks_expanded(cx);
15772        });
15773    }
15774
15775    pub fn expand_all_diff_hunks(
15776        &mut self,
15777        _: &ExpandAllDiffHunks,
15778        _window: &mut Window,
15779        cx: &mut Context<Self>,
15780    ) {
15781        self.buffer.update(cx, |buffer, cx| {
15782            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15783        });
15784    }
15785
15786    pub fn toggle_selected_diff_hunks(
15787        &mut self,
15788        _: &ToggleSelectedDiffHunks,
15789        _window: &mut Window,
15790        cx: &mut Context<Self>,
15791    ) {
15792        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15793        self.toggle_diff_hunks_in_ranges(ranges, cx);
15794    }
15795
15796    pub fn diff_hunks_in_ranges<'a>(
15797        &'a self,
15798        ranges: &'a [Range<Anchor>],
15799        buffer: &'a MultiBufferSnapshot,
15800    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15801        ranges.iter().flat_map(move |range| {
15802            let end_excerpt_id = range.end.excerpt_id;
15803            let range = range.to_point(buffer);
15804            let mut peek_end = range.end;
15805            if range.end.row < buffer.max_row().0 {
15806                peek_end = Point::new(range.end.row + 1, 0);
15807            }
15808            buffer
15809                .diff_hunks_in_range(range.start..peek_end)
15810                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15811        })
15812    }
15813
15814    pub fn has_stageable_diff_hunks_in_ranges(
15815        &self,
15816        ranges: &[Range<Anchor>],
15817        snapshot: &MultiBufferSnapshot,
15818    ) -> bool {
15819        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15820        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15821    }
15822
15823    pub fn toggle_staged_selected_diff_hunks(
15824        &mut self,
15825        _: &::git::ToggleStaged,
15826        _: &mut Window,
15827        cx: &mut Context<Self>,
15828    ) {
15829        let snapshot = self.buffer.read(cx).snapshot(cx);
15830        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15831        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15832        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15833    }
15834
15835    pub fn set_render_diff_hunk_controls(
15836        &mut self,
15837        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15838        cx: &mut Context<Self>,
15839    ) {
15840        self.render_diff_hunk_controls = render_diff_hunk_controls;
15841        cx.notify();
15842    }
15843
15844    pub fn stage_and_next(
15845        &mut self,
15846        _: &::git::StageAndNext,
15847        window: &mut Window,
15848        cx: &mut Context<Self>,
15849    ) {
15850        self.do_stage_or_unstage_and_next(true, window, cx);
15851    }
15852
15853    pub fn unstage_and_next(
15854        &mut self,
15855        _: &::git::UnstageAndNext,
15856        window: &mut Window,
15857        cx: &mut Context<Self>,
15858    ) {
15859        self.do_stage_or_unstage_and_next(false, window, cx);
15860    }
15861
15862    pub fn stage_or_unstage_diff_hunks(
15863        &mut self,
15864        stage: bool,
15865        ranges: Vec<Range<Anchor>>,
15866        cx: &mut Context<Self>,
15867    ) {
15868        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15869        cx.spawn(async move |this, cx| {
15870            task.await?;
15871            this.update(cx, |this, cx| {
15872                let snapshot = this.buffer.read(cx).snapshot(cx);
15873                let chunk_by = this
15874                    .diff_hunks_in_ranges(&ranges, &snapshot)
15875                    .chunk_by(|hunk| hunk.buffer_id);
15876                for (buffer_id, hunks) in &chunk_by {
15877                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15878                }
15879            })
15880        })
15881        .detach_and_log_err(cx);
15882    }
15883
15884    fn save_buffers_for_ranges_if_needed(
15885        &mut self,
15886        ranges: &[Range<Anchor>],
15887        cx: &mut Context<Editor>,
15888    ) -> Task<Result<()>> {
15889        let multibuffer = self.buffer.read(cx);
15890        let snapshot = multibuffer.read(cx);
15891        let buffer_ids: HashSet<_> = ranges
15892            .iter()
15893            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15894            .collect();
15895        drop(snapshot);
15896
15897        let mut buffers = HashSet::default();
15898        for buffer_id in buffer_ids {
15899            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15900                let buffer = buffer_entity.read(cx);
15901                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15902                {
15903                    buffers.insert(buffer_entity);
15904                }
15905            }
15906        }
15907
15908        if let Some(project) = &self.project {
15909            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15910        } else {
15911            Task::ready(Ok(()))
15912        }
15913    }
15914
15915    fn do_stage_or_unstage_and_next(
15916        &mut self,
15917        stage: bool,
15918        window: &mut Window,
15919        cx: &mut Context<Self>,
15920    ) {
15921        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15922
15923        if ranges.iter().any(|range| range.start != range.end) {
15924            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15925            return;
15926        }
15927
15928        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15929        let snapshot = self.snapshot(window, cx);
15930        let position = self.selections.newest::<Point>(cx).head();
15931        let mut row = snapshot
15932            .buffer_snapshot
15933            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15934            .find(|hunk| hunk.row_range.start.0 > position.row)
15935            .map(|hunk| hunk.row_range.start);
15936
15937        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15938        // Outside of the project diff editor, wrap around to the beginning.
15939        if !all_diff_hunks_expanded {
15940            row = row.or_else(|| {
15941                snapshot
15942                    .buffer_snapshot
15943                    .diff_hunks_in_range(Point::zero()..position)
15944                    .find(|hunk| hunk.row_range.end.0 < position.row)
15945                    .map(|hunk| hunk.row_range.start)
15946            });
15947        }
15948
15949        if let Some(row) = row {
15950            let destination = Point::new(row.0, 0);
15951            let autoscroll = Autoscroll::center();
15952
15953            self.unfold_ranges(&[destination..destination], false, false, cx);
15954            self.change_selections(Some(autoscroll), window, cx, |s| {
15955                s.select_ranges([destination..destination]);
15956            });
15957        }
15958    }
15959
15960    fn do_stage_or_unstage(
15961        &self,
15962        stage: bool,
15963        buffer_id: BufferId,
15964        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15965        cx: &mut App,
15966    ) -> Option<()> {
15967        let project = self.project.as_ref()?;
15968        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15969        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15970        let buffer_snapshot = buffer.read(cx).snapshot();
15971        let file_exists = buffer_snapshot
15972            .file()
15973            .is_some_and(|file| file.disk_state().exists());
15974        diff.update(cx, |diff, cx| {
15975            diff.stage_or_unstage_hunks(
15976                stage,
15977                &hunks
15978                    .map(|hunk| buffer_diff::DiffHunk {
15979                        buffer_range: hunk.buffer_range,
15980                        diff_base_byte_range: hunk.diff_base_byte_range,
15981                        secondary_status: hunk.secondary_status,
15982                        range: Point::zero()..Point::zero(), // unused
15983                    })
15984                    .collect::<Vec<_>>(),
15985                &buffer_snapshot,
15986                file_exists,
15987                cx,
15988            )
15989        });
15990        None
15991    }
15992
15993    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15994        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15995        self.buffer
15996            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15997    }
15998
15999    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16000        self.buffer.update(cx, |buffer, cx| {
16001            let ranges = vec![Anchor::min()..Anchor::max()];
16002            if !buffer.all_diff_hunks_expanded()
16003                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16004            {
16005                buffer.collapse_diff_hunks(ranges, cx);
16006                true
16007            } else {
16008                false
16009            }
16010        })
16011    }
16012
16013    fn toggle_diff_hunks_in_ranges(
16014        &mut self,
16015        ranges: Vec<Range<Anchor>>,
16016        cx: &mut Context<Editor>,
16017    ) {
16018        self.buffer.update(cx, |buffer, cx| {
16019            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16020            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16021        })
16022    }
16023
16024    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16025        self.buffer.update(cx, |buffer, cx| {
16026            let snapshot = buffer.snapshot(cx);
16027            let excerpt_id = range.end.excerpt_id;
16028            let point_range = range.to_point(&snapshot);
16029            let expand = !buffer.single_hunk_is_expanded(range, cx);
16030            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16031        })
16032    }
16033
16034    pub(crate) fn apply_all_diff_hunks(
16035        &mut self,
16036        _: &ApplyAllDiffHunks,
16037        window: &mut Window,
16038        cx: &mut Context<Self>,
16039    ) {
16040        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16041
16042        let buffers = self.buffer.read(cx).all_buffers();
16043        for branch_buffer in buffers {
16044            branch_buffer.update(cx, |branch_buffer, cx| {
16045                branch_buffer.merge_into_base(Vec::new(), cx);
16046            });
16047        }
16048
16049        if let Some(project) = self.project.clone() {
16050            self.save(true, project, window, cx).detach_and_log_err(cx);
16051        }
16052    }
16053
16054    pub(crate) fn apply_selected_diff_hunks(
16055        &mut self,
16056        _: &ApplyDiffHunk,
16057        window: &mut Window,
16058        cx: &mut Context<Self>,
16059    ) {
16060        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16061        let snapshot = self.snapshot(window, cx);
16062        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16063        let mut ranges_by_buffer = HashMap::default();
16064        self.transact(window, cx, |editor, _window, cx| {
16065            for hunk in hunks {
16066                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16067                    ranges_by_buffer
16068                        .entry(buffer.clone())
16069                        .or_insert_with(Vec::new)
16070                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16071                }
16072            }
16073
16074            for (buffer, ranges) in ranges_by_buffer {
16075                buffer.update(cx, |buffer, cx| {
16076                    buffer.merge_into_base(ranges, cx);
16077                });
16078            }
16079        });
16080
16081        if let Some(project) = self.project.clone() {
16082            self.save(true, project, window, cx).detach_and_log_err(cx);
16083        }
16084    }
16085
16086    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16087        if hovered != self.gutter_hovered {
16088            self.gutter_hovered = hovered;
16089            cx.notify();
16090        }
16091    }
16092
16093    pub fn insert_blocks(
16094        &mut self,
16095        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16096        autoscroll: Option<Autoscroll>,
16097        cx: &mut Context<Self>,
16098    ) -> Vec<CustomBlockId> {
16099        let blocks = self
16100            .display_map
16101            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16102        if let Some(autoscroll) = autoscroll {
16103            self.request_autoscroll(autoscroll, cx);
16104        }
16105        cx.notify();
16106        blocks
16107    }
16108
16109    pub fn resize_blocks(
16110        &mut self,
16111        heights: HashMap<CustomBlockId, u32>,
16112        autoscroll: Option<Autoscroll>,
16113        cx: &mut Context<Self>,
16114    ) {
16115        self.display_map
16116            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16117        if let Some(autoscroll) = autoscroll {
16118            self.request_autoscroll(autoscroll, cx);
16119        }
16120        cx.notify();
16121    }
16122
16123    pub fn replace_blocks(
16124        &mut self,
16125        renderers: HashMap<CustomBlockId, RenderBlock>,
16126        autoscroll: Option<Autoscroll>,
16127        cx: &mut Context<Self>,
16128    ) {
16129        self.display_map
16130            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16131        if let Some(autoscroll) = autoscroll {
16132            self.request_autoscroll(autoscroll, cx);
16133        }
16134        cx.notify();
16135    }
16136
16137    pub fn remove_blocks(
16138        &mut self,
16139        block_ids: HashSet<CustomBlockId>,
16140        autoscroll: Option<Autoscroll>,
16141        cx: &mut Context<Self>,
16142    ) {
16143        self.display_map.update(cx, |display_map, cx| {
16144            display_map.remove_blocks(block_ids, cx)
16145        });
16146        if let Some(autoscroll) = autoscroll {
16147            self.request_autoscroll(autoscroll, cx);
16148        }
16149        cx.notify();
16150    }
16151
16152    pub fn row_for_block(
16153        &self,
16154        block_id: CustomBlockId,
16155        cx: &mut Context<Self>,
16156    ) -> Option<DisplayRow> {
16157        self.display_map
16158            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16159    }
16160
16161    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16162        self.focused_block = Some(focused_block);
16163    }
16164
16165    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16166        self.focused_block.take()
16167    }
16168
16169    pub fn insert_creases(
16170        &mut self,
16171        creases: impl IntoIterator<Item = Crease<Anchor>>,
16172        cx: &mut Context<Self>,
16173    ) -> Vec<CreaseId> {
16174        self.display_map
16175            .update(cx, |map, cx| map.insert_creases(creases, cx))
16176    }
16177
16178    pub fn remove_creases(
16179        &mut self,
16180        ids: impl IntoIterator<Item = CreaseId>,
16181        cx: &mut Context<Self>,
16182    ) -> Vec<(CreaseId, Range<Anchor>)> {
16183        self.display_map
16184            .update(cx, |map, cx| map.remove_creases(ids, cx))
16185    }
16186
16187    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16188        self.display_map
16189            .update(cx, |map, cx| map.snapshot(cx))
16190            .longest_row()
16191    }
16192
16193    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16194        self.display_map
16195            .update(cx, |map, cx| map.snapshot(cx))
16196            .max_point()
16197    }
16198
16199    pub fn text(&self, cx: &App) -> String {
16200        self.buffer.read(cx).read(cx).text()
16201    }
16202
16203    pub fn is_empty(&self, cx: &App) -> bool {
16204        self.buffer.read(cx).read(cx).is_empty()
16205    }
16206
16207    pub fn text_option(&self, cx: &App) -> Option<String> {
16208        let text = self.text(cx);
16209        let text = text.trim();
16210
16211        if text.is_empty() {
16212            return None;
16213        }
16214
16215        Some(text.to_string())
16216    }
16217
16218    pub fn set_text(
16219        &mut self,
16220        text: impl Into<Arc<str>>,
16221        window: &mut Window,
16222        cx: &mut Context<Self>,
16223    ) {
16224        self.transact(window, cx, |this, _, cx| {
16225            this.buffer
16226                .read(cx)
16227                .as_singleton()
16228                .expect("you can only call set_text on editors for singleton buffers")
16229                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16230        });
16231    }
16232
16233    pub fn display_text(&self, cx: &mut App) -> String {
16234        self.display_map
16235            .update(cx, |map, cx| map.snapshot(cx))
16236            .text()
16237    }
16238
16239    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16240        let mut wrap_guides = smallvec::smallvec![];
16241
16242        if self.show_wrap_guides == Some(false) {
16243            return wrap_guides;
16244        }
16245
16246        let settings = self.buffer.read(cx).language_settings(cx);
16247        if settings.show_wrap_guides {
16248            match self.soft_wrap_mode(cx) {
16249                SoftWrap::Column(soft_wrap) => {
16250                    wrap_guides.push((soft_wrap as usize, true));
16251                }
16252                SoftWrap::Bounded(soft_wrap) => {
16253                    wrap_guides.push((soft_wrap as usize, true));
16254                }
16255                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16256            }
16257            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16258        }
16259
16260        wrap_guides
16261    }
16262
16263    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16264        let settings = self.buffer.read(cx).language_settings(cx);
16265        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16266        match mode {
16267            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16268                SoftWrap::None
16269            }
16270            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16271            language_settings::SoftWrap::PreferredLineLength => {
16272                SoftWrap::Column(settings.preferred_line_length)
16273            }
16274            language_settings::SoftWrap::Bounded => {
16275                SoftWrap::Bounded(settings.preferred_line_length)
16276            }
16277        }
16278    }
16279
16280    pub fn set_soft_wrap_mode(
16281        &mut self,
16282        mode: language_settings::SoftWrap,
16283
16284        cx: &mut Context<Self>,
16285    ) {
16286        self.soft_wrap_mode_override = Some(mode);
16287        cx.notify();
16288    }
16289
16290    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16291        self.hard_wrap = hard_wrap;
16292        cx.notify();
16293    }
16294
16295    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16296        self.text_style_refinement = Some(style);
16297    }
16298
16299    /// called by the Element so we know what style we were most recently rendered with.
16300    pub(crate) fn set_style(
16301        &mut self,
16302        style: EditorStyle,
16303        window: &mut Window,
16304        cx: &mut Context<Self>,
16305    ) {
16306        let rem_size = window.rem_size();
16307        self.display_map.update(cx, |map, cx| {
16308            map.set_font(
16309                style.text.font(),
16310                style.text.font_size.to_pixels(rem_size),
16311                cx,
16312            )
16313        });
16314        self.style = Some(style);
16315    }
16316
16317    pub fn style(&self) -> Option<&EditorStyle> {
16318        self.style.as_ref()
16319    }
16320
16321    // Called by the element. This method is not designed to be called outside of the editor
16322    // element's layout code because it does not notify when rewrapping is computed synchronously.
16323    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16324        self.display_map
16325            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16326    }
16327
16328    pub fn set_soft_wrap(&mut self) {
16329        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16330    }
16331
16332    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16333        if self.soft_wrap_mode_override.is_some() {
16334            self.soft_wrap_mode_override.take();
16335        } else {
16336            let soft_wrap = match self.soft_wrap_mode(cx) {
16337                SoftWrap::GitDiff => return,
16338                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16339                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16340                    language_settings::SoftWrap::None
16341                }
16342            };
16343            self.soft_wrap_mode_override = Some(soft_wrap);
16344        }
16345        cx.notify();
16346    }
16347
16348    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16349        let Some(workspace) = self.workspace() else {
16350            return;
16351        };
16352        let fs = workspace.read(cx).app_state().fs.clone();
16353        let current_show = TabBarSettings::get_global(cx).show;
16354        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16355            setting.show = Some(!current_show);
16356        });
16357    }
16358
16359    pub fn toggle_indent_guides(
16360        &mut self,
16361        _: &ToggleIndentGuides,
16362        _: &mut Window,
16363        cx: &mut Context<Self>,
16364    ) {
16365        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16366            self.buffer
16367                .read(cx)
16368                .language_settings(cx)
16369                .indent_guides
16370                .enabled
16371        });
16372        self.show_indent_guides = Some(!currently_enabled);
16373        cx.notify();
16374    }
16375
16376    fn should_show_indent_guides(&self) -> Option<bool> {
16377        self.show_indent_guides
16378    }
16379
16380    pub fn toggle_line_numbers(
16381        &mut self,
16382        _: &ToggleLineNumbers,
16383        _: &mut Window,
16384        cx: &mut Context<Self>,
16385    ) {
16386        let mut editor_settings = EditorSettings::get_global(cx).clone();
16387        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16388        EditorSettings::override_global(editor_settings, cx);
16389    }
16390
16391    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16392        if let Some(show_line_numbers) = self.show_line_numbers {
16393            return show_line_numbers;
16394        }
16395        EditorSettings::get_global(cx).gutter.line_numbers
16396    }
16397
16398    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16399        self.use_relative_line_numbers
16400            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16401    }
16402
16403    pub fn toggle_relative_line_numbers(
16404        &mut self,
16405        _: &ToggleRelativeLineNumbers,
16406        _: &mut Window,
16407        cx: &mut Context<Self>,
16408    ) {
16409        let is_relative = self.should_use_relative_line_numbers(cx);
16410        self.set_relative_line_number(Some(!is_relative), cx)
16411    }
16412
16413    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16414        self.use_relative_line_numbers = is_relative;
16415        cx.notify();
16416    }
16417
16418    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16419        self.show_gutter = show_gutter;
16420        cx.notify();
16421    }
16422
16423    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16424        self.show_scrollbars = show_scrollbars;
16425        cx.notify();
16426    }
16427
16428    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16429        self.show_line_numbers = Some(show_line_numbers);
16430        cx.notify();
16431    }
16432
16433    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16434        self.disable_expand_excerpt_buttons = true;
16435        cx.notify();
16436    }
16437
16438    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16439        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16440        cx.notify();
16441    }
16442
16443    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16444        self.show_code_actions = Some(show_code_actions);
16445        cx.notify();
16446    }
16447
16448    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16449        self.show_runnables = Some(show_runnables);
16450        cx.notify();
16451    }
16452
16453    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16454        self.show_breakpoints = Some(show_breakpoints);
16455        cx.notify();
16456    }
16457
16458    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16459        if self.display_map.read(cx).masked != masked {
16460            self.display_map.update(cx, |map, _| map.masked = masked);
16461        }
16462        cx.notify()
16463    }
16464
16465    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16466        self.show_wrap_guides = Some(show_wrap_guides);
16467        cx.notify();
16468    }
16469
16470    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16471        self.show_indent_guides = Some(show_indent_guides);
16472        cx.notify();
16473    }
16474
16475    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16476        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16477            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16478                if let Some(dir) = file.abs_path(cx).parent() {
16479                    return Some(dir.to_owned());
16480                }
16481            }
16482
16483            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16484                return Some(project_path.path.to_path_buf());
16485            }
16486        }
16487
16488        None
16489    }
16490
16491    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16492        self.active_excerpt(cx)?
16493            .1
16494            .read(cx)
16495            .file()
16496            .and_then(|f| f.as_local())
16497    }
16498
16499    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16500        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16501            let buffer = buffer.read(cx);
16502            if let Some(project_path) = buffer.project_path(cx) {
16503                let project = self.project.as_ref()?.read(cx);
16504                project.absolute_path(&project_path, cx)
16505            } else {
16506                buffer
16507                    .file()
16508                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16509            }
16510        })
16511    }
16512
16513    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16514        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16515            let project_path = buffer.read(cx).project_path(cx)?;
16516            let project = self.project.as_ref()?.read(cx);
16517            let entry = project.entry_for_path(&project_path, cx)?;
16518            let path = entry.path.to_path_buf();
16519            Some(path)
16520        })
16521    }
16522
16523    pub fn reveal_in_finder(
16524        &mut self,
16525        _: &RevealInFileManager,
16526        _window: &mut Window,
16527        cx: &mut Context<Self>,
16528    ) {
16529        if let Some(target) = self.target_file(cx) {
16530            cx.reveal_path(&target.abs_path(cx));
16531        }
16532    }
16533
16534    pub fn copy_path(
16535        &mut self,
16536        _: &zed_actions::workspace::CopyPath,
16537        _window: &mut Window,
16538        cx: &mut Context<Self>,
16539    ) {
16540        if let Some(path) = self.target_file_abs_path(cx) {
16541            if let Some(path) = path.to_str() {
16542                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16543            }
16544        }
16545    }
16546
16547    pub fn copy_relative_path(
16548        &mut self,
16549        _: &zed_actions::workspace::CopyRelativePath,
16550        _window: &mut Window,
16551        cx: &mut Context<Self>,
16552    ) {
16553        if let Some(path) = self.target_file_path(cx) {
16554            if let Some(path) = path.to_str() {
16555                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16556            }
16557        }
16558    }
16559
16560    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16561        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16562            buffer.read(cx).project_path(cx)
16563        } else {
16564            None
16565        }
16566    }
16567
16568    // Returns true if the editor handled a go-to-line request
16569    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16570        maybe!({
16571            let breakpoint_store = self.breakpoint_store.as_ref()?;
16572
16573            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16574            else {
16575                self.clear_row_highlights::<ActiveDebugLine>();
16576                return None;
16577            };
16578
16579            let position = active_stack_frame.position;
16580            let buffer_id = position.buffer_id?;
16581            let snapshot = self
16582                .project
16583                .as_ref()?
16584                .read(cx)
16585                .buffer_for_id(buffer_id, cx)?
16586                .read(cx)
16587                .snapshot();
16588
16589            let mut handled = false;
16590            for (id, ExcerptRange { context, .. }) in
16591                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16592            {
16593                if context.start.cmp(&position, &snapshot).is_ge()
16594                    || context.end.cmp(&position, &snapshot).is_lt()
16595                {
16596                    continue;
16597                }
16598                let snapshot = self.buffer.read(cx).snapshot(cx);
16599                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16600
16601                handled = true;
16602                self.clear_row_highlights::<ActiveDebugLine>();
16603                self.go_to_line::<ActiveDebugLine>(
16604                    multibuffer_anchor,
16605                    Some(cx.theme().colors().editor_debugger_active_line_background),
16606                    window,
16607                    cx,
16608                );
16609
16610                cx.notify();
16611            }
16612
16613            handled.then_some(())
16614        })
16615        .is_some()
16616    }
16617
16618    pub fn copy_file_name_without_extension(
16619        &mut self,
16620        _: &CopyFileNameWithoutExtension,
16621        _: &mut Window,
16622        cx: &mut Context<Self>,
16623    ) {
16624        if let Some(file) = self.target_file(cx) {
16625            if let Some(file_stem) = file.path().file_stem() {
16626                if let Some(name) = file_stem.to_str() {
16627                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16628                }
16629            }
16630        }
16631    }
16632
16633    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16634        if let Some(file) = self.target_file(cx) {
16635            if let Some(file_name) = file.path().file_name() {
16636                if let Some(name) = file_name.to_str() {
16637                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16638                }
16639            }
16640        }
16641    }
16642
16643    pub fn toggle_git_blame(
16644        &mut self,
16645        _: &::git::Blame,
16646        window: &mut Window,
16647        cx: &mut Context<Self>,
16648    ) {
16649        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16650
16651        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16652            self.start_git_blame(true, window, cx);
16653        }
16654
16655        cx.notify();
16656    }
16657
16658    pub fn toggle_git_blame_inline(
16659        &mut self,
16660        _: &ToggleGitBlameInline,
16661        window: &mut Window,
16662        cx: &mut Context<Self>,
16663    ) {
16664        self.toggle_git_blame_inline_internal(true, window, cx);
16665        cx.notify();
16666    }
16667
16668    pub fn open_git_blame_commit(
16669        &mut self,
16670        _: &OpenGitBlameCommit,
16671        window: &mut Window,
16672        cx: &mut Context<Self>,
16673    ) {
16674        self.open_git_blame_commit_internal(window, cx);
16675    }
16676
16677    fn open_git_blame_commit_internal(
16678        &mut self,
16679        window: &mut Window,
16680        cx: &mut Context<Self>,
16681    ) -> Option<()> {
16682        let blame = self.blame.as_ref()?;
16683        let snapshot = self.snapshot(window, cx);
16684        let cursor = self.selections.newest::<Point>(cx).head();
16685        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16686        let blame_entry = blame
16687            .update(cx, |blame, cx| {
16688                blame
16689                    .blame_for_rows(
16690                        &[RowInfo {
16691                            buffer_id: Some(buffer.remote_id()),
16692                            buffer_row: Some(point.row),
16693                            ..Default::default()
16694                        }],
16695                        cx,
16696                    )
16697                    .next()
16698            })
16699            .flatten()?;
16700        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16701        let repo = blame.read(cx).repository(cx)?;
16702        let workspace = self.workspace()?.downgrade();
16703        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16704        None
16705    }
16706
16707    pub fn git_blame_inline_enabled(&self) -> bool {
16708        self.git_blame_inline_enabled
16709    }
16710
16711    pub fn toggle_selection_menu(
16712        &mut self,
16713        _: &ToggleSelectionMenu,
16714        _: &mut Window,
16715        cx: &mut Context<Self>,
16716    ) {
16717        self.show_selection_menu = self
16718            .show_selection_menu
16719            .map(|show_selections_menu| !show_selections_menu)
16720            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16721
16722        cx.notify();
16723    }
16724
16725    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16726        self.show_selection_menu
16727            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16728    }
16729
16730    fn start_git_blame(
16731        &mut self,
16732        user_triggered: bool,
16733        window: &mut Window,
16734        cx: &mut Context<Self>,
16735    ) {
16736        if let Some(project) = self.project.as_ref() {
16737            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16738                return;
16739            };
16740
16741            if buffer.read(cx).file().is_none() {
16742                return;
16743            }
16744
16745            let focused = self.focus_handle(cx).contains_focused(window, cx);
16746
16747            let project = project.clone();
16748            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16749            self.blame_subscription =
16750                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16751            self.blame = Some(blame);
16752        }
16753    }
16754
16755    fn toggle_git_blame_inline_internal(
16756        &mut self,
16757        user_triggered: bool,
16758        window: &mut Window,
16759        cx: &mut Context<Self>,
16760    ) {
16761        if self.git_blame_inline_enabled {
16762            self.git_blame_inline_enabled = false;
16763            self.show_git_blame_inline = false;
16764            self.show_git_blame_inline_delay_task.take();
16765        } else {
16766            self.git_blame_inline_enabled = true;
16767            self.start_git_blame_inline(user_triggered, window, cx);
16768        }
16769
16770        cx.notify();
16771    }
16772
16773    fn start_git_blame_inline(
16774        &mut self,
16775        user_triggered: bool,
16776        window: &mut Window,
16777        cx: &mut Context<Self>,
16778    ) {
16779        self.start_git_blame(user_triggered, window, cx);
16780
16781        if ProjectSettings::get_global(cx)
16782            .git
16783            .inline_blame_delay()
16784            .is_some()
16785        {
16786            self.start_inline_blame_timer(window, cx);
16787        } else {
16788            self.show_git_blame_inline = true
16789        }
16790    }
16791
16792    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16793        self.blame.as_ref()
16794    }
16795
16796    pub fn show_git_blame_gutter(&self) -> bool {
16797        self.show_git_blame_gutter
16798    }
16799
16800    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16801        self.show_git_blame_gutter && self.has_blame_entries(cx)
16802    }
16803
16804    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16805        self.show_git_blame_inline
16806            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16807            && !self.newest_selection_head_on_empty_line(cx)
16808            && self.has_blame_entries(cx)
16809    }
16810
16811    fn has_blame_entries(&self, cx: &App) -> bool {
16812        self.blame()
16813            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16814    }
16815
16816    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16817        let cursor_anchor = self.selections.newest_anchor().head();
16818
16819        let snapshot = self.buffer.read(cx).snapshot(cx);
16820        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16821
16822        snapshot.line_len(buffer_row) == 0
16823    }
16824
16825    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16826        let buffer_and_selection = maybe!({
16827            let selection = self.selections.newest::<Point>(cx);
16828            let selection_range = selection.range();
16829
16830            let multi_buffer = self.buffer().read(cx);
16831            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16832            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16833
16834            let (buffer, range, _) = if selection.reversed {
16835                buffer_ranges.first()
16836            } else {
16837                buffer_ranges.last()
16838            }?;
16839
16840            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16841                ..text::ToPoint::to_point(&range.end, &buffer).row;
16842            Some((
16843                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16844                selection,
16845            ))
16846        });
16847
16848        let Some((buffer, selection)) = buffer_and_selection else {
16849            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16850        };
16851
16852        let Some(project) = self.project.as_ref() else {
16853            return Task::ready(Err(anyhow!("editor does not have project")));
16854        };
16855
16856        project.update(cx, |project, cx| {
16857            project.get_permalink_to_line(&buffer, selection, cx)
16858        })
16859    }
16860
16861    pub fn copy_permalink_to_line(
16862        &mut self,
16863        _: &CopyPermalinkToLine,
16864        window: &mut Window,
16865        cx: &mut Context<Self>,
16866    ) {
16867        let permalink_task = self.get_permalink_to_line(cx);
16868        let workspace = self.workspace();
16869
16870        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16871            Ok(permalink) => {
16872                cx.update(|_, cx| {
16873                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16874                })
16875                .ok();
16876            }
16877            Err(err) => {
16878                let message = format!("Failed to copy permalink: {err}");
16879
16880                Err::<(), anyhow::Error>(err).log_err();
16881
16882                if let Some(workspace) = workspace {
16883                    workspace
16884                        .update_in(cx, |workspace, _, cx| {
16885                            struct CopyPermalinkToLine;
16886
16887                            workspace.show_toast(
16888                                Toast::new(
16889                                    NotificationId::unique::<CopyPermalinkToLine>(),
16890                                    message,
16891                                ),
16892                                cx,
16893                            )
16894                        })
16895                        .ok();
16896                }
16897            }
16898        })
16899        .detach();
16900    }
16901
16902    pub fn copy_file_location(
16903        &mut self,
16904        _: &CopyFileLocation,
16905        _: &mut Window,
16906        cx: &mut Context<Self>,
16907    ) {
16908        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16909        if let Some(file) = self.target_file(cx) {
16910            if let Some(path) = file.path().to_str() {
16911                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16912            }
16913        }
16914    }
16915
16916    pub fn open_permalink_to_line(
16917        &mut self,
16918        _: &OpenPermalinkToLine,
16919        window: &mut Window,
16920        cx: &mut Context<Self>,
16921    ) {
16922        let permalink_task = self.get_permalink_to_line(cx);
16923        let workspace = self.workspace();
16924
16925        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16926            Ok(permalink) => {
16927                cx.update(|_, cx| {
16928                    cx.open_url(permalink.as_ref());
16929                })
16930                .ok();
16931            }
16932            Err(err) => {
16933                let message = format!("Failed to open permalink: {err}");
16934
16935                Err::<(), anyhow::Error>(err).log_err();
16936
16937                if let Some(workspace) = workspace {
16938                    workspace
16939                        .update(cx, |workspace, cx| {
16940                            struct OpenPermalinkToLine;
16941
16942                            workspace.show_toast(
16943                                Toast::new(
16944                                    NotificationId::unique::<OpenPermalinkToLine>(),
16945                                    message,
16946                                ),
16947                                cx,
16948                            )
16949                        })
16950                        .ok();
16951                }
16952            }
16953        })
16954        .detach();
16955    }
16956
16957    pub fn insert_uuid_v4(
16958        &mut self,
16959        _: &InsertUuidV4,
16960        window: &mut Window,
16961        cx: &mut Context<Self>,
16962    ) {
16963        self.insert_uuid(UuidVersion::V4, window, cx);
16964    }
16965
16966    pub fn insert_uuid_v7(
16967        &mut self,
16968        _: &InsertUuidV7,
16969        window: &mut Window,
16970        cx: &mut Context<Self>,
16971    ) {
16972        self.insert_uuid(UuidVersion::V7, window, cx);
16973    }
16974
16975    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16976        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16977        self.transact(window, cx, |this, window, cx| {
16978            let edits = this
16979                .selections
16980                .all::<Point>(cx)
16981                .into_iter()
16982                .map(|selection| {
16983                    let uuid = match version {
16984                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16985                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16986                    };
16987
16988                    (selection.range(), uuid.to_string())
16989                });
16990            this.edit(edits, cx);
16991            this.refresh_inline_completion(true, false, window, cx);
16992        });
16993    }
16994
16995    pub fn open_selections_in_multibuffer(
16996        &mut self,
16997        _: &OpenSelectionsInMultibuffer,
16998        window: &mut Window,
16999        cx: &mut Context<Self>,
17000    ) {
17001        let multibuffer = self.buffer.read(cx);
17002
17003        let Some(buffer) = multibuffer.as_singleton() else {
17004            return;
17005        };
17006
17007        let Some(workspace) = self.workspace() else {
17008            return;
17009        };
17010
17011        let locations = self
17012            .selections
17013            .disjoint_anchors()
17014            .iter()
17015            .map(|range| Location {
17016                buffer: buffer.clone(),
17017                range: range.start.text_anchor..range.end.text_anchor,
17018            })
17019            .collect::<Vec<_>>();
17020
17021        let title = multibuffer.title(cx).to_string();
17022
17023        cx.spawn_in(window, async move |_, cx| {
17024            workspace.update_in(cx, |workspace, window, cx| {
17025                Self::open_locations_in_multibuffer(
17026                    workspace,
17027                    locations,
17028                    format!("Selections for '{title}'"),
17029                    false,
17030                    MultibufferSelectionMode::All,
17031                    window,
17032                    cx,
17033                );
17034            })
17035        })
17036        .detach();
17037    }
17038
17039    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17040    /// last highlight added will be used.
17041    ///
17042    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17043    pub fn highlight_rows<T: 'static>(
17044        &mut self,
17045        range: Range<Anchor>,
17046        color: Hsla,
17047        options: RowHighlightOptions,
17048        cx: &mut Context<Self>,
17049    ) {
17050        let snapshot = self.buffer().read(cx).snapshot(cx);
17051        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17052        let ix = row_highlights.binary_search_by(|highlight| {
17053            Ordering::Equal
17054                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17055                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17056        });
17057
17058        if let Err(mut ix) = ix {
17059            let index = post_inc(&mut self.highlight_order);
17060
17061            // If this range intersects with the preceding highlight, then merge it with
17062            // the preceding highlight. Otherwise insert a new highlight.
17063            let mut merged = false;
17064            if ix > 0 {
17065                let prev_highlight = &mut row_highlights[ix - 1];
17066                if prev_highlight
17067                    .range
17068                    .end
17069                    .cmp(&range.start, &snapshot)
17070                    .is_ge()
17071                {
17072                    ix -= 1;
17073                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17074                        prev_highlight.range.end = range.end;
17075                    }
17076                    merged = true;
17077                    prev_highlight.index = index;
17078                    prev_highlight.color = color;
17079                    prev_highlight.options = options;
17080                }
17081            }
17082
17083            if !merged {
17084                row_highlights.insert(
17085                    ix,
17086                    RowHighlight {
17087                        range: range.clone(),
17088                        index,
17089                        color,
17090                        options,
17091                        type_id: TypeId::of::<T>(),
17092                    },
17093                );
17094            }
17095
17096            // If any of the following highlights intersect with this one, merge them.
17097            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17098                let highlight = &row_highlights[ix];
17099                if next_highlight
17100                    .range
17101                    .start
17102                    .cmp(&highlight.range.end, &snapshot)
17103                    .is_le()
17104                {
17105                    if next_highlight
17106                        .range
17107                        .end
17108                        .cmp(&highlight.range.end, &snapshot)
17109                        .is_gt()
17110                    {
17111                        row_highlights[ix].range.end = next_highlight.range.end;
17112                    }
17113                    row_highlights.remove(ix + 1);
17114                } else {
17115                    break;
17116                }
17117            }
17118        }
17119    }
17120
17121    /// Remove any highlighted row ranges of the given type that intersect the
17122    /// given ranges.
17123    pub fn remove_highlighted_rows<T: 'static>(
17124        &mut self,
17125        ranges_to_remove: Vec<Range<Anchor>>,
17126        cx: &mut Context<Self>,
17127    ) {
17128        let snapshot = self.buffer().read(cx).snapshot(cx);
17129        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17130        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17131        row_highlights.retain(|highlight| {
17132            while let Some(range_to_remove) = ranges_to_remove.peek() {
17133                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17134                    Ordering::Less | Ordering::Equal => {
17135                        ranges_to_remove.next();
17136                    }
17137                    Ordering::Greater => {
17138                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17139                            Ordering::Less | Ordering::Equal => {
17140                                return false;
17141                            }
17142                            Ordering::Greater => break,
17143                        }
17144                    }
17145                }
17146            }
17147
17148            true
17149        })
17150    }
17151
17152    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17153    pub fn clear_row_highlights<T: 'static>(&mut self) {
17154        self.highlighted_rows.remove(&TypeId::of::<T>());
17155    }
17156
17157    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17158    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17159        self.highlighted_rows
17160            .get(&TypeId::of::<T>())
17161            .map_or(&[] as &[_], |vec| vec.as_slice())
17162            .iter()
17163            .map(|highlight| (highlight.range.clone(), highlight.color))
17164    }
17165
17166    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17167    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17168    /// Allows to ignore certain kinds of highlights.
17169    pub fn highlighted_display_rows(
17170        &self,
17171        window: &mut Window,
17172        cx: &mut App,
17173    ) -> BTreeMap<DisplayRow, LineHighlight> {
17174        let snapshot = self.snapshot(window, cx);
17175        let mut used_highlight_orders = HashMap::default();
17176        self.highlighted_rows
17177            .iter()
17178            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17179            .fold(
17180                BTreeMap::<DisplayRow, LineHighlight>::new(),
17181                |mut unique_rows, highlight| {
17182                    let start = highlight.range.start.to_display_point(&snapshot);
17183                    let end = highlight.range.end.to_display_point(&snapshot);
17184                    let start_row = start.row().0;
17185                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17186                        && end.column() == 0
17187                    {
17188                        end.row().0.saturating_sub(1)
17189                    } else {
17190                        end.row().0
17191                    };
17192                    for row in start_row..=end_row {
17193                        let used_index =
17194                            used_highlight_orders.entry(row).or_insert(highlight.index);
17195                        if highlight.index >= *used_index {
17196                            *used_index = highlight.index;
17197                            unique_rows.insert(
17198                                DisplayRow(row),
17199                                LineHighlight {
17200                                    include_gutter: highlight.options.include_gutter,
17201                                    border: None,
17202                                    background: highlight.color.into(),
17203                                    type_id: Some(highlight.type_id),
17204                                },
17205                            );
17206                        }
17207                    }
17208                    unique_rows
17209                },
17210            )
17211    }
17212
17213    pub fn highlighted_display_row_for_autoscroll(
17214        &self,
17215        snapshot: &DisplaySnapshot,
17216    ) -> Option<DisplayRow> {
17217        self.highlighted_rows
17218            .values()
17219            .flat_map(|highlighted_rows| highlighted_rows.iter())
17220            .filter_map(|highlight| {
17221                if highlight.options.autoscroll {
17222                    Some(highlight.range.start.to_display_point(snapshot).row())
17223                } else {
17224                    None
17225                }
17226            })
17227            .min()
17228    }
17229
17230    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17231        self.highlight_background::<SearchWithinRange>(
17232            ranges,
17233            |colors| colors.editor_document_highlight_read_background,
17234            cx,
17235        )
17236    }
17237
17238    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17239        self.breadcrumb_header = Some(new_header);
17240    }
17241
17242    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17243        self.clear_background_highlights::<SearchWithinRange>(cx);
17244    }
17245
17246    pub fn highlight_background<T: 'static>(
17247        &mut self,
17248        ranges: &[Range<Anchor>],
17249        color_fetcher: fn(&ThemeColors) -> Hsla,
17250        cx: &mut Context<Self>,
17251    ) {
17252        self.background_highlights
17253            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17254        self.scrollbar_marker_state.dirty = true;
17255        cx.notify();
17256    }
17257
17258    pub fn clear_background_highlights<T: 'static>(
17259        &mut self,
17260        cx: &mut Context<Self>,
17261    ) -> Option<BackgroundHighlight> {
17262        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17263        if !text_highlights.1.is_empty() {
17264            self.scrollbar_marker_state.dirty = true;
17265            cx.notify();
17266        }
17267        Some(text_highlights)
17268    }
17269
17270    pub fn highlight_gutter<T: 'static>(
17271        &mut self,
17272        ranges: &[Range<Anchor>],
17273        color_fetcher: fn(&App) -> Hsla,
17274        cx: &mut Context<Self>,
17275    ) {
17276        self.gutter_highlights
17277            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17278        cx.notify();
17279    }
17280
17281    pub fn clear_gutter_highlights<T: 'static>(
17282        &mut self,
17283        cx: &mut Context<Self>,
17284    ) -> Option<GutterHighlight> {
17285        cx.notify();
17286        self.gutter_highlights.remove(&TypeId::of::<T>())
17287    }
17288
17289    #[cfg(feature = "test-support")]
17290    pub fn all_text_background_highlights(
17291        &self,
17292        window: &mut Window,
17293        cx: &mut Context<Self>,
17294    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17295        let snapshot = self.snapshot(window, cx);
17296        let buffer = &snapshot.buffer_snapshot;
17297        let start = buffer.anchor_before(0);
17298        let end = buffer.anchor_after(buffer.len());
17299        let theme = cx.theme().colors();
17300        self.background_highlights_in_range(start..end, &snapshot, theme)
17301    }
17302
17303    #[cfg(feature = "test-support")]
17304    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17305        let snapshot = self.buffer().read(cx).snapshot(cx);
17306
17307        let highlights = self
17308            .background_highlights
17309            .get(&TypeId::of::<items::BufferSearchHighlights>());
17310
17311        if let Some((_color, ranges)) = highlights {
17312            ranges
17313                .iter()
17314                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17315                .collect_vec()
17316        } else {
17317            vec![]
17318        }
17319    }
17320
17321    fn document_highlights_for_position<'a>(
17322        &'a self,
17323        position: Anchor,
17324        buffer: &'a MultiBufferSnapshot,
17325    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17326        let read_highlights = self
17327            .background_highlights
17328            .get(&TypeId::of::<DocumentHighlightRead>())
17329            .map(|h| &h.1);
17330        let write_highlights = self
17331            .background_highlights
17332            .get(&TypeId::of::<DocumentHighlightWrite>())
17333            .map(|h| &h.1);
17334        let left_position = position.bias_left(buffer);
17335        let right_position = position.bias_right(buffer);
17336        read_highlights
17337            .into_iter()
17338            .chain(write_highlights)
17339            .flat_map(move |ranges| {
17340                let start_ix = match ranges.binary_search_by(|probe| {
17341                    let cmp = probe.end.cmp(&left_position, buffer);
17342                    if cmp.is_ge() {
17343                        Ordering::Greater
17344                    } else {
17345                        Ordering::Less
17346                    }
17347                }) {
17348                    Ok(i) | Err(i) => i,
17349                };
17350
17351                ranges[start_ix..]
17352                    .iter()
17353                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17354            })
17355    }
17356
17357    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17358        self.background_highlights
17359            .get(&TypeId::of::<T>())
17360            .map_or(false, |(_, highlights)| !highlights.is_empty())
17361    }
17362
17363    pub fn background_highlights_in_range(
17364        &self,
17365        search_range: Range<Anchor>,
17366        display_snapshot: &DisplaySnapshot,
17367        theme: &ThemeColors,
17368    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17369        let mut results = Vec::new();
17370        for (color_fetcher, ranges) in self.background_highlights.values() {
17371            let color = color_fetcher(theme);
17372            let start_ix = match ranges.binary_search_by(|probe| {
17373                let cmp = probe
17374                    .end
17375                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17376                if cmp.is_gt() {
17377                    Ordering::Greater
17378                } else {
17379                    Ordering::Less
17380                }
17381            }) {
17382                Ok(i) | Err(i) => i,
17383            };
17384            for range in &ranges[start_ix..] {
17385                if range
17386                    .start
17387                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17388                    .is_ge()
17389                {
17390                    break;
17391                }
17392
17393                let start = range.start.to_display_point(display_snapshot);
17394                let end = range.end.to_display_point(display_snapshot);
17395                results.push((start..end, color))
17396            }
17397        }
17398        results
17399    }
17400
17401    pub fn background_highlight_row_ranges<T: 'static>(
17402        &self,
17403        search_range: Range<Anchor>,
17404        display_snapshot: &DisplaySnapshot,
17405        count: usize,
17406    ) -> Vec<RangeInclusive<DisplayPoint>> {
17407        let mut results = Vec::new();
17408        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17409            return vec![];
17410        };
17411
17412        let start_ix = match ranges.binary_search_by(|probe| {
17413            let cmp = probe
17414                .end
17415                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17416            if cmp.is_gt() {
17417                Ordering::Greater
17418            } else {
17419                Ordering::Less
17420            }
17421        }) {
17422            Ok(i) | Err(i) => i,
17423        };
17424        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17425            if let (Some(start_display), Some(end_display)) = (start, end) {
17426                results.push(
17427                    start_display.to_display_point(display_snapshot)
17428                        ..=end_display.to_display_point(display_snapshot),
17429                );
17430            }
17431        };
17432        let mut start_row: Option<Point> = None;
17433        let mut end_row: Option<Point> = None;
17434        if ranges.len() > count {
17435            return Vec::new();
17436        }
17437        for range in &ranges[start_ix..] {
17438            if range
17439                .start
17440                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17441                .is_ge()
17442            {
17443                break;
17444            }
17445            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17446            if let Some(current_row) = &end_row {
17447                if end.row == current_row.row {
17448                    continue;
17449                }
17450            }
17451            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17452            if start_row.is_none() {
17453                assert_eq!(end_row, None);
17454                start_row = Some(start);
17455                end_row = Some(end);
17456                continue;
17457            }
17458            if let Some(current_end) = end_row.as_mut() {
17459                if start.row > current_end.row + 1 {
17460                    push_region(start_row, end_row);
17461                    start_row = Some(start);
17462                    end_row = Some(end);
17463                } else {
17464                    // Merge two hunks.
17465                    *current_end = end;
17466                }
17467            } else {
17468                unreachable!();
17469            }
17470        }
17471        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17472        push_region(start_row, end_row);
17473        results
17474    }
17475
17476    pub fn gutter_highlights_in_range(
17477        &self,
17478        search_range: Range<Anchor>,
17479        display_snapshot: &DisplaySnapshot,
17480        cx: &App,
17481    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17482        let mut results = Vec::new();
17483        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17484            let color = color_fetcher(cx);
17485            let start_ix = match ranges.binary_search_by(|probe| {
17486                let cmp = probe
17487                    .end
17488                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17489                if cmp.is_gt() {
17490                    Ordering::Greater
17491                } else {
17492                    Ordering::Less
17493                }
17494            }) {
17495                Ok(i) | Err(i) => i,
17496            };
17497            for range in &ranges[start_ix..] {
17498                if range
17499                    .start
17500                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17501                    .is_ge()
17502                {
17503                    break;
17504                }
17505
17506                let start = range.start.to_display_point(display_snapshot);
17507                let end = range.end.to_display_point(display_snapshot);
17508                results.push((start..end, color))
17509            }
17510        }
17511        results
17512    }
17513
17514    /// Get the text ranges corresponding to the redaction query
17515    pub fn redacted_ranges(
17516        &self,
17517        search_range: Range<Anchor>,
17518        display_snapshot: &DisplaySnapshot,
17519        cx: &App,
17520    ) -> Vec<Range<DisplayPoint>> {
17521        display_snapshot
17522            .buffer_snapshot
17523            .redacted_ranges(search_range, |file| {
17524                if let Some(file) = file {
17525                    file.is_private()
17526                        && EditorSettings::get(
17527                            Some(SettingsLocation {
17528                                worktree_id: file.worktree_id(cx),
17529                                path: file.path().as_ref(),
17530                            }),
17531                            cx,
17532                        )
17533                        .redact_private_values
17534                } else {
17535                    false
17536                }
17537            })
17538            .map(|range| {
17539                range.start.to_display_point(display_snapshot)
17540                    ..range.end.to_display_point(display_snapshot)
17541            })
17542            .collect()
17543    }
17544
17545    pub fn highlight_text<T: 'static>(
17546        &mut self,
17547        ranges: Vec<Range<Anchor>>,
17548        style: HighlightStyle,
17549        cx: &mut Context<Self>,
17550    ) {
17551        self.display_map.update(cx, |map, _| {
17552            map.highlight_text(TypeId::of::<T>(), ranges, style)
17553        });
17554        cx.notify();
17555    }
17556
17557    pub(crate) fn highlight_inlays<T: 'static>(
17558        &mut self,
17559        highlights: Vec<InlayHighlight>,
17560        style: HighlightStyle,
17561        cx: &mut Context<Self>,
17562    ) {
17563        self.display_map.update(cx, |map, _| {
17564            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17565        });
17566        cx.notify();
17567    }
17568
17569    pub fn text_highlights<'a, T: 'static>(
17570        &'a self,
17571        cx: &'a App,
17572    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17573        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17574    }
17575
17576    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17577        let cleared = self
17578            .display_map
17579            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17580        if cleared {
17581            cx.notify();
17582        }
17583    }
17584
17585    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17586        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17587            && self.focus_handle.is_focused(window)
17588    }
17589
17590    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17591        self.show_cursor_when_unfocused = is_enabled;
17592        cx.notify();
17593    }
17594
17595    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17596        cx.notify();
17597    }
17598
17599    fn on_debug_session_event(
17600        &mut self,
17601        _session: Entity<Session>,
17602        event: &SessionEvent,
17603        cx: &mut Context<Self>,
17604    ) {
17605        match event {
17606            SessionEvent::InvalidateInlineValue => {
17607                self.refresh_inline_values(cx);
17608            }
17609            _ => {}
17610        }
17611    }
17612
17613    pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17614        let Some(project) = self.project.clone() else {
17615            return;
17616        };
17617        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17618            return;
17619        };
17620        if !self.inline_value_cache.enabled {
17621            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17622            self.splice_inlays(&inlays, Vec::new(), cx);
17623            return;
17624        }
17625
17626        let current_execution_position = self
17627            .highlighted_rows
17628            .get(&TypeId::of::<ActiveDebugLine>())
17629            .and_then(|lines| lines.last().map(|line| line.range.start));
17630
17631        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17632            let snapshot = editor
17633                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17634                .ok()?;
17635
17636            let inline_values = editor
17637                .update(cx, |_, cx| {
17638                    let Some(current_execution_position) = current_execution_position else {
17639                        return Some(Task::ready(Ok(Vec::new())));
17640                    };
17641
17642                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17643                    // anchor is in the same buffer
17644                    let range =
17645                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17646                    project.inline_values(buffer, range, cx)
17647                })
17648                .ok()
17649                .flatten()?
17650                .await
17651                .context("refreshing debugger inlays")
17652                .log_err()?;
17653
17654            let (excerpt_id, buffer_id) = snapshot
17655                .excerpts()
17656                .next()
17657                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17658            editor
17659                .update(cx, |editor, cx| {
17660                    let new_inlays = inline_values
17661                        .into_iter()
17662                        .map(|debugger_value| {
17663                            Inlay::debugger_hint(
17664                                post_inc(&mut editor.next_inlay_id),
17665                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17666                                debugger_value.text(),
17667                            )
17668                        })
17669                        .collect::<Vec<_>>();
17670                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17671                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17672
17673                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17674                })
17675                .ok()?;
17676            Some(())
17677        });
17678    }
17679
17680    fn on_buffer_event(
17681        &mut self,
17682        multibuffer: &Entity<MultiBuffer>,
17683        event: &multi_buffer::Event,
17684        window: &mut Window,
17685        cx: &mut Context<Self>,
17686    ) {
17687        match event {
17688            multi_buffer::Event::Edited {
17689                singleton_buffer_edited,
17690                edited_buffer: buffer_edited,
17691            } => {
17692                self.scrollbar_marker_state.dirty = true;
17693                self.active_indent_guides_state.dirty = true;
17694                self.refresh_active_diagnostics(cx);
17695                self.refresh_code_actions(window, cx);
17696                self.refresh_selected_text_highlights(true, window, cx);
17697                refresh_matching_bracket_highlights(self, window, cx);
17698                if self.has_active_inline_completion() {
17699                    self.update_visible_inline_completion(window, cx);
17700                }
17701                if let Some(buffer) = buffer_edited {
17702                    let buffer_id = buffer.read(cx).remote_id();
17703                    if !self.registered_buffers.contains_key(&buffer_id) {
17704                        if let Some(project) = self.project.as_ref() {
17705                            project.update(cx, |project, cx| {
17706                                self.registered_buffers.insert(
17707                                    buffer_id,
17708                                    project.register_buffer_with_language_servers(&buffer, cx),
17709                                );
17710                            })
17711                        }
17712                    }
17713                }
17714                cx.emit(EditorEvent::BufferEdited);
17715                cx.emit(SearchEvent::MatchesInvalidated);
17716                if *singleton_buffer_edited {
17717                    if let Some(project) = &self.project {
17718                        #[allow(clippy::mutable_key_type)]
17719                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17720                            multibuffer
17721                                .all_buffers()
17722                                .into_iter()
17723                                .filter_map(|buffer| {
17724                                    buffer.update(cx, |buffer, cx| {
17725                                        let language = buffer.language()?;
17726                                        let should_discard = project.update(cx, |project, cx| {
17727                                            project.is_local()
17728                                                && !project.has_language_servers_for(buffer, cx)
17729                                        });
17730                                        should_discard.not().then_some(language.clone())
17731                                    })
17732                                })
17733                                .collect::<HashSet<_>>()
17734                        });
17735                        if !languages_affected.is_empty() {
17736                            self.refresh_inlay_hints(
17737                                InlayHintRefreshReason::BufferEdited(languages_affected),
17738                                cx,
17739                            );
17740                        }
17741                    }
17742                }
17743
17744                let Some(project) = &self.project else { return };
17745                let (telemetry, is_via_ssh) = {
17746                    let project = project.read(cx);
17747                    let telemetry = project.client().telemetry().clone();
17748                    let is_via_ssh = project.is_via_ssh();
17749                    (telemetry, is_via_ssh)
17750                };
17751                refresh_linked_ranges(self, window, cx);
17752                telemetry.log_edit_event("editor", is_via_ssh);
17753            }
17754            multi_buffer::Event::ExcerptsAdded {
17755                buffer,
17756                predecessor,
17757                excerpts,
17758            } => {
17759                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17760                let buffer_id = buffer.read(cx).remote_id();
17761                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17762                    if let Some(project) = &self.project {
17763                        update_uncommitted_diff_for_buffer(
17764                            cx.entity(),
17765                            project,
17766                            [buffer.clone()],
17767                            self.buffer.clone(),
17768                            cx,
17769                        )
17770                        .detach();
17771                    }
17772                }
17773                cx.emit(EditorEvent::ExcerptsAdded {
17774                    buffer: buffer.clone(),
17775                    predecessor: *predecessor,
17776                    excerpts: excerpts.clone(),
17777                });
17778                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17779            }
17780            multi_buffer::Event::ExcerptsRemoved {
17781                ids,
17782                removed_buffer_ids,
17783            } => {
17784                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17785                let buffer = self.buffer.read(cx);
17786                self.registered_buffers
17787                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17788                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17789                cx.emit(EditorEvent::ExcerptsRemoved {
17790                    ids: ids.clone(),
17791                    removed_buffer_ids: removed_buffer_ids.clone(),
17792                })
17793            }
17794            multi_buffer::Event::ExcerptsEdited {
17795                excerpt_ids,
17796                buffer_ids,
17797            } => {
17798                self.display_map.update(cx, |map, cx| {
17799                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17800                });
17801                cx.emit(EditorEvent::ExcerptsEdited {
17802                    ids: excerpt_ids.clone(),
17803                })
17804            }
17805            multi_buffer::Event::ExcerptsExpanded { ids } => {
17806                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17807                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17808            }
17809            multi_buffer::Event::Reparsed(buffer_id) => {
17810                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17811                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17812
17813                cx.emit(EditorEvent::Reparsed(*buffer_id));
17814            }
17815            multi_buffer::Event::DiffHunksToggled => {
17816                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17817            }
17818            multi_buffer::Event::LanguageChanged(buffer_id) => {
17819                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17820                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17821                cx.emit(EditorEvent::Reparsed(*buffer_id));
17822                cx.notify();
17823            }
17824            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17825            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17826            multi_buffer::Event::FileHandleChanged
17827            | multi_buffer::Event::Reloaded
17828            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17829            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17830            multi_buffer::Event::DiagnosticsUpdated => {
17831                self.refresh_active_diagnostics(cx);
17832                self.refresh_inline_diagnostics(true, window, cx);
17833                self.scrollbar_marker_state.dirty = true;
17834                cx.notify();
17835            }
17836            _ => {}
17837        };
17838    }
17839
17840    pub fn start_temporary_diff_override(&mut self) {
17841        self.load_diff_task.take();
17842        self.temporary_diff_override = true;
17843    }
17844
17845    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17846        self.temporary_diff_override = false;
17847        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17848        self.buffer.update(cx, |buffer, cx| {
17849            buffer.set_all_diff_hunks_collapsed(cx);
17850        });
17851
17852        if let Some(project) = self.project.clone() {
17853            self.load_diff_task = Some(
17854                update_uncommitted_diff_for_buffer(
17855                    cx.entity(),
17856                    &project,
17857                    self.buffer.read(cx).all_buffers(),
17858                    self.buffer.clone(),
17859                    cx,
17860                )
17861                .shared(),
17862            );
17863        }
17864    }
17865
17866    fn on_display_map_changed(
17867        &mut self,
17868        _: Entity<DisplayMap>,
17869        _: &mut Window,
17870        cx: &mut Context<Self>,
17871    ) {
17872        cx.notify();
17873    }
17874
17875    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17876        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17877        self.update_edit_prediction_settings(cx);
17878        self.refresh_inline_completion(true, false, window, cx);
17879        self.refresh_inlay_hints(
17880            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17881                self.selections.newest_anchor().head(),
17882                &self.buffer.read(cx).snapshot(cx),
17883                cx,
17884            )),
17885            cx,
17886        );
17887
17888        let old_cursor_shape = self.cursor_shape;
17889
17890        {
17891            let editor_settings = EditorSettings::get_global(cx);
17892            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17893            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17894            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17895            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17896        }
17897
17898        if old_cursor_shape != self.cursor_shape {
17899            cx.emit(EditorEvent::CursorShapeChanged);
17900        }
17901
17902        let project_settings = ProjectSettings::get_global(cx);
17903        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17904
17905        if self.mode.is_full() {
17906            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17907            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17908            if self.show_inline_diagnostics != show_inline_diagnostics {
17909                self.show_inline_diagnostics = show_inline_diagnostics;
17910                self.refresh_inline_diagnostics(false, window, cx);
17911            }
17912
17913            if self.git_blame_inline_enabled != inline_blame_enabled {
17914                self.toggle_git_blame_inline_internal(false, window, cx);
17915            }
17916        }
17917
17918        cx.notify();
17919    }
17920
17921    pub fn set_searchable(&mut self, searchable: bool) {
17922        self.searchable = searchable;
17923    }
17924
17925    pub fn searchable(&self) -> bool {
17926        self.searchable
17927    }
17928
17929    fn open_proposed_changes_editor(
17930        &mut self,
17931        _: &OpenProposedChangesEditor,
17932        window: &mut Window,
17933        cx: &mut Context<Self>,
17934    ) {
17935        let Some(workspace) = self.workspace() else {
17936            cx.propagate();
17937            return;
17938        };
17939
17940        let selections = self.selections.all::<usize>(cx);
17941        let multi_buffer = self.buffer.read(cx);
17942        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17943        let mut new_selections_by_buffer = HashMap::default();
17944        for selection in selections {
17945            for (buffer, range, _) in
17946                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17947            {
17948                let mut range = range.to_point(buffer);
17949                range.start.column = 0;
17950                range.end.column = buffer.line_len(range.end.row);
17951                new_selections_by_buffer
17952                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17953                    .or_insert(Vec::new())
17954                    .push(range)
17955            }
17956        }
17957
17958        let proposed_changes_buffers = new_selections_by_buffer
17959            .into_iter()
17960            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17961            .collect::<Vec<_>>();
17962        let proposed_changes_editor = cx.new(|cx| {
17963            ProposedChangesEditor::new(
17964                "Proposed changes",
17965                proposed_changes_buffers,
17966                self.project.clone(),
17967                window,
17968                cx,
17969            )
17970        });
17971
17972        window.defer(cx, move |window, cx| {
17973            workspace.update(cx, |workspace, cx| {
17974                workspace.active_pane().update(cx, |pane, cx| {
17975                    pane.add_item(
17976                        Box::new(proposed_changes_editor),
17977                        true,
17978                        true,
17979                        None,
17980                        window,
17981                        cx,
17982                    );
17983                });
17984            });
17985        });
17986    }
17987
17988    pub fn open_excerpts_in_split(
17989        &mut self,
17990        _: &OpenExcerptsSplit,
17991        window: &mut Window,
17992        cx: &mut Context<Self>,
17993    ) {
17994        self.open_excerpts_common(None, true, window, cx)
17995    }
17996
17997    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17998        self.open_excerpts_common(None, false, window, cx)
17999    }
18000
18001    fn open_excerpts_common(
18002        &mut self,
18003        jump_data: Option<JumpData>,
18004        split: bool,
18005        window: &mut Window,
18006        cx: &mut Context<Self>,
18007    ) {
18008        let Some(workspace) = self.workspace() else {
18009            cx.propagate();
18010            return;
18011        };
18012
18013        if self.buffer.read(cx).is_singleton() {
18014            cx.propagate();
18015            return;
18016        }
18017
18018        let mut new_selections_by_buffer = HashMap::default();
18019        match &jump_data {
18020            Some(JumpData::MultiBufferPoint {
18021                excerpt_id,
18022                position,
18023                anchor,
18024                line_offset_from_top,
18025            }) => {
18026                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18027                if let Some(buffer) = multi_buffer_snapshot
18028                    .buffer_id_for_excerpt(*excerpt_id)
18029                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18030                {
18031                    let buffer_snapshot = buffer.read(cx).snapshot();
18032                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18033                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18034                    } else {
18035                        buffer_snapshot.clip_point(*position, Bias::Left)
18036                    };
18037                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18038                    new_selections_by_buffer.insert(
18039                        buffer,
18040                        (
18041                            vec![jump_to_offset..jump_to_offset],
18042                            Some(*line_offset_from_top),
18043                        ),
18044                    );
18045                }
18046            }
18047            Some(JumpData::MultiBufferRow {
18048                row,
18049                line_offset_from_top,
18050            }) => {
18051                let point = MultiBufferPoint::new(row.0, 0);
18052                if let Some((buffer, buffer_point, _)) =
18053                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18054                {
18055                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18056                    new_selections_by_buffer
18057                        .entry(buffer)
18058                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18059                        .0
18060                        .push(buffer_offset..buffer_offset)
18061                }
18062            }
18063            None => {
18064                let selections = self.selections.all::<usize>(cx);
18065                let multi_buffer = self.buffer.read(cx);
18066                for selection in selections {
18067                    for (snapshot, range, _, anchor) in multi_buffer
18068                        .snapshot(cx)
18069                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18070                    {
18071                        if let Some(anchor) = anchor {
18072                            // selection is in a deleted hunk
18073                            let Some(buffer_id) = anchor.buffer_id else {
18074                                continue;
18075                            };
18076                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18077                                continue;
18078                            };
18079                            let offset = text::ToOffset::to_offset(
18080                                &anchor.text_anchor,
18081                                &buffer_handle.read(cx).snapshot(),
18082                            );
18083                            let range = offset..offset;
18084                            new_selections_by_buffer
18085                                .entry(buffer_handle)
18086                                .or_insert((Vec::new(), None))
18087                                .0
18088                                .push(range)
18089                        } else {
18090                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18091                            else {
18092                                continue;
18093                            };
18094                            new_selections_by_buffer
18095                                .entry(buffer_handle)
18096                                .or_insert((Vec::new(), None))
18097                                .0
18098                                .push(range)
18099                        }
18100                    }
18101                }
18102            }
18103        }
18104
18105        new_selections_by_buffer
18106            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18107
18108        if new_selections_by_buffer.is_empty() {
18109            return;
18110        }
18111
18112        // We defer the pane interaction because we ourselves are a workspace item
18113        // and activating a new item causes the pane to call a method on us reentrantly,
18114        // which panics if we're on the stack.
18115        window.defer(cx, move |window, cx| {
18116            workspace.update(cx, |workspace, cx| {
18117                let pane = if split {
18118                    workspace.adjacent_pane(window, cx)
18119                } else {
18120                    workspace.active_pane().clone()
18121                };
18122
18123                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18124                    let editor = buffer
18125                        .read(cx)
18126                        .file()
18127                        .is_none()
18128                        .then(|| {
18129                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18130                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18131                            // Instead, we try to activate the existing editor in the pane first.
18132                            let (editor, pane_item_index) =
18133                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18134                                    let editor = item.downcast::<Editor>()?;
18135                                    let singleton_buffer =
18136                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18137                                    if singleton_buffer == buffer {
18138                                        Some((editor, i))
18139                                    } else {
18140                                        None
18141                                    }
18142                                })?;
18143                            pane.update(cx, |pane, cx| {
18144                                pane.activate_item(pane_item_index, true, true, window, cx)
18145                            });
18146                            Some(editor)
18147                        })
18148                        .flatten()
18149                        .unwrap_or_else(|| {
18150                            workspace.open_project_item::<Self>(
18151                                pane.clone(),
18152                                buffer,
18153                                true,
18154                                true,
18155                                window,
18156                                cx,
18157                            )
18158                        });
18159
18160                    editor.update(cx, |editor, cx| {
18161                        let autoscroll = match scroll_offset {
18162                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18163                            None => Autoscroll::newest(),
18164                        };
18165                        let nav_history = editor.nav_history.take();
18166                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18167                            s.select_ranges(ranges);
18168                        });
18169                        editor.nav_history = nav_history;
18170                    });
18171                }
18172            })
18173        });
18174    }
18175
18176    // For now, don't allow opening excerpts in buffers that aren't backed by
18177    // regular project files.
18178    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18179        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18180    }
18181
18182    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18183        let snapshot = self.buffer.read(cx).read(cx);
18184        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18185        Some(
18186            ranges
18187                .iter()
18188                .map(move |range| {
18189                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18190                })
18191                .collect(),
18192        )
18193    }
18194
18195    fn selection_replacement_ranges(
18196        &self,
18197        range: Range<OffsetUtf16>,
18198        cx: &mut App,
18199    ) -> Vec<Range<OffsetUtf16>> {
18200        let selections = self.selections.all::<OffsetUtf16>(cx);
18201        let newest_selection = selections
18202            .iter()
18203            .max_by_key(|selection| selection.id)
18204            .unwrap();
18205        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18206        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18207        let snapshot = self.buffer.read(cx).read(cx);
18208        selections
18209            .into_iter()
18210            .map(|mut selection| {
18211                selection.start.0 =
18212                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18213                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18214                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18215                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18216            })
18217            .collect()
18218    }
18219
18220    fn report_editor_event(
18221        &self,
18222        event_type: &'static str,
18223        file_extension: Option<String>,
18224        cx: &App,
18225    ) {
18226        if cfg!(any(test, feature = "test-support")) {
18227            return;
18228        }
18229
18230        let Some(project) = &self.project else { return };
18231
18232        // If None, we are in a file without an extension
18233        let file = self
18234            .buffer
18235            .read(cx)
18236            .as_singleton()
18237            .and_then(|b| b.read(cx).file());
18238        let file_extension = file_extension.or(file
18239            .as_ref()
18240            .and_then(|file| Path::new(file.file_name(cx)).extension())
18241            .and_then(|e| e.to_str())
18242            .map(|a| a.to_string()));
18243
18244        let vim_mode = vim_enabled(cx);
18245
18246        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18247        let copilot_enabled = edit_predictions_provider
18248            == language::language_settings::EditPredictionProvider::Copilot;
18249        let copilot_enabled_for_language = self
18250            .buffer
18251            .read(cx)
18252            .language_settings(cx)
18253            .show_edit_predictions;
18254
18255        let project = project.read(cx);
18256        telemetry::event!(
18257            event_type,
18258            file_extension,
18259            vim_mode,
18260            copilot_enabled,
18261            copilot_enabled_for_language,
18262            edit_predictions_provider,
18263            is_via_ssh = project.is_via_ssh(),
18264        );
18265    }
18266
18267    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18268    /// with each line being an array of {text, highlight} objects.
18269    fn copy_highlight_json(
18270        &mut self,
18271        _: &CopyHighlightJson,
18272        window: &mut Window,
18273        cx: &mut Context<Self>,
18274    ) {
18275        #[derive(Serialize)]
18276        struct Chunk<'a> {
18277            text: String,
18278            highlight: Option<&'a str>,
18279        }
18280
18281        let snapshot = self.buffer.read(cx).snapshot(cx);
18282        let range = self
18283            .selected_text_range(false, window, cx)
18284            .and_then(|selection| {
18285                if selection.range.is_empty() {
18286                    None
18287                } else {
18288                    Some(selection.range)
18289                }
18290            })
18291            .unwrap_or_else(|| 0..snapshot.len());
18292
18293        let chunks = snapshot.chunks(range, true);
18294        let mut lines = Vec::new();
18295        let mut line: VecDeque<Chunk> = VecDeque::new();
18296
18297        let Some(style) = self.style.as_ref() else {
18298            return;
18299        };
18300
18301        for chunk in chunks {
18302            let highlight = chunk
18303                .syntax_highlight_id
18304                .and_then(|id| id.name(&style.syntax));
18305            let mut chunk_lines = chunk.text.split('\n').peekable();
18306            while let Some(text) = chunk_lines.next() {
18307                let mut merged_with_last_token = false;
18308                if let Some(last_token) = line.back_mut() {
18309                    if last_token.highlight == highlight {
18310                        last_token.text.push_str(text);
18311                        merged_with_last_token = true;
18312                    }
18313                }
18314
18315                if !merged_with_last_token {
18316                    line.push_back(Chunk {
18317                        text: text.into(),
18318                        highlight,
18319                    });
18320                }
18321
18322                if chunk_lines.peek().is_some() {
18323                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18324                        line.pop_front();
18325                    }
18326                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18327                        line.pop_back();
18328                    }
18329
18330                    lines.push(mem::take(&mut line));
18331                }
18332            }
18333        }
18334
18335        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18336            return;
18337        };
18338        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18339    }
18340
18341    pub fn open_context_menu(
18342        &mut self,
18343        _: &OpenContextMenu,
18344        window: &mut Window,
18345        cx: &mut Context<Self>,
18346    ) {
18347        self.request_autoscroll(Autoscroll::newest(), cx);
18348        let position = self.selections.newest_display(cx).start;
18349        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18350    }
18351
18352    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18353        &self.inlay_hint_cache
18354    }
18355
18356    pub fn replay_insert_event(
18357        &mut self,
18358        text: &str,
18359        relative_utf16_range: Option<Range<isize>>,
18360        window: &mut Window,
18361        cx: &mut Context<Self>,
18362    ) {
18363        if !self.input_enabled {
18364            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18365            return;
18366        }
18367        if let Some(relative_utf16_range) = relative_utf16_range {
18368            let selections = self.selections.all::<OffsetUtf16>(cx);
18369            self.change_selections(None, window, cx, |s| {
18370                let new_ranges = selections.into_iter().map(|range| {
18371                    let start = OffsetUtf16(
18372                        range
18373                            .head()
18374                            .0
18375                            .saturating_add_signed(relative_utf16_range.start),
18376                    );
18377                    let end = OffsetUtf16(
18378                        range
18379                            .head()
18380                            .0
18381                            .saturating_add_signed(relative_utf16_range.end),
18382                    );
18383                    start..end
18384                });
18385                s.select_ranges(new_ranges);
18386            });
18387        }
18388
18389        self.handle_input(text, window, cx);
18390    }
18391
18392    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18393        let Some(provider) = self.semantics_provider.as_ref() else {
18394            return false;
18395        };
18396
18397        let mut supports = false;
18398        self.buffer().update(cx, |this, cx| {
18399            this.for_each_buffer(|buffer| {
18400                supports |= provider.supports_inlay_hints(buffer, cx);
18401            });
18402        });
18403
18404        supports
18405    }
18406
18407    pub fn is_focused(&self, window: &Window) -> bool {
18408        self.focus_handle.is_focused(window)
18409    }
18410
18411    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18412        cx.emit(EditorEvent::Focused);
18413
18414        if let Some(descendant) = self
18415            .last_focused_descendant
18416            .take()
18417            .and_then(|descendant| descendant.upgrade())
18418        {
18419            window.focus(&descendant);
18420        } else {
18421            if let Some(blame) = self.blame.as_ref() {
18422                blame.update(cx, GitBlame::focus)
18423            }
18424
18425            self.blink_manager.update(cx, BlinkManager::enable);
18426            self.show_cursor_names(window, cx);
18427            self.buffer.update(cx, |buffer, cx| {
18428                buffer.finalize_last_transaction(cx);
18429                if self.leader_id.is_none() {
18430                    buffer.set_active_selections(
18431                        &self.selections.disjoint_anchors(),
18432                        self.selections.line_mode,
18433                        self.cursor_shape,
18434                        cx,
18435                    );
18436                }
18437            });
18438        }
18439    }
18440
18441    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18442        cx.emit(EditorEvent::FocusedIn)
18443    }
18444
18445    fn handle_focus_out(
18446        &mut self,
18447        event: FocusOutEvent,
18448        _window: &mut Window,
18449        cx: &mut Context<Self>,
18450    ) {
18451        if event.blurred != self.focus_handle {
18452            self.last_focused_descendant = Some(event.blurred);
18453        }
18454        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18455    }
18456
18457    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18458        self.blink_manager.update(cx, BlinkManager::disable);
18459        self.buffer
18460            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18461
18462        if let Some(blame) = self.blame.as_ref() {
18463            blame.update(cx, GitBlame::blur)
18464        }
18465        if !self.hover_state.focused(window, cx) {
18466            hide_hover(self, cx);
18467        }
18468        if !self
18469            .context_menu
18470            .borrow()
18471            .as_ref()
18472            .is_some_and(|context_menu| context_menu.focused(window, cx))
18473        {
18474            self.hide_context_menu(window, cx);
18475        }
18476        self.discard_inline_completion(false, cx);
18477        cx.emit(EditorEvent::Blurred);
18478        cx.notify();
18479    }
18480
18481    pub fn register_action<A: Action>(
18482        &mut self,
18483        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18484    ) -> Subscription {
18485        let id = self.next_editor_action_id.post_inc();
18486        let listener = Arc::new(listener);
18487        self.editor_actions.borrow_mut().insert(
18488            id,
18489            Box::new(move |window, _| {
18490                let listener = listener.clone();
18491                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18492                    let action = action.downcast_ref().unwrap();
18493                    if phase == DispatchPhase::Bubble {
18494                        listener(action, window, cx)
18495                    }
18496                })
18497            }),
18498        );
18499
18500        let editor_actions = self.editor_actions.clone();
18501        Subscription::new(move || {
18502            editor_actions.borrow_mut().remove(&id);
18503        })
18504    }
18505
18506    pub fn file_header_size(&self) -> u32 {
18507        FILE_HEADER_HEIGHT
18508    }
18509
18510    pub fn restore(
18511        &mut self,
18512        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18513        window: &mut Window,
18514        cx: &mut Context<Self>,
18515    ) {
18516        let workspace = self.workspace();
18517        let project = self.project.as_ref();
18518        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18519            let mut tasks = Vec::new();
18520            for (buffer_id, changes) in revert_changes {
18521                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18522                    buffer.update(cx, |buffer, cx| {
18523                        buffer.edit(
18524                            changes
18525                                .into_iter()
18526                                .map(|(range, text)| (range, text.to_string())),
18527                            None,
18528                            cx,
18529                        );
18530                    });
18531
18532                    if let Some(project) =
18533                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18534                    {
18535                        project.update(cx, |project, cx| {
18536                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18537                        })
18538                    }
18539                }
18540            }
18541            tasks
18542        });
18543        cx.spawn_in(window, async move |_, cx| {
18544            for (buffer, task) in save_tasks {
18545                let result = task.await;
18546                if result.is_err() {
18547                    let Some(path) = buffer
18548                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18549                        .ok()
18550                    else {
18551                        continue;
18552                    };
18553                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18554                        let Some(task) = cx
18555                            .update_window_entity(&workspace, |workspace, window, cx| {
18556                                workspace
18557                                    .open_path_preview(path, None, false, false, false, window, cx)
18558                            })
18559                            .ok()
18560                        else {
18561                            continue;
18562                        };
18563                        task.await.log_err();
18564                    }
18565                }
18566            }
18567        })
18568        .detach();
18569        self.change_selections(None, window, cx, |selections| selections.refresh());
18570    }
18571
18572    pub fn to_pixel_point(
18573        &self,
18574        source: multi_buffer::Anchor,
18575        editor_snapshot: &EditorSnapshot,
18576        window: &mut Window,
18577    ) -> Option<gpui::Point<Pixels>> {
18578        let source_point = source.to_display_point(editor_snapshot);
18579        self.display_to_pixel_point(source_point, editor_snapshot, window)
18580    }
18581
18582    pub fn display_to_pixel_point(
18583        &self,
18584        source: DisplayPoint,
18585        editor_snapshot: &EditorSnapshot,
18586        window: &mut Window,
18587    ) -> Option<gpui::Point<Pixels>> {
18588        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18589        let text_layout_details = self.text_layout_details(window);
18590        let scroll_top = text_layout_details
18591            .scroll_anchor
18592            .scroll_position(editor_snapshot)
18593            .y;
18594
18595        if source.row().as_f32() < scroll_top.floor() {
18596            return None;
18597        }
18598        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18599        let source_y = line_height * (source.row().as_f32() - scroll_top);
18600        Some(gpui::Point::new(source_x, source_y))
18601    }
18602
18603    pub fn has_visible_completions_menu(&self) -> bool {
18604        !self.edit_prediction_preview_is_active()
18605            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18606                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18607            })
18608    }
18609
18610    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18611        self.addons
18612            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18613    }
18614
18615    pub fn unregister_addon<T: Addon>(&mut self) {
18616        self.addons.remove(&std::any::TypeId::of::<T>());
18617    }
18618
18619    pub fn addon<T: Addon>(&self) -> Option<&T> {
18620        let type_id = std::any::TypeId::of::<T>();
18621        self.addons
18622            .get(&type_id)
18623            .and_then(|item| item.to_any().downcast_ref::<T>())
18624    }
18625
18626    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18627        let type_id = std::any::TypeId::of::<T>();
18628        self.addons
18629            .get_mut(&type_id)
18630            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18631    }
18632
18633    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18634        let text_layout_details = self.text_layout_details(window);
18635        let style = &text_layout_details.editor_style;
18636        let font_id = window.text_system().resolve_font(&style.text.font());
18637        let font_size = style.text.font_size.to_pixels(window.rem_size());
18638        let line_height = style.text.line_height_in_pixels(window.rem_size());
18639        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18640
18641        gpui::Size::new(em_width, line_height)
18642    }
18643
18644    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18645        self.load_diff_task.clone()
18646    }
18647
18648    fn read_metadata_from_db(
18649        &mut self,
18650        item_id: u64,
18651        workspace_id: WorkspaceId,
18652        window: &mut Window,
18653        cx: &mut Context<Editor>,
18654    ) {
18655        if self.is_singleton(cx)
18656            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18657        {
18658            let buffer_snapshot = OnceCell::new();
18659
18660            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18661                if !folds.is_empty() {
18662                    let snapshot =
18663                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18664                    self.fold_ranges(
18665                        folds
18666                            .into_iter()
18667                            .map(|(start, end)| {
18668                                snapshot.clip_offset(start, Bias::Left)
18669                                    ..snapshot.clip_offset(end, Bias::Right)
18670                            })
18671                            .collect(),
18672                        false,
18673                        window,
18674                        cx,
18675                    );
18676                }
18677            }
18678
18679            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18680                if !selections.is_empty() {
18681                    let snapshot =
18682                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18683                    self.change_selections(None, window, cx, |s| {
18684                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18685                            snapshot.clip_offset(start, Bias::Left)
18686                                ..snapshot.clip_offset(end, Bias::Right)
18687                        }));
18688                    });
18689                }
18690            };
18691        }
18692
18693        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18694    }
18695}
18696
18697fn vim_enabled(cx: &App) -> bool {
18698    cx.global::<SettingsStore>()
18699        .raw_user_settings()
18700        .get("vim_mode")
18701        == Some(&serde_json::Value::Bool(true))
18702}
18703
18704// Consider user intent and default settings
18705fn choose_completion_range(
18706    completion: &Completion,
18707    intent: CompletionIntent,
18708    buffer: &Entity<Buffer>,
18709    cx: &mut Context<Editor>,
18710) -> Range<usize> {
18711    fn should_replace(
18712        completion: &Completion,
18713        insert_range: &Range<text::Anchor>,
18714        intent: CompletionIntent,
18715        completion_mode_setting: LspInsertMode,
18716        buffer: &Buffer,
18717    ) -> bool {
18718        // specific actions take precedence over settings
18719        match intent {
18720            CompletionIntent::CompleteWithInsert => return false,
18721            CompletionIntent::CompleteWithReplace => return true,
18722            CompletionIntent::Complete | CompletionIntent::Compose => {}
18723        }
18724
18725        match completion_mode_setting {
18726            LspInsertMode::Insert => false,
18727            LspInsertMode::Replace => true,
18728            LspInsertMode::ReplaceSubsequence => {
18729                let mut text_to_replace = buffer.chars_for_range(
18730                    buffer.anchor_before(completion.replace_range.start)
18731                        ..buffer.anchor_after(completion.replace_range.end),
18732                );
18733                let mut completion_text = completion.new_text.chars();
18734
18735                // is `text_to_replace` a subsequence of `completion_text`
18736                text_to_replace
18737                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18738            }
18739            LspInsertMode::ReplaceSuffix => {
18740                let range_after_cursor = insert_range.end..completion.replace_range.end;
18741
18742                let text_after_cursor = buffer
18743                    .text_for_range(
18744                        buffer.anchor_before(range_after_cursor.start)
18745                            ..buffer.anchor_after(range_after_cursor.end),
18746                    )
18747                    .collect::<String>();
18748                completion.new_text.ends_with(&text_after_cursor)
18749            }
18750        }
18751    }
18752
18753    let buffer = buffer.read(cx);
18754
18755    if let CompletionSource::Lsp {
18756        insert_range: Some(insert_range),
18757        ..
18758    } = &completion.source
18759    {
18760        let completion_mode_setting =
18761            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18762                .completions
18763                .lsp_insert_mode;
18764
18765        if !should_replace(
18766            completion,
18767            &insert_range,
18768            intent,
18769            completion_mode_setting,
18770            buffer,
18771        ) {
18772            return insert_range.to_offset(buffer);
18773        }
18774    }
18775
18776    completion.replace_range.to_offset(buffer)
18777}
18778
18779fn insert_extra_newline_brackets(
18780    buffer: &MultiBufferSnapshot,
18781    range: Range<usize>,
18782    language: &language::LanguageScope,
18783) -> bool {
18784    let leading_whitespace_len = buffer
18785        .reversed_chars_at(range.start)
18786        .take_while(|c| c.is_whitespace() && *c != '\n')
18787        .map(|c| c.len_utf8())
18788        .sum::<usize>();
18789    let trailing_whitespace_len = buffer
18790        .chars_at(range.end)
18791        .take_while(|c| c.is_whitespace() && *c != '\n')
18792        .map(|c| c.len_utf8())
18793        .sum::<usize>();
18794    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18795
18796    language.brackets().any(|(pair, enabled)| {
18797        let pair_start = pair.start.trim_end();
18798        let pair_end = pair.end.trim_start();
18799
18800        enabled
18801            && pair.newline
18802            && buffer.contains_str_at(range.end, pair_end)
18803            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18804    })
18805}
18806
18807fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18808    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18809        [(buffer, range, _)] => (*buffer, range.clone()),
18810        _ => return false,
18811    };
18812    let pair = {
18813        let mut result: Option<BracketMatch> = None;
18814
18815        for pair in buffer
18816            .all_bracket_ranges(range.clone())
18817            .filter(move |pair| {
18818                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18819            })
18820        {
18821            let len = pair.close_range.end - pair.open_range.start;
18822
18823            if let Some(existing) = &result {
18824                let existing_len = existing.close_range.end - existing.open_range.start;
18825                if len > existing_len {
18826                    continue;
18827                }
18828            }
18829
18830            result = Some(pair);
18831        }
18832
18833        result
18834    };
18835    let Some(pair) = pair else {
18836        return false;
18837    };
18838    pair.newline_only
18839        && buffer
18840            .chars_for_range(pair.open_range.end..range.start)
18841            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18842            .all(|c| c.is_whitespace() && c != '\n')
18843}
18844
18845fn update_uncommitted_diff_for_buffer(
18846    editor: Entity<Editor>,
18847    project: &Entity<Project>,
18848    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18849    buffer: Entity<MultiBuffer>,
18850    cx: &mut App,
18851) -> Task<()> {
18852    let mut tasks = Vec::new();
18853    project.update(cx, |project, cx| {
18854        for buffer in buffers {
18855            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18856                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18857            }
18858        }
18859    });
18860    cx.spawn(async move |cx| {
18861        let diffs = future::join_all(tasks).await;
18862        if editor
18863            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18864            .unwrap_or(false)
18865        {
18866            return;
18867        }
18868
18869        buffer
18870            .update(cx, |buffer, cx| {
18871                for diff in diffs.into_iter().flatten() {
18872                    buffer.add_diff(diff, cx);
18873                }
18874            })
18875            .ok();
18876    })
18877}
18878
18879fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18880    let tab_size = tab_size.get() as usize;
18881    let mut width = offset;
18882
18883    for ch in text.chars() {
18884        width += if ch == '\t' {
18885            tab_size - (width % tab_size)
18886        } else {
18887            1
18888        };
18889    }
18890
18891    width - offset
18892}
18893
18894#[cfg(test)]
18895mod tests {
18896    use super::*;
18897
18898    #[test]
18899    fn test_string_size_with_expanded_tabs() {
18900        let nz = |val| NonZeroU32::new(val).unwrap();
18901        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18902        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18903        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18904        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18905        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18906        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18907        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18908        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18909    }
18910}
18911
18912/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18913struct WordBreakingTokenizer<'a> {
18914    input: &'a str,
18915}
18916
18917impl<'a> WordBreakingTokenizer<'a> {
18918    fn new(input: &'a str) -> Self {
18919        Self { input }
18920    }
18921}
18922
18923fn is_char_ideographic(ch: char) -> bool {
18924    use unicode_script::Script::*;
18925    use unicode_script::UnicodeScript;
18926    matches!(ch.script(), Han | Tangut | Yi)
18927}
18928
18929fn is_grapheme_ideographic(text: &str) -> bool {
18930    text.chars().any(is_char_ideographic)
18931}
18932
18933fn is_grapheme_whitespace(text: &str) -> bool {
18934    text.chars().any(|x| x.is_whitespace())
18935}
18936
18937fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18938    text.chars().next().map_or(false, |ch| {
18939        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18940    })
18941}
18942
18943#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18944enum WordBreakToken<'a> {
18945    Word { token: &'a str, grapheme_len: usize },
18946    InlineWhitespace { token: &'a str, grapheme_len: usize },
18947    Newline,
18948}
18949
18950impl<'a> Iterator for WordBreakingTokenizer<'a> {
18951    /// Yields a span, the count of graphemes in the token, and whether it was
18952    /// whitespace. Note that it also breaks at word boundaries.
18953    type Item = WordBreakToken<'a>;
18954
18955    fn next(&mut self) -> Option<Self::Item> {
18956        use unicode_segmentation::UnicodeSegmentation;
18957        if self.input.is_empty() {
18958            return None;
18959        }
18960
18961        let mut iter = self.input.graphemes(true).peekable();
18962        let mut offset = 0;
18963        let mut grapheme_len = 0;
18964        if let Some(first_grapheme) = iter.next() {
18965            let is_newline = first_grapheme == "\n";
18966            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18967            offset += first_grapheme.len();
18968            grapheme_len += 1;
18969            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18970                if let Some(grapheme) = iter.peek().copied() {
18971                    if should_stay_with_preceding_ideograph(grapheme) {
18972                        offset += grapheme.len();
18973                        grapheme_len += 1;
18974                    }
18975                }
18976            } else {
18977                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18978                let mut next_word_bound = words.peek().copied();
18979                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18980                    next_word_bound = words.next();
18981                }
18982                while let Some(grapheme) = iter.peek().copied() {
18983                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18984                        break;
18985                    };
18986                    if is_grapheme_whitespace(grapheme) != is_whitespace
18987                        || (grapheme == "\n") != is_newline
18988                    {
18989                        break;
18990                    };
18991                    offset += grapheme.len();
18992                    grapheme_len += 1;
18993                    iter.next();
18994                }
18995            }
18996            let token = &self.input[..offset];
18997            self.input = &self.input[offset..];
18998            if token == "\n" {
18999                Some(WordBreakToken::Newline)
19000            } else if is_whitespace {
19001                Some(WordBreakToken::InlineWhitespace {
19002                    token,
19003                    grapheme_len,
19004                })
19005            } else {
19006                Some(WordBreakToken::Word {
19007                    token,
19008                    grapheme_len,
19009                })
19010            }
19011        } else {
19012            None
19013        }
19014    }
19015}
19016
19017#[test]
19018fn test_word_breaking_tokenizer() {
19019    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19020        ("", &[]),
19021        ("  ", &[whitespace("  ", 2)]),
19022        ("Ʒ", &[word("Ʒ", 1)]),
19023        ("Ǽ", &[word("Ǽ", 1)]),
19024        ("", &[word("", 1)]),
19025        ("⋑⋑", &[word("⋑⋑", 2)]),
19026        (
19027            "原理,进而",
19028            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19029        ),
19030        (
19031            "hello world",
19032            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19033        ),
19034        (
19035            "hello, world",
19036            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19037        ),
19038        (
19039            "  hello world",
19040            &[
19041                whitespace("  ", 2),
19042                word("hello", 5),
19043                whitespace(" ", 1),
19044                word("world", 5),
19045            ],
19046        ),
19047        (
19048            "这是什么 \n 钢笔",
19049            &[
19050                word("", 1),
19051                word("", 1),
19052                word("", 1),
19053                word("", 1),
19054                whitespace(" ", 1),
19055                newline(),
19056                whitespace(" ", 1),
19057                word("", 1),
19058                word("", 1),
19059            ],
19060        ),
19061        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19062    ];
19063
19064    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19065        WordBreakToken::Word {
19066            token,
19067            grapheme_len,
19068        }
19069    }
19070
19071    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19072        WordBreakToken::InlineWhitespace {
19073            token,
19074            grapheme_len,
19075        }
19076    }
19077
19078    fn newline() -> WordBreakToken<'static> {
19079        WordBreakToken::Newline
19080    }
19081
19082    for (input, result) in tests {
19083        assert_eq!(
19084            WordBreakingTokenizer::new(input)
19085                .collect::<Vec<_>>()
19086                .as_slice(),
19087            *result,
19088        );
19089    }
19090}
19091
19092fn wrap_with_prefix(
19093    line_prefix: String,
19094    unwrapped_text: String,
19095    wrap_column: usize,
19096    tab_size: NonZeroU32,
19097    preserve_existing_whitespace: bool,
19098) -> String {
19099    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19100    let mut wrapped_text = String::new();
19101    let mut current_line = line_prefix.clone();
19102
19103    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19104    let mut current_line_len = line_prefix_len;
19105    let mut in_whitespace = false;
19106    for token in tokenizer {
19107        let have_preceding_whitespace = in_whitespace;
19108        match token {
19109            WordBreakToken::Word {
19110                token,
19111                grapheme_len,
19112            } => {
19113                in_whitespace = false;
19114                if current_line_len + grapheme_len > wrap_column
19115                    && current_line_len != line_prefix_len
19116                {
19117                    wrapped_text.push_str(current_line.trim_end());
19118                    wrapped_text.push('\n');
19119                    current_line.truncate(line_prefix.len());
19120                    current_line_len = line_prefix_len;
19121                }
19122                current_line.push_str(token);
19123                current_line_len += grapheme_len;
19124            }
19125            WordBreakToken::InlineWhitespace {
19126                mut token,
19127                mut grapheme_len,
19128            } => {
19129                in_whitespace = true;
19130                if have_preceding_whitespace && !preserve_existing_whitespace {
19131                    continue;
19132                }
19133                if !preserve_existing_whitespace {
19134                    token = " ";
19135                    grapheme_len = 1;
19136                }
19137                if current_line_len + grapheme_len > wrap_column {
19138                    wrapped_text.push_str(current_line.trim_end());
19139                    wrapped_text.push('\n');
19140                    current_line.truncate(line_prefix.len());
19141                    current_line_len = line_prefix_len;
19142                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19143                    current_line.push_str(token);
19144                    current_line_len += grapheme_len;
19145                }
19146            }
19147            WordBreakToken::Newline => {
19148                in_whitespace = true;
19149                if preserve_existing_whitespace {
19150                    wrapped_text.push_str(current_line.trim_end());
19151                    wrapped_text.push('\n');
19152                    current_line.truncate(line_prefix.len());
19153                    current_line_len = line_prefix_len;
19154                } else if have_preceding_whitespace {
19155                    continue;
19156                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19157                {
19158                    wrapped_text.push_str(current_line.trim_end());
19159                    wrapped_text.push('\n');
19160                    current_line.truncate(line_prefix.len());
19161                    current_line_len = line_prefix_len;
19162                } else if current_line_len != line_prefix_len {
19163                    current_line.push(' ');
19164                    current_line_len += 1;
19165                }
19166            }
19167        }
19168    }
19169
19170    if !current_line.is_empty() {
19171        wrapped_text.push_str(&current_line);
19172    }
19173    wrapped_text
19174}
19175
19176#[test]
19177fn test_wrap_with_prefix() {
19178    assert_eq!(
19179        wrap_with_prefix(
19180            "# ".to_string(),
19181            "abcdefg".to_string(),
19182            4,
19183            NonZeroU32::new(4).unwrap(),
19184            false,
19185        ),
19186        "# abcdefg"
19187    );
19188    assert_eq!(
19189        wrap_with_prefix(
19190            "".to_string(),
19191            "\thello world".to_string(),
19192            8,
19193            NonZeroU32::new(4).unwrap(),
19194            false,
19195        ),
19196        "hello\nworld"
19197    );
19198    assert_eq!(
19199        wrap_with_prefix(
19200            "// ".to_string(),
19201            "xx \nyy zz aa bb cc".to_string(),
19202            12,
19203            NonZeroU32::new(4).unwrap(),
19204            false,
19205        ),
19206        "// xx yy zz\n// aa bb cc"
19207    );
19208    assert_eq!(
19209        wrap_with_prefix(
19210            String::new(),
19211            "这是什么 \n 钢笔".to_string(),
19212            3,
19213            NonZeroU32::new(4).unwrap(),
19214            false,
19215        ),
19216        "这是什\n么 钢\n"
19217    );
19218}
19219
19220pub trait CollaborationHub {
19221    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19222    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19223    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19224}
19225
19226impl CollaborationHub for Entity<Project> {
19227    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19228        self.read(cx).collaborators()
19229    }
19230
19231    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19232        self.read(cx).user_store().read(cx).participant_indices()
19233    }
19234
19235    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19236        let this = self.read(cx);
19237        let user_ids = this.collaborators().values().map(|c| c.user_id);
19238        this.user_store().read_with(cx, |user_store, cx| {
19239            user_store.participant_names(user_ids, cx)
19240        })
19241    }
19242}
19243
19244pub trait SemanticsProvider {
19245    fn hover(
19246        &self,
19247        buffer: &Entity<Buffer>,
19248        position: text::Anchor,
19249        cx: &mut App,
19250    ) -> Option<Task<Vec<project::Hover>>>;
19251
19252    fn inline_values(
19253        &self,
19254        buffer_handle: Entity<Buffer>,
19255        range: Range<text::Anchor>,
19256        cx: &mut App,
19257    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19258
19259    fn inlay_hints(
19260        &self,
19261        buffer_handle: Entity<Buffer>,
19262        range: Range<text::Anchor>,
19263        cx: &mut App,
19264    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19265
19266    fn resolve_inlay_hint(
19267        &self,
19268        hint: InlayHint,
19269        buffer_handle: Entity<Buffer>,
19270        server_id: LanguageServerId,
19271        cx: &mut App,
19272    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19273
19274    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19275
19276    fn document_highlights(
19277        &self,
19278        buffer: &Entity<Buffer>,
19279        position: text::Anchor,
19280        cx: &mut App,
19281    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19282
19283    fn definitions(
19284        &self,
19285        buffer: &Entity<Buffer>,
19286        position: text::Anchor,
19287        kind: GotoDefinitionKind,
19288        cx: &mut App,
19289    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19290
19291    fn range_for_rename(
19292        &self,
19293        buffer: &Entity<Buffer>,
19294        position: text::Anchor,
19295        cx: &mut App,
19296    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19297
19298    fn perform_rename(
19299        &self,
19300        buffer: &Entity<Buffer>,
19301        position: text::Anchor,
19302        new_name: String,
19303        cx: &mut App,
19304    ) -> Option<Task<Result<ProjectTransaction>>>;
19305}
19306
19307pub trait CompletionProvider {
19308    fn completions(
19309        &self,
19310        excerpt_id: ExcerptId,
19311        buffer: &Entity<Buffer>,
19312        buffer_position: text::Anchor,
19313        trigger: CompletionContext,
19314        window: &mut Window,
19315        cx: &mut Context<Editor>,
19316    ) -> Task<Result<Option<Vec<Completion>>>>;
19317
19318    fn resolve_completions(
19319        &self,
19320        buffer: Entity<Buffer>,
19321        completion_indices: Vec<usize>,
19322        completions: Rc<RefCell<Box<[Completion]>>>,
19323        cx: &mut Context<Editor>,
19324    ) -> Task<Result<bool>>;
19325
19326    fn apply_additional_edits_for_completion(
19327        &self,
19328        _buffer: Entity<Buffer>,
19329        _completions: Rc<RefCell<Box<[Completion]>>>,
19330        _completion_index: usize,
19331        _push_to_history: bool,
19332        _cx: &mut Context<Editor>,
19333    ) -> Task<Result<Option<language::Transaction>>> {
19334        Task::ready(Ok(None))
19335    }
19336
19337    fn is_completion_trigger(
19338        &self,
19339        buffer: &Entity<Buffer>,
19340        position: language::Anchor,
19341        text: &str,
19342        trigger_in_words: bool,
19343        cx: &mut Context<Editor>,
19344    ) -> bool;
19345
19346    fn sort_completions(&self) -> bool {
19347        true
19348    }
19349
19350    fn filter_completions(&self) -> bool {
19351        true
19352    }
19353}
19354
19355pub trait CodeActionProvider {
19356    fn id(&self) -> Arc<str>;
19357
19358    fn code_actions(
19359        &self,
19360        buffer: &Entity<Buffer>,
19361        range: Range<text::Anchor>,
19362        window: &mut Window,
19363        cx: &mut App,
19364    ) -> Task<Result<Vec<CodeAction>>>;
19365
19366    fn apply_code_action(
19367        &self,
19368        buffer_handle: Entity<Buffer>,
19369        action: CodeAction,
19370        excerpt_id: ExcerptId,
19371        push_to_history: bool,
19372        window: &mut Window,
19373        cx: &mut App,
19374    ) -> Task<Result<ProjectTransaction>>;
19375}
19376
19377impl CodeActionProvider for Entity<Project> {
19378    fn id(&self) -> Arc<str> {
19379        "project".into()
19380    }
19381
19382    fn code_actions(
19383        &self,
19384        buffer: &Entity<Buffer>,
19385        range: Range<text::Anchor>,
19386        _window: &mut Window,
19387        cx: &mut App,
19388    ) -> Task<Result<Vec<CodeAction>>> {
19389        self.update(cx, |project, cx| {
19390            let code_lens = project.code_lens(buffer, range.clone(), cx);
19391            let code_actions = project.code_actions(buffer, range, None, cx);
19392            cx.background_spawn(async move {
19393                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19394                Ok(code_lens
19395                    .context("code lens fetch")?
19396                    .into_iter()
19397                    .chain(code_actions.context("code action fetch")?)
19398                    .collect())
19399            })
19400        })
19401    }
19402
19403    fn apply_code_action(
19404        &self,
19405        buffer_handle: Entity<Buffer>,
19406        action: CodeAction,
19407        _excerpt_id: ExcerptId,
19408        push_to_history: bool,
19409        _window: &mut Window,
19410        cx: &mut App,
19411    ) -> Task<Result<ProjectTransaction>> {
19412        self.update(cx, |project, cx| {
19413            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19414        })
19415    }
19416}
19417
19418fn snippet_completions(
19419    project: &Project,
19420    buffer: &Entity<Buffer>,
19421    buffer_position: text::Anchor,
19422    cx: &mut App,
19423) -> Task<Result<Vec<Completion>>> {
19424    let languages = buffer.read(cx).languages_at(buffer_position);
19425    let snippet_store = project.snippets().read(cx);
19426
19427    let scopes: Vec<_> = languages
19428        .iter()
19429        .filter_map(|language| {
19430            let language_name = language.lsp_id();
19431            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19432
19433            if snippets.is_empty() {
19434                None
19435            } else {
19436                Some((language.default_scope(), snippets))
19437            }
19438        })
19439        .collect();
19440
19441    if scopes.is_empty() {
19442        return Task::ready(Ok(vec![]));
19443    }
19444
19445    let snapshot = buffer.read(cx).text_snapshot();
19446    let chars: String = snapshot
19447        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19448        .collect();
19449    let executor = cx.background_executor().clone();
19450
19451    cx.background_spawn(async move {
19452        let mut all_results: Vec<Completion> = Vec::new();
19453        for (scope, snippets) in scopes.into_iter() {
19454            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19455            let mut last_word = chars
19456                .chars()
19457                .take_while(|c| classifier.is_word(*c))
19458                .collect::<String>();
19459            last_word = last_word.chars().rev().collect();
19460
19461            if last_word.is_empty() {
19462                return Ok(vec![]);
19463            }
19464
19465            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19466            let to_lsp = |point: &text::Anchor| {
19467                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19468                point_to_lsp(end)
19469            };
19470            let lsp_end = to_lsp(&buffer_position);
19471
19472            let candidates = snippets
19473                .iter()
19474                .enumerate()
19475                .flat_map(|(ix, snippet)| {
19476                    snippet
19477                        .prefix
19478                        .iter()
19479                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19480                })
19481                .collect::<Vec<StringMatchCandidate>>();
19482
19483            let mut matches = fuzzy::match_strings(
19484                &candidates,
19485                &last_word,
19486                last_word.chars().any(|c| c.is_uppercase()),
19487                100,
19488                &Default::default(),
19489                executor.clone(),
19490            )
19491            .await;
19492
19493            // Remove all candidates where the query's start does not match the start of any word in the candidate
19494            if let Some(query_start) = last_word.chars().next() {
19495                matches.retain(|string_match| {
19496                    split_words(&string_match.string).any(|word| {
19497                        // Check that the first codepoint of the word as lowercase matches the first
19498                        // codepoint of the query as lowercase
19499                        word.chars()
19500                            .flat_map(|codepoint| codepoint.to_lowercase())
19501                            .zip(query_start.to_lowercase())
19502                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19503                    })
19504                });
19505            }
19506
19507            let matched_strings = matches
19508                .into_iter()
19509                .map(|m| m.string)
19510                .collect::<HashSet<_>>();
19511
19512            let mut result: Vec<Completion> = snippets
19513                .iter()
19514                .filter_map(|snippet| {
19515                    let matching_prefix = snippet
19516                        .prefix
19517                        .iter()
19518                        .find(|prefix| matched_strings.contains(*prefix))?;
19519                    let start = as_offset - last_word.len();
19520                    let start = snapshot.anchor_before(start);
19521                    let range = start..buffer_position;
19522                    let lsp_start = to_lsp(&start);
19523                    let lsp_range = lsp::Range {
19524                        start: lsp_start,
19525                        end: lsp_end,
19526                    };
19527                    Some(Completion {
19528                        replace_range: range,
19529                        new_text: snippet.body.clone(),
19530                        source: CompletionSource::Lsp {
19531                            insert_range: None,
19532                            server_id: LanguageServerId(usize::MAX),
19533                            resolved: true,
19534                            lsp_completion: Box::new(lsp::CompletionItem {
19535                                label: snippet.prefix.first().unwrap().clone(),
19536                                kind: Some(CompletionItemKind::SNIPPET),
19537                                label_details: snippet.description.as_ref().map(|description| {
19538                                    lsp::CompletionItemLabelDetails {
19539                                        detail: Some(description.clone()),
19540                                        description: None,
19541                                    }
19542                                }),
19543                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19544                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19545                                    lsp::InsertReplaceEdit {
19546                                        new_text: snippet.body.clone(),
19547                                        insert: lsp_range,
19548                                        replace: lsp_range,
19549                                    },
19550                                )),
19551                                filter_text: Some(snippet.body.clone()),
19552                                sort_text: Some(char::MAX.to_string()),
19553                                ..lsp::CompletionItem::default()
19554                            }),
19555                            lsp_defaults: None,
19556                        },
19557                        label: CodeLabel {
19558                            text: matching_prefix.clone(),
19559                            runs: Vec::new(),
19560                            filter_range: 0..matching_prefix.len(),
19561                        },
19562                        icon_path: None,
19563                        documentation: snippet.description.clone().map(|description| {
19564                            CompletionDocumentation::SingleLine(description.into())
19565                        }),
19566                        insert_text_mode: None,
19567                        confirm: None,
19568                    })
19569                })
19570                .collect();
19571
19572            all_results.append(&mut result);
19573        }
19574
19575        Ok(all_results)
19576    })
19577}
19578
19579impl CompletionProvider for Entity<Project> {
19580    fn completions(
19581        &self,
19582        _excerpt_id: ExcerptId,
19583        buffer: &Entity<Buffer>,
19584        buffer_position: text::Anchor,
19585        options: CompletionContext,
19586        _window: &mut Window,
19587        cx: &mut Context<Editor>,
19588    ) -> Task<Result<Option<Vec<Completion>>>> {
19589        self.update(cx, |project, cx| {
19590            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19591            let project_completions = project.completions(buffer, buffer_position, options, cx);
19592            cx.background_spawn(async move {
19593                let snippets_completions = snippets.await?;
19594                match project_completions.await? {
19595                    Some(mut completions) => {
19596                        completions.extend(snippets_completions);
19597                        Ok(Some(completions))
19598                    }
19599                    None => {
19600                        if snippets_completions.is_empty() {
19601                            Ok(None)
19602                        } else {
19603                            Ok(Some(snippets_completions))
19604                        }
19605                    }
19606                }
19607            })
19608        })
19609    }
19610
19611    fn resolve_completions(
19612        &self,
19613        buffer: Entity<Buffer>,
19614        completion_indices: Vec<usize>,
19615        completions: Rc<RefCell<Box<[Completion]>>>,
19616        cx: &mut Context<Editor>,
19617    ) -> Task<Result<bool>> {
19618        self.update(cx, |project, cx| {
19619            project.lsp_store().update(cx, |lsp_store, cx| {
19620                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19621            })
19622        })
19623    }
19624
19625    fn apply_additional_edits_for_completion(
19626        &self,
19627        buffer: Entity<Buffer>,
19628        completions: Rc<RefCell<Box<[Completion]>>>,
19629        completion_index: usize,
19630        push_to_history: bool,
19631        cx: &mut Context<Editor>,
19632    ) -> Task<Result<Option<language::Transaction>>> {
19633        self.update(cx, |project, cx| {
19634            project.lsp_store().update(cx, |lsp_store, cx| {
19635                lsp_store.apply_additional_edits_for_completion(
19636                    buffer,
19637                    completions,
19638                    completion_index,
19639                    push_to_history,
19640                    cx,
19641                )
19642            })
19643        })
19644    }
19645
19646    fn is_completion_trigger(
19647        &self,
19648        buffer: &Entity<Buffer>,
19649        position: language::Anchor,
19650        text: &str,
19651        trigger_in_words: bool,
19652        cx: &mut Context<Editor>,
19653    ) -> bool {
19654        let mut chars = text.chars();
19655        let char = if let Some(char) = chars.next() {
19656            char
19657        } else {
19658            return false;
19659        };
19660        if chars.next().is_some() {
19661            return false;
19662        }
19663
19664        let buffer = buffer.read(cx);
19665        let snapshot = buffer.snapshot();
19666        if !snapshot.settings_at(position, cx).show_completions_on_input {
19667            return false;
19668        }
19669        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19670        if trigger_in_words && classifier.is_word(char) {
19671            return true;
19672        }
19673
19674        buffer.completion_triggers().contains(text)
19675    }
19676}
19677
19678impl SemanticsProvider for Entity<Project> {
19679    fn hover(
19680        &self,
19681        buffer: &Entity<Buffer>,
19682        position: text::Anchor,
19683        cx: &mut App,
19684    ) -> Option<Task<Vec<project::Hover>>> {
19685        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19686    }
19687
19688    fn document_highlights(
19689        &self,
19690        buffer: &Entity<Buffer>,
19691        position: text::Anchor,
19692        cx: &mut App,
19693    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19694        Some(self.update(cx, |project, cx| {
19695            project.document_highlights(buffer, position, cx)
19696        }))
19697    }
19698
19699    fn definitions(
19700        &self,
19701        buffer: &Entity<Buffer>,
19702        position: text::Anchor,
19703        kind: GotoDefinitionKind,
19704        cx: &mut App,
19705    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19706        Some(self.update(cx, |project, cx| match kind {
19707            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19708            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19709            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19710            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19711        }))
19712    }
19713
19714    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19715        // TODO: make this work for remote projects
19716        self.update(cx, |project, cx| {
19717            if project
19718                .active_debug_session(cx)
19719                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19720            {
19721                return true;
19722            }
19723
19724            buffer.update(cx, |buffer, cx| {
19725                project.any_language_server_supports_inlay_hints(buffer, cx)
19726            })
19727        })
19728    }
19729
19730    fn inline_values(
19731        &self,
19732        buffer_handle: Entity<Buffer>,
19733        range: Range<text::Anchor>,
19734        cx: &mut App,
19735    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19736        self.update(cx, |project, cx| {
19737            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19738
19739            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19740        })
19741    }
19742
19743    fn inlay_hints(
19744        &self,
19745        buffer_handle: Entity<Buffer>,
19746        range: Range<text::Anchor>,
19747        cx: &mut App,
19748    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19749        Some(self.update(cx, |project, cx| {
19750            project.inlay_hints(buffer_handle, range, cx)
19751        }))
19752    }
19753
19754    fn resolve_inlay_hint(
19755        &self,
19756        hint: InlayHint,
19757        buffer_handle: Entity<Buffer>,
19758        server_id: LanguageServerId,
19759        cx: &mut App,
19760    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19761        Some(self.update(cx, |project, cx| {
19762            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19763        }))
19764    }
19765
19766    fn range_for_rename(
19767        &self,
19768        buffer: &Entity<Buffer>,
19769        position: text::Anchor,
19770        cx: &mut App,
19771    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19772        Some(self.update(cx, |project, cx| {
19773            let buffer = buffer.clone();
19774            let task = project.prepare_rename(buffer.clone(), position, cx);
19775            cx.spawn(async move |_, cx| {
19776                Ok(match task.await? {
19777                    PrepareRenameResponse::Success(range) => Some(range),
19778                    PrepareRenameResponse::InvalidPosition => None,
19779                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19780                        // Fallback on using TreeSitter info to determine identifier range
19781                        buffer.update(cx, |buffer, _| {
19782                            let snapshot = buffer.snapshot();
19783                            let (range, kind) = snapshot.surrounding_word(position);
19784                            if kind != Some(CharKind::Word) {
19785                                return None;
19786                            }
19787                            Some(
19788                                snapshot.anchor_before(range.start)
19789                                    ..snapshot.anchor_after(range.end),
19790                            )
19791                        })?
19792                    }
19793                })
19794            })
19795        }))
19796    }
19797
19798    fn perform_rename(
19799        &self,
19800        buffer: &Entity<Buffer>,
19801        position: text::Anchor,
19802        new_name: String,
19803        cx: &mut App,
19804    ) -> Option<Task<Result<ProjectTransaction>>> {
19805        Some(self.update(cx, |project, cx| {
19806            project.perform_rename(buffer.clone(), position, new_name, cx)
19807        }))
19808    }
19809}
19810
19811fn inlay_hint_settings(
19812    location: Anchor,
19813    snapshot: &MultiBufferSnapshot,
19814    cx: &mut Context<Editor>,
19815) -> InlayHintSettings {
19816    let file = snapshot.file_at(location);
19817    let language = snapshot.language_at(location).map(|l| l.name());
19818    language_settings(language, file, cx).inlay_hints
19819}
19820
19821fn consume_contiguous_rows(
19822    contiguous_row_selections: &mut Vec<Selection<Point>>,
19823    selection: &Selection<Point>,
19824    display_map: &DisplaySnapshot,
19825    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19826) -> (MultiBufferRow, MultiBufferRow) {
19827    contiguous_row_selections.push(selection.clone());
19828    let start_row = MultiBufferRow(selection.start.row);
19829    let mut end_row = ending_row(selection, display_map);
19830
19831    while let Some(next_selection) = selections.peek() {
19832        if next_selection.start.row <= end_row.0 {
19833            end_row = ending_row(next_selection, display_map);
19834            contiguous_row_selections.push(selections.next().unwrap().clone());
19835        } else {
19836            break;
19837        }
19838    }
19839    (start_row, end_row)
19840}
19841
19842fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19843    if next_selection.end.column > 0 || next_selection.is_empty() {
19844        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19845    } else {
19846        MultiBufferRow(next_selection.end.row)
19847    }
19848}
19849
19850impl EditorSnapshot {
19851    pub fn remote_selections_in_range<'a>(
19852        &'a self,
19853        range: &'a Range<Anchor>,
19854        collaboration_hub: &dyn CollaborationHub,
19855        cx: &'a App,
19856    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19857        let participant_names = collaboration_hub.user_names(cx);
19858        let participant_indices = collaboration_hub.user_participant_indices(cx);
19859        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19860        let collaborators_by_replica_id = collaborators_by_peer_id
19861            .iter()
19862            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19863            .collect::<HashMap<_, _>>();
19864        self.buffer_snapshot
19865            .selections_in_range(range, false)
19866            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19867                if replica_id == AGENT_REPLICA_ID {
19868                    Some(RemoteSelection {
19869                        replica_id,
19870                        selection,
19871                        cursor_shape,
19872                        line_mode,
19873                        collaborator_id: CollaboratorId::Agent,
19874                        user_name: Some("Agent".into()),
19875                        color: cx.theme().players().agent(),
19876                    })
19877                } else {
19878                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19879                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19880                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19881                    Some(RemoteSelection {
19882                        replica_id,
19883                        selection,
19884                        cursor_shape,
19885                        line_mode,
19886                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19887                        user_name,
19888                        color: if let Some(index) = participant_index {
19889                            cx.theme().players().color_for_participant(index.0)
19890                        } else {
19891                            cx.theme().players().absent()
19892                        },
19893                    })
19894                }
19895            })
19896    }
19897
19898    pub fn hunks_for_ranges(
19899        &self,
19900        ranges: impl IntoIterator<Item = Range<Point>>,
19901    ) -> Vec<MultiBufferDiffHunk> {
19902        let mut hunks = Vec::new();
19903        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19904            HashMap::default();
19905        for query_range in ranges {
19906            let query_rows =
19907                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19908            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19909                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19910            ) {
19911                // Include deleted hunks that are adjacent to the query range, because
19912                // otherwise they would be missed.
19913                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19914                if hunk.status().is_deleted() {
19915                    intersects_range |= hunk.row_range.start == query_rows.end;
19916                    intersects_range |= hunk.row_range.end == query_rows.start;
19917                }
19918                if intersects_range {
19919                    if !processed_buffer_rows
19920                        .entry(hunk.buffer_id)
19921                        .or_default()
19922                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19923                    {
19924                        continue;
19925                    }
19926                    hunks.push(hunk);
19927                }
19928            }
19929        }
19930
19931        hunks
19932    }
19933
19934    fn display_diff_hunks_for_rows<'a>(
19935        &'a self,
19936        display_rows: Range<DisplayRow>,
19937        folded_buffers: &'a HashSet<BufferId>,
19938    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19939        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19940        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19941
19942        self.buffer_snapshot
19943            .diff_hunks_in_range(buffer_start..buffer_end)
19944            .filter_map(|hunk| {
19945                if folded_buffers.contains(&hunk.buffer_id) {
19946                    return None;
19947                }
19948
19949                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19950                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19951
19952                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19953                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19954
19955                let display_hunk = if hunk_display_start.column() != 0 {
19956                    DisplayDiffHunk::Folded {
19957                        display_row: hunk_display_start.row(),
19958                    }
19959                } else {
19960                    let mut end_row = hunk_display_end.row();
19961                    if hunk_display_end.column() > 0 {
19962                        end_row.0 += 1;
19963                    }
19964                    let is_created_file = hunk.is_created_file();
19965                    DisplayDiffHunk::Unfolded {
19966                        status: hunk.status(),
19967                        diff_base_byte_range: hunk.diff_base_byte_range,
19968                        display_row_range: hunk_display_start.row()..end_row,
19969                        multi_buffer_range: Anchor::range_in_buffer(
19970                            hunk.excerpt_id,
19971                            hunk.buffer_id,
19972                            hunk.buffer_range,
19973                        ),
19974                        is_created_file,
19975                    }
19976                };
19977
19978                Some(display_hunk)
19979            })
19980    }
19981
19982    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19983        self.display_snapshot.buffer_snapshot.language_at(position)
19984    }
19985
19986    pub fn is_focused(&self) -> bool {
19987        self.is_focused
19988    }
19989
19990    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19991        self.placeholder_text.as_ref()
19992    }
19993
19994    pub fn scroll_position(&self) -> gpui::Point<f32> {
19995        self.scroll_anchor.scroll_position(&self.display_snapshot)
19996    }
19997
19998    fn gutter_dimensions(
19999        &self,
20000        font_id: FontId,
20001        font_size: Pixels,
20002        max_line_number_width: Pixels,
20003        cx: &App,
20004    ) -> Option<GutterDimensions> {
20005        if !self.show_gutter {
20006            return None;
20007        }
20008
20009        let descent = cx.text_system().descent(font_id, font_size);
20010        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20011        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20012
20013        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20014            matches!(
20015                ProjectSettings::get_global(cx).git.git_gutter,
20016                Some(GitGutterSetting::TrackedFiles)
20017            )
20018        });
20019        let gutter_settings = EditorSettings::get_global(cx).gutter;
20020        let show_line_numbers = self
20021            .show_line_numbers
20022            .unwrap_or(gutter_settings.line_numbers);
20023        let line_gutter_width = if show_line_numbers {
20024            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20025            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20026            max_line_number_width.max(min_width_for_number_on_gutter)
20027        } else {
20028            0.0.into()
20029        };
20030
20031        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20032        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20033
20034        let git_blame_entries_width =
20035            self.git_blame_gutter_max_author_length
20036                .map(|max_author_length| {
20037                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20038                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20039
20040                    /// The number of characters to dedicate to gaps and margins.
20041                    const SPACING_WIDTH: usize = 4;
20042
20043                    let max_char_count = max_author_length.min(renderer.max_author_length())
20044                        + ::git::SHORT_SHA_LENGTH
20045                        + MAX_RELATIVE_TIMESTAMP.len()
20046                        + SPACING_WIDTH;
20047
20048                    em_advance * max_char_count
20049                });
20050
20051        let is_singleton = self.buffer_snapshot.is_singleton();
20052
20053        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20054        left_padding += if !is_singleton {
20055            em_width * 4.0
20056        } else if show_runnables || show_breakpoints {
20057            em_width * 3.0
20058        } else if show_git_gutter && show_line_numbers {
20059            em_width * 2.0
20060        } else if show_git_gutter || show_line_numbers {
20061            em_width
20062        } else {
20063            px(0.)
20064        };
20065
20066        let shows_folds = is_singleton && gutter_settings.folds;
20067
20068        let right_padding = if shows_folds && show_line_numbers {
20069            em_width * 4.0
20070        } else if shows_folds || (!is_singleton && show_line_numbers) {
20071            em_width * 3.0
20072        } else if show_line_numbers {
20073            em_width
20074        } else {
20075            px(0.)
20076        };
20077
20078        Some(GutterDimensions {
20079            left_padding,
20080            right_padding,
20081            width: line_gutter_width + left_padding + right_padding,
20082            margin: -descent,
20083            git_blame_entries_width,
20084        })
20085    }
20086
20087    pub fn render_crease_toggle(
20088        &self,
20089        buffer_row: MultiBufferRow,
20090        row_contains_cursor: bool,
20091        editor: Entity<Editor>,
20092        window: &mut Window,
20093        cx: &mut App,
20094    ) -> Option<AnyElement> {
20095        let folded = self.is_line_folded(buffer_row);
20096        let mut is_foldable = false;
20097
20098        if let Some(crease) = self
20099            .crease_snapshot
20100            .query_row(buffer_row, &self.buffer_snapshot)
20101        {
20102            is_foldable = true;
20103            match crease {
20104                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20105                    if let Some(render_toggle) = render_toggle {
20106                        let toggle_callback =
20107                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20108                                if folded {
20109                                    editor.update(cx, |editor, cx| {
20110                                        editor.fold_at(buffer_row, window, cx)
20111                                    });
20112                                } else {
20113                                    editor.update(cx, |editor, cx| {
20114                                        editor.unfold_at(buffer_row, window, cx)
20115                                    });
20116                                }
20117                            });
20118                        return Some((render_toggle)(
20119                            buffer_row,
20120                            folded,
20121                            toggle_callback,
20122                            window,
20123                            cx,
20124                        ));
20125                    }
20126                }
20127            }
20128        }
20129
20130        is_foldable |= self.starts_indent(buffer_row);
20131
20132        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20133            Some(
20134                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20135                    .toggle_state(folded)
20136                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20137                        if folded {
20138                            this.unfold_at(buffer_row, window, cx);
20139                        } else {
20140                            this.fold_at(buffer_row, window, cx);
20141                        }
20142                    }))
20143                    .into_any_element(),
20144            )
20145        } else {
20146            None
20147        }
20148    }
20149
20150    pub fn render_crease_trailer(
20151        &self,
20152        buffer_row: MultiBufferRow,
20153        window: &mut Window,
20154        cx: &mut App,
20155    ) -> Option<AnyElement> {
20156        let folded = self.is_line_folded(buffer_row);
20157        if let Crease::Inline { render_trailer, .. } = self
20158            .crease_snapshot
20159            .query_row(buffer_row, &self.buffer_snapshot)?
20160        {
20161            let render_trailer = render_trailer.as_ref()?;
20162            Some(render_trailer(buffer_row, folded, window, cx))
20163        } else {
20164            None
20165        }
20166    }
20167}
20168
20169impl Deref for EditorSnapshot {
20170    type Target = DisplaySnapshot;
20171
20172    fn deref(&self) -> &Self::Target {
20173        &self.display_snapshot
20174    }
20175}
20176
20177#[derive(Clone, Debug, PartialEq, Eq)]
20178pub enum EditorEvent {
20179    InputIgnored {
20180        text: Arc<str>,
20181    },
20182    InputHandled {
20183        utf16_range_to_replace: Option<Range<isize>>,
20184        text: Arc<str>,
20185    },
20186    ExcerptsAdded {
20187        buffer: Entity<Buffer>,
20188        predecessor: ExcerptId,
20189        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20190    },
20191    ExcerptsRemoved {
20192        ids: Vec<ExcerptId>,
20193        removed_buffer_ids: Vec<BufferId>,
20194    },
20195    BufferFoldToggled {
20196        ids: Vec<ExcerptId>,
20197        folded: bool,
20198    },
20199    ExcerptsEdited {
20200        ids: Vec<ExcerptId>,
20201    },
20202    ExcerptsExpanded {
20203        ids: Vec<ExcerptId>,
20204    },
20205    BufferEdited,
20206    Edited {
20207        transaction_id: clock::Lamport,
20208    },
20209    Reparsed(BufferId),
20210    Focused,
20211    FocusedIn,
20212    Blurred,
20213    DirtyChanged,
20214    Saved,
20215    TitleChanged,
20216    DiffBaseChanged,
20217    SelectionsChanged {
20218        local: bool,
20219    },
20220    ScrollPositionChanged {
20221        local: bool,
20222        autoscroll: bool,
20223    },
20224    Closed,
20225    TransactionUndone {
20226        transaction_id: clock::Lamport,
20227    },
20228    TransactionBegun {
20229        transaction_id: clock::Lamport,
20230    },
20231    Reloaded,
20232    CursorShapeChanged,
20233    PushedToNavHistory {
20234        anchor: Anchor,
20235        is_deactivate: bool,
20236    },
20237}
20238
20239impl EventEmitter<EditorEvent> for Editor {}
20240
20241impl Focusable for Editor {
20242    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20243        self.focus_handle.clone()
20244    }
20245}
20246
20247impl Render for Editor {
20248    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20249        let settings = ThemeSettings::get_global(cx);
20250
20251        let mut text_style = match self.mode {
20252            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20253                color: cx.theme().colors().editor_foreground,
20254                font_family: settings.ui_font.family.clone(),
20255                font_features: settings.ui_font.features.clone(),
20256                font_fallbacks: settings.ui_font.fallbacks.clone(),
20257                font_size: rems(0.875).into(),
20258                font_weight: settings.ui_font.weight,
20259                line_height: relative(settings.buffer_line_height.value()),
20260                ..Default::default()
20261            },
20262            EditorMode::Full { .. } => TextStyle {
20263                color: cx.theme().colors().editor_foreground,
20264                font_family: settings.buffer_font.family.clone(),
20265                font_features: settings.buffer_font.features.clone(),
20266                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20267                font_size: settings.buffer_font_size(cx).into(),
20268                font_weight: settings.buffer_font.weight,
20269                line_height: relative(settings.buffer_line_height.value()),
20270                ..Default::default()
20271            },
20272        };
20273        if let Some(text_style_refinement) = &self.text_style_refinement {
20274            text_style.refine(text_style_refinement)
20275        }
20276
20277        let background = match self.mode {
20278            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20279            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20280            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20281        };
20282
20283        EditorElement::new(
20284            &cx.entity(),
20285            EditorStyle {
20286                background,
20287                horizontal_padding: Pixels::default(),
20288                local_player: cx.theme().players().local(),
20289                text: text_style,
20290                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20291                syntax: cx.theme().syntax().clone(),
20292                status: cx.theme().status().clone(),
20293                inlay_hints_style: make_inlay_hints_style(cx),
20294                inline_completion_styles: make_suggestion_styles(cx),
20295                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20296            },
20297        )
20298    }
20299}
20300
20301impl EntityInputHandler for Editor {
20302    fn text_for_range(
20303        &mut self,
20304        range_utf16: Range<usize>,
20305        adjusted_range: &mut Option<Range<usize>>,
20306        _: &mut Window,
20307        cx: &mut Context<Self>,
20308    ) -> Option<String> {
20309        let snapshot = self.buffer.read(cx).read(cx);
20310        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20311        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20312        if (start.0..end.0) != range_utf16 {
20313            adjusted_range.replace(start.0..end.0);
20314        }
20315        Some(snapshot.text_for_range(start..end).collect())
20316    }
20317
20318    fn selected_text_range(
20319        &mut self,
20320        ignore_disabled_input: bool,
20321        _: &mut Window,
20322        cx: &mut Context<Self>,
20323    ) -> Option<UTF16Selection> {
20324        // Prevent the IME menu from appearing when holding down an alphabetic key
20325        // while input is disabled.
20326        if !ignore_disabled_input && !self.input_enabled {
20327            return None;
20328        }
20329
20330        let selection = self.selections.newest::<OffsetUtf16>(cx);
20331        let range = selection.range();
20332
20333        Some(UTF16Selection {
20334            range: range.start.0..range.end.0,
20335            reversed: selection.reversed,
20336        })
20337    }
20338
20339    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20340        let snapshot = self.buffer.read(cx).read(cx);
20341        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20342        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20343    }
20344
20345    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20346        self.clear_highlights::<InputComposition>(cx);
20347        self.ime_transaction.take();
20348    }
20349
20350    fn replace_text_in_range(
20351        &mut self,
20352        range_utf16: Option<Range<usize>>,
20353        text: &str,
20354        window: &mut Window,
20355        cx: &mut Context<Self>,
20356    ) {
20357        if !self.input_enabled {
20358            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20359            return;
20360        }
20361
20362        self.transact(window, cx, |this, window, cx| {
20363            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20364                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20365                Some(this.selection_replacement_ranges(range_utf16, cx))
20366            } else {
20367                this.marked_text_ranges(cx)
20368            };
20369
20370            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20371                let newest_selection_id = this.selections.newest_anchor().id;
20372                this.selections
20373                    .all::<OffsetUtf16>(cx)
20374                    .iter()
20375                    .zip(ranges_to_replace.iter())
20376                    .find_map(|(selection, range)| {
20377                        if selection.id == newest_selection_id {
20378                            Some(
20379                                (range.start.0 as isize - selection.head().0 as isize)
20380                                    ..(range.end.0 as isize - selection.head().0 as isize),
20381                            )
20382                        } else {
20383                            None
20384                        }
20385                    })
20386            });
20387
20388            cx.emit(EditorEvent::InputHandled {
20389                utf16_range_to_replace: range_to_replace,
20390                text: text.into(),
20391            });
20392
20393            if let Some(new_selected_ranges) = new_selected_ranges {
20394                this.change_selections(None, window, cx, |selections| {
20395                    selections.select_ranges(new_selected_ranges)
20396                });
20397                this.backspace(&Default::default(), window, cx);
20398            }
20399
20400            this.handle_input(text, window, cx);
20401        });
20402
20403        if let Some(transaction) = self.ime_transaction {
20404            self.buffer.update(cx, |buffer, cx| {
20405                buffer.group_until_transaction(transaction, cx);
20406            });
20407        }
20408
20409        self.unmark_text(window, cx);
20410    }
20411
20412    fn replace_and_mark_text_in_range(
20413        &mut self,
20414        range_utf16: Option<Range<usize>>,
20415        text: &str,
20416        new_selected_range_utf16: Option<Range<usize>>,
20417        window: &mut Window,
20418        cx: &mut Context<Self>,
20419    ) {
20420        if !self.input_enabled {
20421            return;
20422        }
20423
20424        let transaction = self.transact(window, cx, |this, window, cx| {
20425            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20426                let snapshot = this.buffer.read(cx).read(cx);
20427                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20428                    for marked_range in &mut marked_ranges {
20429                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20430                        marked_range.start.0 += relative_range_utf16.start;
20431                        marked_range.start =
20432                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20433                        marked_range.end =
20434                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20435                    }
20436                }
20437                Some(marked_ranges)
20438            } else if let Some(range_utf16) = range_utf16 {
20439                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20440                Some(this.selection_replacement_ranges(range_utf16, cx))
20441            } else {
20442                None
20443            };
20444
20445            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20446                let newest_selection_id = this.selections.newest_anchor().id;
20447                this.selections
20448                    .all::<OffsetUtf16>(cx)
20449                    .iter()
20450                    .zip(ranges_to_replace.iter())
20451                    .find_map(|(selection, range)| {
20452                        if selection.id == newest_selection_id {
20453                            Some(
20454                                (range.start.0 as isize - selection.head().0 as isize)
20455                                    ..(range.end.0 as isize - selection.head().0 as isize),
20456                            )
20457                        } else {
20458                            None
20459                        }
20460                    })
20461            });
20462
20463            cx.emit(EditorEvent::InputHandled {
20464                utf16_range_to_replace: range_to_replace,
20465                text: text.into(),
20466            });
20467
20468            if let Some(ranges) = ranges_to_replace {
20469                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20470            }
20471
20472            let marked_ranges = {
20473                let snapshot = this.buffer.read(cx).read(cx);
20474                this.selections
20475                    .disjoint_anchors()
20476                    .iter()
20477                    .map(|selection| {
20478                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20479                    })
20480                    .collect::<Vec<_>>()
20481            };
20482
20483            if text.is_empty() {
20484                this.unmark_text(window, cx);
20485            } else {
20486                this.highlight_text::<InputComposition>(
20487                    marked_ranges.clone(),
20488                    HighlightStyle {
20489                        underline: Some(UnderlineStyle {
20490                            thickness: px(1.),
20491                            color: None,
20492                            wavy: false,
20493                        }),
20494                        ..Default::default()
20495                    },
20496                    cx,
20497                );
20498            }
20499
20500            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20501            let use_autoclose = this.use_autoclose;
20502            let use_auto_surround = this.use_auto_surround;
20503            this.set_use_autoclose(false);
20504            this.set_use_auto_surround(false);
20505            this.handle_input(text, window, cx);
20506            this.set_use_autoclose(use_autoclose);
20507            this.set_use_auto_surround(use_auto_surround);
20508
20509            if let Some(new_selected_range) = new_selected_range_utf16 {
20510                let snapshot = this.buffer.read(cx).read(cx);
20511                let new_selected_ranges = marked_ranges
20512                    .into_iter()
20513                    .map(|marked_range| {
20514                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20515                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20516                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20517                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20518                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20519                    })
20520                    .collect::<Vec<_>>();
20521
20522                drop(snapshot);
20523                this.change_selections(None, window, cx, |selections| {
20524                    selections.select_ranges(new_selected_ranges)
20525                });
20526            }
20527        });
20528
20529        self.ime_transaction = self.ime_transaction.or(transaction);
20530        if let Some(transaction) = self.ime_transaction {
20531            self.buffer.update(cx, |buffer, cx| {
20532                buffer.group_until_transaction(transaction, cx);
20533            });
20534        }
20535
20536        if self.text_highlights::<InputComposition>(cx).is_none() {
20537            self.ime_transaction.take();
20538        }
20539    }
20540
20541    fn bounds_for_range(
20542        &mut self,
20543        range_utf16: Range<usize>,
20544        element_bounds: gpui::Bounds<Pixels>,
20545        window: &mut Window,
20546        cx: &mut Context<Self>,
20547    ) -> Option<gpui::Bounds<Pixels>> {
20548        let text_layout_details = self.text_layout_details(window);
20549        let gpui::Size {
20550            width: em_width,
20551            height: line_height,
20552        } = self.character_size(window);
20553
20554        let snapshot = self.snapshot(window, cx);
20555        let scroll_position = snapshot.scroll_position();
20556        let scroll_left = scroll_position.x * em_width;
20557
20558        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20559        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20560            + self.gutter_dimensions.width
20561            + self.gutter_dimensions.margin;
20562        let y = line_height * (start.row().as_f32() - scroll_position.y);
20563
20564        Some(Bounds {
20565            origin: element_bounds.origin + point(x, y),
20566            size: size(em_width, line_height),
20567        })
20568    }
20569
20570    fn character_index_for_point(
20571        &mut self,
20572        point: gpui::Point<Pixels>,
20573        _window: &mut Window,
20574        _cx: &mut Context<Self>,
20575    ) -> Option<usize> {
20576        let position_map = self.last_position_map.as_ref()?;
20577        if !position_map.text_hitbox.contains(&point) {
20578            return None;
20579        }
20580        let display_point = position_map.point_for_position(point).previous_valid;
20581        let anchor = position_map
20582            .snapshot
20583            .display_point_to_anchor(display_point, Bias::Left);
20584        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20585        Some(utf16_offset.0)
20586    }
20587}
20588
20589trait SelectionExt {
20590    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20591    fn spanned_rows(
20592        &self,
20593        include_end_if_at_line_start: bool,
20594        map: &DisplaySnapshot,
20595    ) -> Range<MultiBufferRow>;
20596}
20597
20598impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20599    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20600        let start = self
20601            .start
20602            .to_point(&map.buffer_snapshot)
20603            .to_display_point(map);
20604        let end = self
20605            .end
20606            .to_point(&map.buffer_snapshot)
20607            .to_display_point(map);
20608        if self.reversed {
20609            end..start
20610        } else {
20611            start..end
20612        }
20613    }
20614
20615    fn spanned_rows(
20616        &self,
20617        include_end_if_at_line_start: bool,
20618        map: &DisplaySnapshot,
20619    ) -> Range<MultiBufferRow> {
20620        let start = self.start.to_point(&map.buffer_snapshot);
20621        let mut end = self.end.to_point(&map.buffer_snapshot);
20622        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20623            end.row -= 1;
20624        }
20625
20626        let buffer_start = map.prev_line_boundary(start).0;
20627        let buffer_end = map.next_line_boundary(end).0;
20628        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20629    }
20630}
20631
20632impl<T: InvalidationRegion> InvalidationStack<T> {
20633    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20634    where
20635        S: Clone + ToOffset,
20636    {
20637        while let Some(region) = self.last() {
20638            let all_selections_inside_invalidation_ranges =
20639                if selections.len() == region.ranges().len() {
20640                    selections
20641                        .iter()
20642                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20643                        .all(|(selection, invalidation_range)| {
20644                            let head = selection.head().to_offset(buffer);
20645                            invalidation_range.start <= head && invalidation_range.end >= head
20646                        })
20647                } else {
20648                    false
20649                };
20650
20651            if all_selections_inside_invalidation_ranges {
20652                break;
20653            } else {
20654                self.pop();
20655            }
20656        }
20657    }
20658}
20659
20660impl<T> Default for InvalidationStack<T> {
20661    fn default() -> Self {
20662        Self(Default::default())
20663    }
20664}
20665
20666impl<T> Deref for InvalidationStack<T> {
20667    type Target = Vec<T>;
20668
20669    fn deref(&self) -> &Self::Target {
20670        &self.0
20671    }
20672}
20673
20674impl<T> DerefMut for InvalidationStack<T> {
20675    fn deref_mut(&mut self) -> &mut Self::Target {
20676        &mut self.0
20677    }
20678}
20679
20680impl InvalidationRegion for SnippetState {
20681    fn ranges(&self) -> &[Range<Anchor>] {
20682        &self.ranges[self.active_index]
20683    }
20684}
20685
20686fn inline_completion_edit_text(
20687    current_snapshot: &BufferSnapshot,
20688    edits: &[(Range<Anchor>, String)],
20689    edit_preview: &EditPreview,
20690    include_deletions: bool,
20691    cx: &App,
20692) -> HighlightedText {
20693    let edits = edits
20694        .iter()
20695        .map(|(anchor, text)| {
20696            (
20697                anchor.start.text_anchor..anchor.end.text_anchor,
20698                text.clone(),
20699            )
20700        })
20701        .collect::<Vec<_>>();
20702
20703    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20704}
20705
20706pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20707    match severity {
20708        DiagnosticSeverity::ERROR => colors.error,
20709        DiagnosticSeverity::WARNING => colors.warning,
20710        DiagnosticSeverity::INFORMATION => colors.info,
20711        DiagnosticSeverity::HINT => colors.info,
20712        _ => colors.ignored,
20713    }
20714}
20715
20716pub fn styled_runs_for_code_label<'a>(
20717    label: &'a CodeLabel,
20718    syntax_theme: &'a theme::SyntaxTheme,
20719) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20720    let fade_out = HighlightStyle {
20721        fade_out: Some(0.35),
20722        ..Default::default()
20723    };
20724
20725    let mut prev_end = label.filter_range.end;
20726    label
20727        .runs
20728        .iter()
20729        .enumerate()
20730        .flat_map(move |(ix, (range, highlight_id))| {
20731            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20732                style
20733            } else {
20734                return Default::default();
20735            };
20736            let mut muted_style = style;
20737            muted_style.highlight(fade_out);
20738
20739            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20740            if range.start >= label.filter_range.end {
20741                if range.start > prev_end {
20742                    runs.push((prev_end..range.start, fade_out));
20743                }
20744                runs.push((range.clone(), muted_style));
20745            } else if range.end <= label.filter_range.end {
20746                runs.push((range.clone(), style));
20747            } else {
20748                runs.push((range.start..label.filter_range.end, style));
20749                runs.push((label.filter_range.end..range.end, muted_style));
20750            }
20751            prev_end = cmp::max(prev_end, range.end);
20752
20753            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20754                runs.push((prev_end..label.text.len(), fade_out));
20755            }
20756
20757            runs
20758        })
20759}
20760
20761pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20762    let mut prev_index = 0;
20763    let mut prev_codepoint: Option<char> = None;
20764    text.char_indices()
20765        .chain([(text.len(), '\0')])
20766        .filter_map(move |(index, codepoint)| {
20767            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20768            let is_boundary = index == text.len()
20769                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20770                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20771            if is_boundary {
20772                let chunk = &text[prev_index..index];
20773                prev_index = index;
20774                Some(chunk)
20775            } else {
20776                None
20777            }
20778        })
20779}
20780
20781pub trait RangeToAnchorExt: Sized {
20782    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20783
20784    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20785        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20786        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20787    }
20788}
20789
20790impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20791    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20792        let start_offset = self.start.to_offset(snapshot);
20793        let end_offset = self.end.to_offset(snapshot);
20794        if start_offset == end_offset {
20795            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20796        } else {
20797            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20798        }
20799    }
20800}
20801
20802pub trait RowExt {
20803    fn as_f32(&self) -> f32;
20804
20805    fn next_row(&self) -> Self;
20806
20807    fn previous_row(&self) -> Self;
20808
20809    fn minus(&self, other: Self) -> u32;
20810}
20811
20812impl RowExt for DisplayRow {
20813    fn as_f32(&self) -> f32 {
20814        self.0 as f32
20815    }
20816
20817    fn next_row(&self) -> Self {
20818        Self(self.0 + 1)
20819    }
20820
20821    fn previous_row(&self) -> Self {
20822        Self(self.0.saturating_sub(1))
20823    }
20824
20825    fn minus(&self, other: Self) -> u32 {
20826        self.0 - other.0
20827    }
20828}
20829
20830impl RowExt for MultiBufferRow {
20831    fn as_f32(&self) -> f32 {
20832        self.0 as f32
20833    }
20834
20835    fn next_row(&self) -> Self {
20836        Self(self.0 + 1)
20837    }
20838
20839    fn previous_row(&self) -> Self {
20840        Self(self.0.saturating_sub(1))
20841    }
20842
20843    fn minus(&self, other: Self) -> u32 {
20844        self.0 - other.0
20845    }
20846}
20847
20848trait RowRangeExt {
20849    type Row;
20850
20851    fn len(&self) -> usize;
20852
20853    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20854}
20855
20856impl RowRangeExt for Range<MultiBufferRow> {
20857    type Row = MultiBufferRow;
20858
20859    fn len(&self) -> usize {
20860        (self.end.0 - self.start.0) as usize
20861    }
20862
20863    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20864        (self.start.0..self.end.0).map(MultiBufferRow)
20865    }
20866}
20867
20868impl RowRangeExt for Range<DisplayRow> {
20869    type Row = DisplayRow;
20870
20871    fn len(&self) -> usize {
20872        (self.end.0 - self.start.0) as usize
20873    }
20874
20875    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20876        (self.start.0..self.end.0).map(DisplayRow)
20877    }
20878}
20879
20880/// If select range has more than one line, we
20881/// just point the cursor to range.start.
20882fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20883    if range.start.row == range.end.row {
20884        range
20885    } else {
20886        range.start..range.start
20887    }
20888}
20889pub struct KillRing(ClipboardItem);
20890impl Global for KillRing {}
20891
20892const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20893
20894enum BreakpointPromptEditAction {
20895    Log,
20896    Condition,
20897    HitCondition,
20898}
20899
20900struct BreakpointPromptEditor {
20901    pub(crate) prompt: Entity<Editor>,
20902    editor: WeakEntity<Editor>,
20903    breakpoint_anchor: Anchor,
20904    breakpoint: Breakpoint,
20905    edit_action: BreakpointPromptEditAction,
20906    block_ids: HashSet<CustomBlockId>,
20907    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20908    _subscriptions: Vec<Subscription>,
20909}
20910
20911impl BreakpointPromptEditor {
20912    const MAX_LINES: u8 = 4;
20913
20914    fn new(
20915        editor: WeakEntity<Editor>,
20916        breakpoint_anchor: Anchor,
20917        breakpoint: Breakpoint,
20918        edit_action: BreakpointPromptEditAction,
20919        window: &mut Window,
20920        cx: &mut Context<Self>,
20921    ) -> Self {
20922        let base_text = match edit_action {
20923            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20924            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20925            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20926        }
20927        .map(|msg| msg.to_string())
20928        .unwrap_or_default();
20929
20930        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20931        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20932
20933        let prompt = cx.new(|cx| {
20934            let mut prompt = Editor::new(
20935                EditorMode::AutoHeight {
20936                    max_lines: Self::MAX_LINES as usize,
20937                },
20938                buffer,
20939                None,
20940                window,
20941                cx,
20942            );
20943            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20944            prompt.set_show_cursor_when_unfocused(false, cx);
20945            prompt.set_placeholder_text(
20946                match edit_action {
20947                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20948                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20949                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20950                },
20951                cx,
20952            );
20953
20954            prompt
20955        });
20956
20957        Self {
20958            prompt,
20959            editor,
20960            breakpoint_anchor,
20961            breakpoint,
20962            edit_action,
20963            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20964            block_ids: Default::default(),
20965            _subscriptions: vec![],
20966        }
20967    }
20968
20969    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20970        self.block_ids.extend(block_ids)
20971    }
20972
20973    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20974        if let Some(editor) = self.editor.upgrade() {
20975            let message = self
20976                .prompt
20977                .read(cx)
20978                .buffer
20979                .read(cx)
20980                .as_singleton()
20981                .expect("A multi buffer in breakpoint prompt isn't possible")
20982                .read(cx)
20983                .as_rope()
20984                .to_string();
20985
20986            editor.update(cx, |editor, cx| {
20987                editor.edit_breakpoint_at_anchor(
20988                    self.breakpoint_anchor,
20989                    self.breakpoint.clone(),
20990                    match self.edit_action {
20991                        BreakpointPromptEditAction::Log => {
20992                            BreakpointEditAction::EditLogMessage(message.into())
20993                        }
20994                        BreakpointPromptEditAction::Condition => {
20995                            BreakpointEditAction::EditCondition(message.into())
20996                        }
20997                        BreakpointPromptEditAction::HitCondition => {
20998                            BreakpointEditAction::EditHitCondition(message.into())
20999                        }
21000                    },
21001                    cx,
21002                );
21003
21004                editor.remove_blocks(self.block_ids.clone(), None, cx);
21005                cx.focus_self(window);
21006            });
21007        }
21008    }
21009
21010    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21011        self.editor
21012            .update(cx, |editor, cx| {
21013                editor.remove_blocks(self.block_ids.clone(), None, cx);
21014                window.focus(&editor.focus_handle);
21015            })
21016            .log_err();
21017    }
21018
21019    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21020        let settings = ThemeSettings::get_global(cx);
21021        let text_style = TextStyle {
21022            color: if self.prompt.read(cx).read_only(cx) {
21023                cx.theme().colors().text_disabled
21024            } else {
21025                cx.theme().colors().text
21026            },
21027            font_family: settings.buffer_font.family.clone(),
21028            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21029            font_size: settings.buffer_font_size(cx).into(),
21030            font_weight: settings.buffer_font.weight,
21031            line_height: relative(settings.buffer_line_height.value()),
21032            ..Default::default()
21033        };
21034        EditorElement::new(
21035            &self.prompt,
21036            EditorStyle {
21037                background: cx.theme().colors().editor_background,
21038                local_player: cx.theme().players().local(),
21039                text: text_style,
21040                ..Default::default()
21041            },
21042        )
21043    }
21044}
21045
21046impl Render for BreakpointPromptEditor {
21047    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21048        let gutter_dimensions = *self.gutter_dimensions.lock();
21049        h_flex()
21050            .key_context("Editor")
21051            .bg(cx.theme().colors().editor_background)
21052            .border_y_1()
21053            .border_color(cx.theme().status().info_border)
21054            .size_full()
21055            .py(window.line_height() / 2.5)
21056            .on_action(cx.listener(Self::confirm))
21057            .on_action(cx.listener(Self::cancel))
21058            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21059            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21060    }
21061}
21062
21063impl Focusable for BreakpointPromptEditor {
21064    fn focus_handle(&self, cx: &App) -> FocusHandle {
21065        self.prompt.focus_handle(cx)
21066    }
21067}
21068
21069fn all_edits_insertions_or_deletions(
21070    edits: &Vec<(Range<Anchor>, String)>,
21071    snapshot: &MultiBufferSnapshot,
21072) -> bool {
21073    let mut all_insertions = true;
21074    let mut all_deletions = true;
21075
21076    for (range, new_text) in edits.iter() {
21077        let range_is_empty = range.to_offset(&snapshot).is_empty();
21078        let text_is_empty = new_text.is_empty();
21079
21080        if range_is_empty != text_is_empty {
21081            if range_is_empty {
21082                all_deletions = false;
21083            } else {
21084                all_insertions = false;
21085            }
21086        } else {
21087            return false;
21088        }
21089
21090        if !all_insertions && !all_deletions {
21091            return false;
21092        }
21093    }
21094    all_insertions || all_deletions
21095}
21096
21097struct MissingEditPredictionKeybindingTooltip;
21098
21099impl Render for MissingEditPredictionKeybindingTooltip {
21100    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21101        ui::tooltip_container(window, cx, |container, _, cx| {
21102            container
21103                .flex_shrink_0()
21104                .max_w_80()
21105                .min_h(rems_from_px(124.))
21106                .justify_between()
21107                .child(
21108                    v_flex()
21109                        .flex_1()
21110                        .text_ui_sm(cx)
21111                        .child(Label::new("Conflict with Accept Keybinding"))
21112                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21113                )
21114                .child(
21115                    h_flex()
21116                        .pb_1()
21117                        .gap_1()
21118                        .items_end()
21119                        .w_full()
21120                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21121                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21122                        }))
21123                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21124                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21125                        })),
21126                )
21127        })
21128    }
21129}
21130
21131#[derive(Debug, Clone, Copy, PartialEq)]
21132pub struct LineHighlight {
21133    pub background: Background,
21134    pub border: Option<gpui::Hsla>,
21135    pub include_gutter: bool,
21136    pub type_id: Option<TypeId>,
21137}
21138
21139fn render_diff_hunk_controls(
21140    row: u32,
21141    status: &DiffHunkStatus,
21142    hunk_range: Range<Anchor>,
21143    is_created_file: bool,
21144    line_height: Pixels,
21145    editor: &Entity<Editor>,
21146    _window: &mut Window,
21147    cx: &mut App,
21148) -> AnyElement {
21149    h_flex()
21150        .h(line_height)
21151        .mr_1()
21152        .gap_1()
21153        .px_0p5()
21154        .pb_1()
21155        .border_x_1()
21156        .border_b_1()
21157        .border_color(cx.theme().colors().border_variant)
21158        .rounded_b_lg()
21159        .bg(cx.theme().colors().editor_background)
21160        .gap_1()
21161        .occlude()
21162        .shadow_md()
21163        .child(if status.has_secondary_hunk() {
21164            Button::new(("stage", row as u64), "Stage")
21165                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21166                .tooltip({
21167                    let focus_handle = editor.focus_handle(cx);
21168                    move |window, cx| {
21169                        Tooltip::for_action_in(
21170                            "Stage Hunk",
21171                            &::git::ToggleStaged,
21172                            &focus_handle,
21173                            window,
21174                            cx,
21175                        )
21176                    }
21177                })
21178                .on_click({
21179                    let editor = editor.clone();
21180                    move |_event, _window, cx| {
21181                        editor.update(cx, |editor, cx| {
21182                            editor.stage_or_unstage_diff_hunks(
21183                                true,
21184                                vec![hunk_range.start..hunk_range.start],
21185                                cx,
21186                            );
21187                        });
21188                    }
21189                })
21190        } else {
21191            Button::new(("unstage", row as u64), "Unstage")
21192                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21193                .tooltip({
21194                    let focus_handle = editor.focus_handle(cx);
21195                    move |window, cx| {
21196                        Tooltip::for_action_in(
21197                            "Unstage Hunk",
21198                            &::git::ToggleStaged,
21199                            &focus_handle,
21200                            window,
21201                            cx,
21202                        )
21203                    }
21204                })
21205                .on_click({
21206                    let editor = editor.clone();
21207                    move |_event, _window, cx| {
21208                        editor.update(cx, |editor, cx| {
21209                            editor.stage_or_unstage_diff_hunks(
21210                                false,
21211                                vec![hunk_range.start..hunk_range.start],
21212                                cx,
21213                            );
21214                        });
21215                    }
21216                })
21217        })
21218        .child(
21219            Button::new(("restore", row as u64), "Restore")
21220                .tooltip({
21221                    let focus_handle = editor.focus_handle(cx);
21222                    move |window, cx| {
21223                        Tooltip::for_action_in(
21224                            "Restore Hunk",
21225                            &::git::Restore,
21226                            &focus_handle,
21227                            window,
21228                            cx,
21229                        )
21230                    }
21231                })
21232                .on_click({
21233                    let editor = editor.clone();
21234                    move |_event, window, cx| {
21235                        editor.update(cx, |editor, cx| {
21236                            let snapshot = editor.snapshot(window, cx);
21237                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21238                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21239                        });
21240                    }
21241                })
21242                .disabled(is_created_file),
21243        )
21244        .when(
21245            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21246            |el| {
21247                el.child(
21248                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21249                        .shape(IconButtonShape::Square)
21250                        .icon_size(IconSize::Small)
21251                        // .disabled(!has_multiple_hunks)
21252                        .tooltip({
21253                            let focus_handle = editor.focus_handle(cx);
21254                            move |window, cx| {
21255                                Tooltip::for_action_in(
21256                                    "Next Hunk",
21257                                    &GoToHunk,
21258                                    &focus_handle,
21259                                    window,
21260                                    cx,
21261                                )
21262                            }
21263                        })
21264                        .on_click({
21265                            let editor = editor.clone();
21266                            move |_event, window, cx| {
21267                                editor.update(cx, |editor, cx| {
21268                                    let snapshot = editor.snapshot(window, cx);
21269                                    let position =
21270                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21271                                    editor.go_to_hunk_before_or_after_position(
21272                                        &snapshot,
21273                                        position,
21274                                        Direction::Next,
21275                                        window,
21276                                        cx,
21277                                    );
21278                                    editor.expand_selected_diff_hunks(cx);
21279                                });
21280                            }
21281                        }),
21282                )
21283                .child(
21284                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21285                        .shape(IconButtonShape::Square)
21286                        .icon_size(IconSize::Small)
21287                        // .disabled(!has_multiple_hunks)
21288                        .tooltip({
21289                            let focus_handle = editor.focus_handle(cx);
21290                            move |window, cx| {
21291                                Tooltip::for_action_in(
21292                                    "Previous Hunk",
21293                                    &GoToPreviousHunk,
21294                                    &focus_handle,
21295                                    window,
21296                                    cx,
21297                                )
21298                            }
21299                        })
21300                        .on_click({
21301                            let editor = editor.clone();
21302                            move |_event, window, cx| {
21303                                editor.update(cx, |editor, cx| {
21304                                    let snapshot = editor.snapshot(window, cx);
21305                                    let point =
21306                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21307                                    editor.go_to_hunk_before_or_after_position(
21308                                        &snapshot,
21309                                        point,
21310                                        Direction::Prev,
21311                                        window,
21312                                        cx,
21313                                    );
21314                                    editor.expand_selected_diff_hunks(cx);
21315                                });
21316                            }
21317                        }),
21318                )
21319            },
21320        )
21321        .into_any_element()
21322}