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 local_player: PlayerColor,
  521    pub text: TextStyle,
  522    pub scrollbar_width: Pixels,
  523    pub syntax: Arc<SyntaxTheme>,
  524    pub status: StatusColors,
  525    pub inlay_hints_style: HighlightStyle,
  526    pub inline_completion_styles: InlineCompletionStyles,
  527    pub unnecessary_code_fade: f32,
  528}
  529
  530impl Default for EditorStyle {
  531    fn default() -> Self {
  532        Self {
  533            background: Hsla::default(),
  534            local_player: PlayerColor::default(),
  535            text: TextStyle::default(),
  536            scrollbar_width: Pixels::default(),
  537            syntax: Default::default(),
  538            // HACK: Status colors don't have a real default.
  539            // We should look into removing the status colors from the editor
  540            // style and retrieve them directly from the theme.
  541            status: StatusColors::dark(),
  542            inlay_hints_style: HighlightStyle::default(),
  543            inline_completion_styles: InlineCompletionStyles {
  544                insertion: HighlightStyle::default(),
  545                whitespace: HighlightStyle::default(),
  546            },
  547            unnecessary_code_fade: Default::default(),
  548        }
  549    }
  550}
  551
  552pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  553    let show_background = language_settings::language_settings(None, None, cx)
  554        .inlay_hints
  555        .show_background;
  556
  557    HighlightStyle {
  558        color: Some(cx.theme().status().hint),
  559        background_color: show_background.then(|| cx.theme().status().hint_background),
  560        ..HighlightStyle::default()
  561    }
  562}
  563
  564pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  565    InlineCompletionStyles {
  566        insertion: HighlightStyle {
  567            color: Some(cx.theme().status().predictive),
  568            ..HighlightStyle::default()
  569        },
  570        whitespace: HighlightStyle {
  571            background_color: Some(cx.theme().status().created_background),
  572            ..HighlightStyle::default()
  573        },
  574    }
  575}
  576
  577type CompletionId = usize;
  578
  579pub(crate) enum EditDisplayMode {
  580    TabAccept,
  581    DiffPopover,
  582    Inline,
  583}
  584
  585enum InlineCompletion {
  586    Edit {
  587        edits: Vec<(Range<Anchor>, String)>,
  588        edit_preview: Option<EditPreview>,
  589        display_mode: EditDisplayMode,
  590        snapshot: BufferSnapshot,
  591    },
  592    Move {
  593        target: Anchor,
  594        snapshot: BufferSnapshot,
  595    },
  596}
  597
  598struct InlineCompletionState {
  599    inlay_ids: Vec<InlayId>,
  600    completion: InlineCompletion,
  601    completion_id: Option<SharedString>,
  602    invalidation_range: Range<Anchor>,
  603}
  604
  605enum EditPredictionSettings {
  606    Disabled,
  607    Enabled {
  608        show_in_menu: bool,
  609        preview_requires_modifier: bool,
  610    },
  611}
  612
  613enum InlineCompletionHighlight {}
  614
  615#[derive(Debug, Clone)]
  616struct InlineDiagnostic {
  617    message: SharedString,
  618    group_id: usize,
  619    is_primary: bool,
  620    start: Point,
  621    severity: DiagnosticSeverity,
  622}
  623
  624pub enum MenuInlineCompletionsPolicy {
  625    Never,
  626    ByProvider,
  627}
  628
  629pub enum EditPredictionPreview {
  630    /// Modifier is not pressed
  631    Inactive { released_too_fast: bool },
  632    /// Modifier pressed
  633    Active {
  634        since: Instant,
  635        previous_scroll_position: Option<ScrollAnchor>,
  636    },
  637}
  638
  639impl EditPredictionPreview {
  640    pub fn released_too_fast(&self) -> bool {
  641        match self {
  642            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  643            EditPredictionPreview::Active { .. } => false,
  644        }
  645    }
  646
  647    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  648        if let EditPredictionPreview::Active {
  649            previous_scroll_position,
  650            ..
  651        } = self
  652        {
  653            *previous_scroll_position = scroll_position;
  654        }
  655    }
  656}
  657
  658pub struct ContextMenuOptions {
  659    pub min_entries_visible: usize,
  660    pub max_entries_visible: usize,
  661    pub placement: Option<ContextMenuPlacement>,
  662}
  663
  664#[derive(Debug, Clone, PartialEq, Eq)]
  665pub enum ContextMenuPlacement {
  666    Above,
  667    Below,
  668}
  669
  670#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  671struct EditorActionId(usize);
  672
  673impl EditorActionId {
  674    pub fn post_inc(&mut self) -> Self {
  675        let answer = self.0;
  676
  677        *self = Self(answer + 1);
  678
  679        Self(answer)
  680    }
  681}
  682
  683// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  684// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  685
  686type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  687type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  688
  689#[derive(Default)]
  690struct ScrollbarMarkerState {
  691    scrollbar_size: Size<Pixels>,
  692    dirty: bool,
  693    markers: Arc<[PaintQuad]>,
  694    pending_refresh: Option<Task<Result<()>>>,
  695}
  696
  697impl ScrollbarMarkerState {
  698    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  699        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  700    }
  701}
  702
  703#[derive(Clone, Debug)]
  704struct RunnableTasks {
  705    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  706    offset: multi_buffer::Anchor,
  707    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  708    column: u32,
  709    // Values of all named captures, including those starting with '_'
  710    extra_variables: HashMap<String, String>,
  711    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  712    context_range: Range<BufferOffset>,
  713}
  714
  715impl RunnableTasks {
  716    fn resolve<'a>(
  717        &'a self,
  718        cx: &'a task::TaskContext,
  719    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  720        self.templates.iter().filter_map(|(kind, template)| {
  721            template
  722                .resolve_task(&kind.to_id_base(), cx)
  723                .map(|task| (kind.clone(), task))
  724        })
  725    }
  726}
  727
  728#[derive(Clone)]
  729struct ResolvedTasks {
  730    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  731    position: Anchor,
  732}
  733
  734#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  735struct BufferOffset(usize);
  736
  737// Addons allow storing per-editor state in other crates (e.g. Vim)
  738pub trait Addon: 'static {
  739    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  740
  741    fn render_buffer_header_controls(
  742        &self,
  743        _: &ExcerptInfo,
  744        _: &Window,
  745        _: &App,
  746    ) -> Option<AnyElement> {
  747        None
  748    }
  749
  750    fn to_any(&self) -> &dyn std::any::Any;
  751
  752    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  753        None
  754    }
  755}
  756
  757/// A set of caret positions, registered when the editor was edited.
  758pub struct ChangeList {
  759    changes: Vec<Vec<Anchor>>,
  760    /// Currently "selected" change.
  761    position: Option<usize>,
  762}
  763
  764impl ChangeList {
  765    pub fn new() -> Self {
  766        Self {
  767            changes: Vec::new(),
  768            position: None,
  769        }
  770    }
  771
  772    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  773    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  774    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  775        if self.changes.is_empty() {
  776            return None;
  777        }
  778
  779        let prev = self.position.unwrap_or(self.changes.len());
  780        let next = if direction == Direction::Prev {
  781            prev.saturating_sub(count)
  782        } else {
  783            (prev + count).min(self.changes.len() - 1)
  784        };
  785        self.position = Some(next);
  786        self.changes.get(next).map(|anchors| anchors.as_slice())
  787    }
  788
  789    /// Adds a new change to the list, resetting the change list position.
  790    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  791        self.position.take();
  792        if pop_state {
  793            self.changes.pop();
  794        }
  795        self.changes.push(new_positions.clone());
  796    }
  797
  798    pub fn last(&self) -> Option<&[Anchor]> {
  799        self.changes.last().map(|anchors| anchors.as_slice())
  800    }
  801}
  802
  803#[derive(Clone)]
  804struct InlineBlamePopoverState {
  805    scroll_handle: ScrollHandle,
  806    commit_message: Option<ParsedCommitMessage>,
  807    markdown: Entity<Markdown>,
  808}
  809
  810struct InlineBlamePopover {
  811    position: gpui::Point<Pixels>,
  812    show_task: Option<Task<()>>,
  813    hide_task: Option<Task<()>>,
  814    popover_bounds: Option<Bounds<Pixels>>,
  815    popover_state: InlineBlamePopoverState,
  816}
  817
  818/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  819/// a breakpoint on them.
  820#[derive(Clone, Copy, Debug)]
  821struct PhantomBreakpointIndicator {
  822    display_row: DisplayRow,
  823    /// There's a small debounce between hovering over the line and showing the indicator.
  824    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  825    is_active: bool,
  826    collides_with_existing_breakpoint: bool,
  827}
  828/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  829///
  830/// See the [module level documentation](self) for more information.
  831pub struct Editor {
  832    focus_handle: FocusHandle,
  833    last_focused_descendant: Option<WeakFocusHandle>,
  834    /// The text buffer being edited
  835    buffer: Entity<MultiBuffer>,
  836    /// Map of how text in the buffer should be displayed.
  837    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  838    pub display_map: Entity<DisplayMap>,
  839    pub selections: SelectionsCollection,
  840    pub scroll_manager: ScrollManager,
  841    /// When inline assist editors are linked, they all render cursors because
  842    /// typing enters text into each of them, even the ones that aren't focused.
  843    pub(crate) show_cursor_when_unfocused: bool,
  844    columnar_selection_tail: Option<Anchor>,
  845    add_selections_state: Option<AddSelectionsState>,
  846    select_next_state: Option<SelectNextState>,
  847    select_prev_state: Option<SelectNextState>,
  848    selection_history: SelectionHistory,
  849    autoclose_regions: Vec<AutocloseRegion>,
  850    snippet_stack: InvalidationStack<SnippetState>,
  851    select_syntax_node_history: SelectSyntaxNodeHistory,
  852    ime_transaction: Option<TransactionId>,
  853    active_diagnostics: ActiveDiagnostic,
  854    show_inline_diagnostics: bool,
  855    inline_diagnostics_update: Task<()>,
  856    inline_diagnostics_enabled: bool,
  857    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  858    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  859    hard_wrap: Option<usize>,
  860
  861    // TODO: make this a access method
  862    pub project: Option<Entity<Project>>,
  863    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  864    completion_provider: Option<Box<dyn CompletionProvider>>,
  865    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  866    blink_manager: Entity<BlinkManager>,
  867    show_cursor_names: bool,
  868    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  869    pub show_local_selections: bool,
  870    mode: EditorMode,
  871    show_breadcrumbs: bool,
  872    show_gutter: bool,
  873    show_scrollbars: bool,
  874    disable_expand_excerpt_buttons: bool,
  875    show_line_numbers: Option<bool>,
  876    use_relative_line_numbers: Option<bool>,
  877    show_git_diff_gutter: Option<bool>,
  878    show_code_actions: Option<bool>,
  879    show_runnables: Option<bool>,
  880    show_breakpoints: Option<bool>,
  881    show_wrap_guides: Option<bool>,
  882    show_indent_guides: Option<bool>,
  883    placeholder_text: Option<Arc<str>>,
  884    highlight_order: usize,
  885    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  886    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  887    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  888    scrollbar_marker_state: ScrollbarMarkerState,
  889    active_indent_guides_state: ActiveIndentGuidesState,
  890    nav_history: Option<ItemNavHistory>,
  891    context_menu: RefCell<Option<CodeContextMenu>>,
  892    context_menu_options: Option<ContextMenuOptions>,
  893    mouse_context_menu: Option<MouseContextMenu>,
  894    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  895    inline_blame_popover: Option<InlineBlamePopover>,
  896    signature_help_state: SignatureHelpState,
  897    auto_signature_help: Option<bool>,
  898    find_all_references_task_sources: Vec<Anchor>,
  899    next_completion_id: CompletionId,
  900    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  901    code_actions_task: Option<Task<Result<()>>>,
  902    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  903    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  904    document_highlights_task: Option<Task<()>>,
  905    linked_editing_range_task: Option<Task<Option<()>>>,
  906    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  907    pending_rename: Option<RenameState>,
  908    searchable: bool,
  909    cursor_shape: CursorShape,
  910    current_line_highlight: Option<CurrentLineHighlight>,
  911    collapse_matches: bool,
  912    autoindent_mode: Option<AutoindentMode>,
  913    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  914    input_enabled: bool,
  915    use_modal_editing: bool,
  916    read_only: bool,
  917    leader_id: Option<CollaboratorId>,
  918    remote_id: Option<ViewId>,
  919    pub hover_state: HoverState,
  920    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  921    gutter_hovered: bool,
  922    hovered_link_state: Option<HoveredLinkState>,
  923    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  924    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  925    active_inline_completion: Option<InlineCompletionState>,
  926    /// Used to prevent flickering as the user types while the menu is open
  927    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  928    edit_prediction_settings: EditPredictionSettings,
  929    inline_completions_hidden_for_vim_mode: bool,
  930    show_inline_completions_override: Option<bool>,
  931    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  932    edit_prediction_preview: EditPredictionPreview,
  933    edit_prediction_indent_conflict: bool,
  934    edit_prediction_requires_modifier_in_indent_conflict: bool,
  935    inlay_hint_cache: InlayHintCache,
  936    next_inlay_id: usize,
  937    _subscriptions: Vec<Subscription>,
  938    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  939    gutter_dimensions: GutterDimensions,
  940    style: Option<EditorStyle>,
  941    text_style_refinement: Option<TextStyleRefinement>,
  942    next_editor_action_id: EditorActionId,
  943    editor_actions:
  944        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  945    use_autoclose: bool,
  946    use_auto_surround: bool,
  947    auto_replace_emoji_shortcode: bool,
  948    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  949    show_git_blame_gutter: bool,
  950    show_git_blame_inline: bool,
  951    show_git_blame_inline_delay_task: Option<Task<()>>,
  952    git_blame_inline_enabled: bool,
  953    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  954    serialize_dirty_buffers: bool,
  955    show_selection_menu: Option<bool>,
  956    blame: Option<Entity<GitBlame>>,
  957    blame_subscription: Option<Subscription>,
  958    custom_context_menu: Option<
  959        Box<
  960            dyn 'static
  961                + Fn(
  962                    &mut Self,
  963                    DisplayPoint,
  964                    &mut Window,
  965                    &mut Context<Self>,
  966                ) -> Option<Entity<ui::ContextMenu>>,
  967        >,
  968    >,
  969    last_bounds: Option<Bounds<Pixels>>,
  970    last_position_map: Option<Rc<PositionMap>>,
  971    expect_bounds_change: Option<Bounds<Pixels>>,
  972    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  973    tasks_update_task: Option<Task<()>>,
  974    breakpoint_store: Option<Entity<BreakpointStore>>,
  975    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
  976    in_project_search: bool,
  977    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  978    breadcrumb_header: Option<String>,
  979    focused_block: Option<FocusedBlock>,
  980    next_scroll_position: NextScrollCursorCenterTopBottom,
  981    addons: HashMap<TypeId, Box<dyn Addon>>,
  982    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  983    load_diff_task: Option<Shared<Task<()>>>,
  984    /// Whether we are temporarily displaying a diff other than git's
  985    temporary_diff_override: bool,
  986    selection_mark_mode: bool,
  987    toggle_fold_multiple_buffers: Task<()>,
  988    _scroll_cursor_center_top_bottom_task: Task<()>,
  989    serialize_selections: Task<()>,
  990    serialize_folds: Task<()>,
  991    mouse_cursor_hidden: bool,
  992    hide_mouse_mode: HideMouseMode,
  993    pub change_list: ChangeList,
  994    inline_value_cache: InlineValueCache,
  995}
  996
  997#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  998enum NextScrollCursorCenterTopBottom {
  999    #[default]
 1000    Center,
 1001    Top,
 1002    Bottom,
 1003}
 1004
 1005impl NextScrollCursorCenterTopBottom {
 1006    fn next(&self) -> Self {
 1007        match self {
 1008            Self::Center => Self::Top,
 1009            Self::Top => Self::Bottom,
 1010            Self::Bottom => Self::Center,
 1011        }
 1012    }
 1013}
 1014
 1015#[derive(Clone)]
 1016pub struct EditorSnapshot {
 1017    pub mode: EditorMode,
 1018    show_gutter: bool,
 1019    show_line_numbers: Option<bool>,
 1020    show_git_diff_gutter: Option<bool>,
 1021    show_runnables: Option<bool>,
 1022    show_breakpoints: Option<bool>,
 1023    git_blame_gutter_max_author_length: Option<usize>,
 1024    pub display_snapshot: DisplaySnapshot,
 1025    pub placeholder_text: Option<Arc<str>>,
 1026    is_focused: bool,
 1027    scroll_anchor: ScrollAnchor,
 1028    ongoing_scroll: OngoingScroll,
 1029    current_line_highlight: CurrentLineHighlight,
 1030    gutter_hovered: bool,
 1031}
 1032
 1033#[derive(Default, Debug, Clone, Copy)]
 1034pub struct GutterDimensions {
 1035    pub left_padding: Pixels,
 1036    pub right_padding: Pixels,
 1037    pub width: Pixels,
 1038    pub margin: Pixels,
 1039    pub git_blame_entries_width: Option<Pixels>,
 1040}
 1041
 1042impl GutterDimensions {
 1043    fn default_with_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Self {
 1044        Self {
 1045            margin: Self::default_gutter_margin(font_id, font_size, cx),
 1046            ..Default::default()
 1047        }
 1048    }
 1049
 1050    fn default_gutter_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Pixels {
 1051        -cx.text_system().descent(font_id, font_size)
 1052    }
 1053    /// The full width of the space taken up by the gutter.
 1054    pub fn full_width(&self) -> Pixels {
 1055        self.margin + self.width
 1056    }
 1057
 1058    /// The width of the space reserved for the fold indicators,
 1059    /// use alongside 'justify_end' and `gutter_width` to
 1060    /// right align content with the line numbers
 1061    pub fn fold_area_width(&self) -> Pixels {
 1062        self.margin + self.right_padding
 1063    }
 1064}
 1065
 1066#[derive(Debug)]
 1067pub struct RemoteSelection {
 1068    pub replica_id: ReplicaId,
 1069    pub selection: Selection<Anchor>,
 1070    pub cursor_shape: CursorShape,
 1071    pub collaborator_id: CollaboratorId,
 1072    pub line_mode: bool,
 1073    pub user_name: Option<SharedString>,
 1074    pub color: PlayerColor,
 1075}
 1076
 1077#[derive(Clone, Debug)]
 1078struct SelectionHistoryEntry {
 1079    selections: Arc<[Selection<Anchor>]>,
 1080    select_next_state: Option<SelectNextState>,
 1081    select_prev_state: Option<SelectNextState>,
 1082    add_selections_state: Option<AddSelectionsState>,
 1083}
 1084
 1085enum SelectionHistoryMode {
 1086    Normal,
 1087    Undoing,
 1088    Redoing,
 1089}
 1090
 1091#[derive(Clone, PartialEq, Eq, Hash)]
 1092struct HoveredCursor {
 1093    replica_id: u16,
 1094    selection_id: usize,
 1095}
 1096
 1097impl Default for SelectionHistoryMode {
 1098    fn default() -> Self {
 1099        Self::Normal
 1100    }
 1101}
 1102
 1103#[derive(Default)]
 1104struct SelectionHistory {
 1105    #[allow(clippy::type_complexity)]
 1106    selections_by_transaction:
 1107        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1108    mode: SelectionHistoryMode,
 1109    undo_stack: VecDeque<SelectionHistoryEntry>,
 1110    redo_stack: VecDeque<SelectionHistoryEntry>,
 1111}
 1112
 1113impl SelectionHistory {
 1114    fn insert_transaction(
 1115        &mut self,
 1116        transaction_id: TransactionId,
 1117        selections: Arc<[Selection<Anchor>]>,
 1118    ) {
 1119        self.selections_by_transaction
 1120            .insert(transaction_id, (selections, None));
 1121    }
 1122
 1123    #[allow(clippy::type_complexity)]
 1124    fn transaction(
 1125        &self,
 1126        transaction_id: TransactionId,
 1127    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1128        self.selections_by_transaction.get(&transaction_id)
 1129    }
 1130
 1131    #[allow(clippy::type_complexity)]
 1132    fn transaction_mut(
 1133        &mut self,
 1134        transaction_id: TransactionId,
 1135    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1136        self.selections_by_transaction.get_mut(&transaction_id)
 1137    }
 1138
 1139    fn push(&mut self, entry: SelectionHistoryEntry) {
 1140        if !entry.selections.is_empty() {
 1141            match self.mode {
 1142                SelectionHistoryMode::Normal => {
 1143                    self.push_undo(entry);
 1144                    self.redo_stack.clear();
 1145                }
 1146                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1147                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1148            }
 1149        }
 1150    }
 1151
 1152    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1153        if self
 1154            .undo_stack
 1155            .back()
 1156            .map_or(true, |e| e.selections != entry.selections)
 1157        {
 1158            self.undo_stack.push_back(entry);
 1159            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1160                self.undo_stack.pop_front();
 1161            }
 1162        }
 1163    }
 1164
 1165    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1166        if self
 1167            .redo_stack
 1168            .back()
 1169            .map_or(true, |e| e.selections != entry.selections)
 1170        {
 1171            self.redo_stack.push_back(entry);
 1172            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1173                self.redo_stack.pop_front();
 1174            }
 1175        }
 1176    }
 1177}
 1178
 1179#[derive(Clone, Copy)]
 1180pub struct RowHighlightOptions {
 1181    pub autoscroll: bool,
 1182    pub include_gutter: bool,
 1183}
 1184
 1185impl Default for RowHighlightOptions {
 1186    fn default() -> Self {
 1187        Self {
 1188            autoscroll: Default::default(),
 1189            include_gutter: true,
 1190        }
 1191    }
 1192}
 1193
 1194struct RowHighlight {
 1195    index: usize,
 1196    range: Range<Anchor>,
 1197    color: Hsla,
 1198    options: RowHighlightOptions,
 1199    type_id: TypeId,
 1200}
 1201
 1202#[derive(Clone, Debug)]
 1203struct AddSelectionsState {
 1204    above: bool,
 1205    stack: Vec<usize>,
 1206}
 1207
 1208#[derive(Clone)]
 1209struct SelectNextState {
 1210    query: AhoCorasick,
 1211    wordwise: bool,
 1212    done: bool,
 1213}
 1214
 1215impl std::fmt::Debug for SelectNextState {
 1216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1217        f.debug_struct(std::any::type_name::<Self>())
 1218            .field("wordwise", &self.wordwise)
 1219            .field("done", &self.done)
 1220            .finish()
 1221    }
 1222}
 1223
 1224#[derive(Debug)]
 1225struct AutocloseRegion {
 1226    selection_id: usize,
 1227    range: Range<Anchor>,
 1228    pair: BracketPair,
 1229}
 1230
 1231#[derive(Debug)]
 1232struct SnippetState {
 1233    ranges: Vec<Vec<Range<Anchor>>>,
 1234    active_index: usize,
 1235    choices: Vec<Option<Vec<String>>>,
 1236}
 1237
 1238#[doc(hidden)]
 1239pub struct RenameState {
 1240    pub range: Range<Anchor>,
 1241    pub old_name: Arc<str>,
 1242    pub editor: Entity<Editor>,
 1243    block_id: CustomBlockId,
 1244}
 1245
 1246struct InvalidationStack<T>(Vec<T>);
 1247
 1248struct RegisteredInlineCompletionProvider {
 1249    provider: Arc<dyn InlineCompletionProviderHandle>,
 1250    _subscription: Subscription,
 1251}
 1252
 1253#[derive(Debug, PartialEq, Eq)]
 1254pub struct ActiveDiagnosticGroup {
 1255    pub active_range: Range<Anchor>,
 1256    pub active_message: String,
 1257    pub group_id: usize,
 1258    pub blocks: HashSet<CustomBlockId>,
 1259}
 1260
 1261#[derive(Debug, PartialEq, Eq)]
 1262#[allow(clippy::large_enum_variant)]
 1263pub(crate) enum ActiveDiagnostic {
 1264    None,
 1265    All,
 1266    Group(ActiveDiagnosticGroup),
 1267}
 1268
 1269#[derive(Serialize, Deserialize, Clone, Debug)]
 1270pub struct ClipboardSelection {
 1271    /// The number of bytes in this selection.
 1272    pub len: usize,
 1273    /// Whether this was a full-line selection.
 1274    pub is_entire_line: bool,
 1275    /// The indentation of the first line when this content was originally copied.
 1276    pub first_line_indent: u32,
 1277}
 1278
 1279// selections, scroll behavior, was newest selection reversed
 1280type SelectSyntaxNodeHistoryState = (
 1281    Box<[Selection<usize>]>,
 1282    SelectSyntaxNodeScrollBehavior,
 1283    bool,
 1284);
 1285
 1286#[derive(Default)]
 1287struct SelectSyntaxNodeHistory {
 1288    stack: Vec<SelectSyntaxNodeHistoryState>,
 1289    // disable temporarily to allow changing selections without losing the stack
 1290    pub disable_clearing: bool,
 1291}
 1292
 1293impl SelectSyntaxNodeHistory {
 1294    pub fn try_clear(&mut self) {
 1295        if !self.disable_clearing {
 1296            self.stack.clear();
 1297        }
 1298    }
 1299
 1300    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1301        self.stack.push(selection);
 1302    }
 1303
 1304    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1305        self.stack.pop()
 1306    }
 1307}
 1308
 1309enum SelectSyntaxNodeScrollBehavior {
 1310    CursorTop,
 1311    FitSelection,
 1312    CursorBottom,
 1313}
 1314
 1315#[derive(Debug)]
 1316pub(crate) struct NavigationData {
 1317    cursor_anchor: Anchor,
 1318    cursor_position: Point,
 1319    scroll_anchor: ScrollAnchor,
 1320    scroll_top_row: u32,
 1321}
 1322
 1323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1324pub enum GotoDefinitionKind {
 1325    Symbol,
 1326    Declaration,
 1327    Type,
 1328    Implementation,
 1329}
 1330
 1331#[derive(Debug, Clone)]
 1332enum InlayHintRefreshReason {
 1333    ModifiersChanged(bool),
 1334    Toggle(bool),
 1335    SettingsChange(InlayHintSettings),
 1336    NewLinesShown,
 1337    BufferEdited(HashSet<Arc<Language>>),
 1338    RefreshRequested,
 1339    ExcerptsRemoved(Vec<ExcerptId>),
 1340}
 1341
 1342impl InlayHintRefreshReason {
 1343    fn description(&self) -> &'static str {
 1344        match self {
 1345            Self::ModifiersChanged(_) => "modifiers changed",
 1346            Self::Toggle(_) => "toggle",
 1347            Self::SettingsChange(_) => "settings change",
 1348            Self::NewLinesShown => "new lines shown",
 1349            Self::BufferEdited(_) => "buffer edited",
 1350            Self::RefreshRequested => "refresh requested",
 1351            Self::ExcerptsRemoved(_) => "excerpts removed",
 1352        }
 1353    }
 1354}
 1355
 1356pub enum FormatTarget {
 1357    Buffers,
 1358    Ranges(Vec<Range<MultiBufferPoint>>),
 1359}
 1360
 1361pub(crate) struct FocusedBlock {
 1362    id: BlockId,
 1363    focus_handle: WeakFocusHandle,
 1364}
 1365
 1366#[derive(Clone)]
 1367enum JumpData {
 1368    MultiBufferRow {
 1369        row: MultiBufferRow,
 1370        line_offset_from_top: u32,
 1371    },
 1372    MultiBufferPoint {
 1373        excerpt_id: ExcerptId,
 1374        position: Point,
 1375        anchor: text::Anchor,
 1376        line_offset_from_top: u32,
 1377    },
 1378}
 1379
 1380pub enum MultibufferSelectionMode {
 1381    First,
 1382    All,
 1383}
 1384
 1385#[derive(Clone, Copy, Debug, Default)]
 1386pub struct RewrapOptions {
 1387    pub override_language_settings: bool,
 1388    pub preserve_existing_whitespace: bool,
 1389}
 1390
 1391impl Editor {
 1392    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1393        let buffer = cx.new(|cx| Buffer::local("", cx));
 1394        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1395        Self::new(
 1396            EditorMode::SingleLine { auto_width: false },
 1397            buffer,
 1398            None,
 1399            window,
 1400            cx,
 1401        )
 1402    }
 1403
 1404    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1405        let buffer = cx.new(|cx| Buffer::local("", cx));
 1406        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1407        Self::new(EditorMode::full(), buffer, None, window, cx)
 1408    }
 1409
 1410    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1411        let buffer = cx.new(|cx| Buffer::local("", cx));
 1412        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1413        Self::new(
 1414            EditorMode::SingleLine { auto_width: true },
 1415            buffer,
 1416            None,
 1417            window,
 1418            cx,
 1419        )
 1420    }
 1421
 1422    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1423        let buffer = cx.new(|cx| Buffer::local("", cx));
 1424        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1425        Self::new(
 1426            EditorMode::AutoHeight { max_lines },
 1427            buffer,
 1428            None,
 1429            window,
 1430            cx,
 1431        )
 1432    }
 1433
 1434    pub fn for_buffer(
 1435        buffer: Entity<Buffer>,
 1436        project: Option<Entity<Project>>,
 1437        window: &mut Window,
 1438        cx: &mut Context<Self>,
 1439    ) -> Self {
 1440        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1441        Self::new(EditorMode::full(), buffer, project, window, cx)
 1442    }
 1443
 1444    pub fn for_multibuffer(
 1445        buffer: Entity<MultiBuffer>,
 1446        project: Option<Entity<Project>>,
 1447        window: &mut Window,
 1448        cx: &mut Context<Self>,
 1449    ) -> Self {
 1450        Self::new(EditorMode::full(), buffer, project, window, cx)
 1451    }
 1452
 1453    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1454        let mut clone = Self::new(
 1455            self.mode,
 1456            self.buffer.clone(),
 1457            self.project.clone(),
 1458            window,
 1459            cx,
 1460        );
 1461        self.display_map.update(cx, |display_map, cx| {
 1462            let snapshot = display_map.snapshot(cx);
 1463            clone.display_map.update(cx, |display_map, cx| {
 1464                display_map.set_state(&snapshot, cx);
 1465            });
 1466        });
 1467        clone.folds_did_change(cx);
 1468        clone.selections.clone_state(&self.selections);
 1469        clone.scroll_manager.clone_state(&self.scroll_manager);
 1470        clone.searchable = self.searchable;
 1471        clone.read_only = self.read_only;
 1472        clone
 1473    }
 1474
 1475    pub fn new(
 1476        mode: EditorMode,
 1477        buffer: Entity<MultiBuffer>,
 1478        project: Option<Entity<Project>>,
 1479        window: &mut Window,
 1480        cx: &mut Context<Self>,
 1481    ) -> Self {
 1482        let style = window.text_style();
 1483        let font_size = style.font_size.to_pixels(window.rem_size());
 1484        let editor = cx.entity().downgrade();
 1485        let fold_placeholder = FoldPlaceholder {
 1486            constrain_width: true,
 1487            render: Arc::new(move |fold_id, fold_range, cx| {
 1488                let editor = editor.clone();
 1489                div()
 1490                    .id(fold_id)
 1491                    .bg(cx.theme().colors().ghost_element_background)
 1492                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1493                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1494                    .rounded_xs()
 1495                    .size_full()
 1496                    .cursor_pointer()
 1497                    .child("")
 1498                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1499                    .on_click(move |_, _window, cx| {
 1500                        editor
 1501                            .update(cx, |editor, cx| {
 1502                                editor.unfold_ranges(
 1503                                    &[fold_range.start..fold_range.end],
 1504                                    true,
 1505                                    false,
 1506                                    cx,
 1507                                );
 1508                                cx.stop_propagation();
 1509                            })
 1510                            .ok();
 1511                    })
 1512                    .into_any()
 1513            }),
 1514            merge_adjacent: true,
 1515            ..Default::default()
 1516        };
 1517        let display_map = cx.new(|cx| {
 1518            DisplayMap::new(
 1519                buffer.clone(),
 1520                style.font(),
 1521                font_size,
 1522                None,
 1523                FILE_HEADER_HEIGHT,
 1524                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1525                fold_placeholder,
 1526                cx,
 1527            )
 1528        });
 1529
 1530        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1531
 1532        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1533
 1534        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1535            .then(|| language_settings::SoftWrap::None);
 1536
 1537        let mut project_subscriptions = Vec::new();
 1538        if mode.is_full() {
 1539            if let Some(project) = project.as_ref() {
 1540                project_subscriptions.push(cx.subscribe_in(
 1541                    project,
 1542                    window,
 1543                    |editor, _, event, window, cx| match event {
 1544                        project::Event::RefreshCodeLens => {
 1545                            // we always query lens with actions, without storing them, always refreshing them
 1546                        }
 1547                        project::Event::RefreshInlayHints => {
 1548                            editor
 1549                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1550                        }
 1551                        project::Event::SnippetEdit(id, snippet_edits) => {
 1552                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1553                                let focus_handle = editor.focus_handle(cx);
 1554                                if focus_handle.is_focused(window) {
 1555                                    let snapshot = buffer.read(cx).snapshot();
 1556                                    for (range, snippet) in snippet_edits {
 1557                                        let editor_range =
 1558                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1559                                        editor
 1560                                            .insert_snippet(
 1561                                                &[editor_range],
 1562                                                snippet.clone(),
 1563                                                window,
 1564                                                cx,
 1565                                            )
 1566                                            .ok();
 1567                                    }
 1568                                }
 1569                            }
 1570                        }
 1571                        _ => {}
 1572                    },
 1573                ));
 1574                if let Some(task_inventory) = project
 1575                    .read(cx)
 1576                    .task_store()
 1577                    .read(cx)
 1578                    .task_inventory()
 1579                    .cloned()
 1580                {
 1581                    project_subscriptions.push(cx.observe_in(
 1582                        &task_inventory,
 1583                        window,
 1584                        |editor, _, window, cx| {
 1585                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1586                        },
 1587                    ));
 1588                };
 1589
 1590                project_subscriptions.push(cx.subscribe_in(
 1591                    &project.read(cx).breakpoint_store(),
 1592                    window,
 1593                    |editor, _, event, window, cx| match event {
 1594                        BreakpointStoreEvent::ClearDebugLines => {
 1595                            editor.clear_row_highlights::<ActiveDebugLine>();
 1596                            editor.refresh_inline_values(cx);
 1597                        }
 1598                        BreakpointStoreEvent::SetDebugLine => {
 1599                            if editor.go_to_active_debug_line(window, cx) {
 1600                                cx.stop_propagation();
 1601                            }
 1602
 1603                            editor.refresh_inline_values(cx);
 1604                        }
 1605                        _ => {}
 1606                    },
 1607                ));
 1608            }
 1609        }
 1610
 1611        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1612
 1613        let inlay_hint_settings =
 1614            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1615        let focus_handle = cx.focus_handle();
 1616        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1617            .detach();
 1618        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1619            .detach();
 1620        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1621            .detach();
 1622        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1623            .detach();
 1624
 1625        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1626            Some(false)
 1627        } else {
 1628            None
 1629        };
 1630
 1631        let breakpoint_store = match (mode, project.as_ref()) {
 1632            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1633            _ => None,
 1634        };
 1635
 1636        let mut code_action_providers = Vec::new();
 1637        let mut load_uncommitted_diff = None;
 1638        if let Some(project) = project.clone() {
 1639            load_uncommitted_diff = Some(
 1640                update_uncommitted_diff_for_buffer(
 1641                    cx.entity(),
 1642                    &project,
 1643                    buffer.read(cx).all_buffers(),
 1644                    buffer.clone(),
 1645                    cx,
 1646                )
 1647                .shared(),
 1648            );
 1649            code_action_providers.push(Rc::new(project) as Rc<_>);
 1650        }
 1651
 1652        let mut this = Self {
 1653            focus_handle,
 1654            show_cursor_when_unfocused: false,
 1655            last_focused_descendant: None,
 1656            buffer: buffer.clone(),
 1657            display_map: display_map.clone(),
 1658            selections,
 1659            scroll_manager: ScrollManager::new(cx),
 1660            columnar_selection_tail: None,
 1661            add_selections_state: None,
 1662            select_next_state: None,
 1663            select_prev_state: None,
 1664            selection_history: Default::default(),
 1665            autoclose_regions: Default::default(),
 1666            snippet_stack: Default::default(),
 1667            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1668            ime_transaction: Default::default(),
 1669            active_diagnostics: ActiveDiagnostic::None,
 1670            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1671            inline_diagnostics_update: Task::ready(()),
 1672            inline_diagnostics: Vec::new(),
 1673            soft_wrap_mode_override,
 1674            hard_wrap: None,
 1675            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1676            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1677            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1678            project,
 1679            blink_manager: blink_manager.clone(),
 1680            show_local_selections: true,
 1681            show_scrollbars: true,
 1682            mode,
 1683            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1684            show_gutter: mode.is_full(),
 1685            show_line_numbers: None,
 1686            use_relative_line_numbers: None,
 1687            disable_expand_excerpt_buttons: false,
 1688            show_git_diff_gutter: None,
 1689            show_code_actions: None,
 1690            show_runnables: None,
 1691            show_breakpoints: None,
 1692            show_wrap_guides: None,
 1693            show_indent_guides,
 1694            placeholder_text: None,
 1695            highlight_order: 0,
 1696            highlighted_rows: HashMap::default(),
 1697            background_highlights: Default::default(),
 1698            gutter_highlights: TreeMap::default(),
 1699            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1700            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1701            nav_history: None,
 1702            context_menu: RefCell::new(None),
 1703            context_menu_options: None,
 1704            mouse_context_menu: None,
 1705            completion_tasks: Default::default(),
 1706            inline_blame_popover: Default::default(),
 1707            signature_help_state: SignatureHelpState::default(),
 1708            auto_signature_help: None,
 1709            find_all_references_task_sources: Vec::new(),
 1710            next_completion_id: 0,
 1711            next_inlay_id: 0,
 1712            code_action_providers,
 1713            available_code_actions: Default::default(),
 1714            code_actions_task: Default::default(),
 1715            quick_selection_highlight_task: Default::default(),
 1716            debounced_selection_highlight_task: Default::default(),
 1717            document_highlights_task: Default::default(),
 1718            linked_editing_range_task: Default::default(),
 1719            pending_rename: Default::default(),
 1720            searchable: true,
 1721            cursor_shape: EditorSettings::get_global(cx)
 1722                .cursor_shape
 1723                .unwrap_or_default(),
 1724            current_line_highlight: None,
 1725            autoindent_mode: Some(AutoindentMode::EachLine),
 1726            collapse_matches: false,
 1727            workspace: None,
 1728            input_enabled: true,
 1729            use_modal_editing: mode.is_full(),
 1730            read_only: false,
 1731            use_autoclose: true,
 1732            use_auto_surround: true,
 1733            auto_replace_emoji_shortcode: false,
 1734            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1735            leader_id: None,
 1736            remote_id: None,
 1737            hover_state: Default::default(),
 1738            pending_mouse_down: None,
 1739            hovered_link_state: Default::default(),
 1740            edit_prediction_provider: None,
 1741            active_inline_completion: None,
 1742            stale_inline_completion_in_menu: None,
 1743            edit_prediction_preview: EditPredictionPreview::Inactive {
 1744                released_too_fast: false,
 1745            },
 1746            inline_diagnostics_enabled: mode.is_full(),
 1747            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1748            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1749
 1750            gutter_hovered: false,
 1751            pixel_position_of_newest_cursor: None,
 1752            last_bounds: None,
 1753            last_position_map: None,
 1754            expect_bounds_change: None,
 1755            gutter_dimensions: GutterDimensions::default(),
 1756            style: None,
 1757            show_cursor_names: false,
 1758            hovered_cursors: Default::default(),
 1759            next_editor_action_id: EditorActionId::default(),
 1760            editor_actions: Rc::default(),
 1761            inline_completions_hidden_for_vim_mode: false,
 1762            show_inline_completions_override: None,
 1763            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1764            edit_prediction_settings: EditPredictionSettings::Disabled,
 1765            edit_prediction_indent_conflict: false,
 1766            edit_prediction_requires_modifier_in_indent_conflict: true,
 1767            custom_context_menu: None,
 1768            show_git_blame_gutter: false,
 1769            show_git_blame_inline: false,
 1770            show_selection_menu: None,
 1771            show_git_blame_inline_delay_task: None,
 1772            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1773            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1774            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1775                .session
 1776                .restore_unsaved_buffers,
 1777            blame: None,
 1778            blame_subscription: None,
 1779            tasks: Default::default(),
 1780
 1781            breakpoint_store,
 1782            gutter_breakpoint_indicator: (None, None),
 1783            _subscriptions: vec![
 1784                cx.observe(&buffer, Self::on_buffer_changed),
 1785                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1786                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1787                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1788                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1789                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1790                cx.observe_window_activation(window, |editor, window, cx| {
 1791                    let active = window.is_window_active();
 1792                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1793                        if active {
 1794                            blink_manager.enable(cx);
 1795                        } else {
 1796                            blink_manager.disable(cx);
 1797                        }
 1798                    });
 1799                }),
 1800            ],
 1801            tasks_update_task: None,
 1802            linked_edit_ranges: Default::default(),
 1803            in_project_search: false,
 1804            previous_search_ranges: None,
 1805            breadcrumb_header: None,
 1806            focused_block: None,
 1807            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1808            addons: HashMap::default(),
 1809            registered_buffers: HashMap::default(),
 1810            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1811            selection_mark_mode: false,
 1812            toggle_fold_multiple_buffers: Task::ready(()),
 1813            serialize_selections: Task::ready(()),
 1814            serialize_folds: Task::ready(()),
 1815            text_style_refinement: None,
 1816            load_diff_task: load_uncommitted_diff,
 1817            temporary_diff_override: false,
 1818            mouse_cursor_hidden: false,
 1819            hide_mouse_mode: EditorSettings::get_global(cx)
 1820                .hide_mouse
 1821                .unwrap_or_default(),
 1822            change_list: ChangeList::new(),
 1823        };
 1824        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1825            this._subscriptions
 1826                .push(cx.observe(breakpoints, |_, _, cx| {
 1827                    cx.notify();
 1828                }));
 1829        }
 1830        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1831        this._subscriptions.extend(project_subscriptions);
 1832
 1833        this._subscriptions.push(cx.subscribe_in(
 1834            &cx.entity(),
 1835            window,
 1836            |editor, _, e: &EditorEvent, window, cx| match e {
 1837                EditorEvent::ScrollPositionChanged { local, .. } => {
 1838                    if *local {
 1839                        let new_anchor = editor.scroll_manager.anchor();
 1840                        let snapshot = editor.snapshot(window, cx);
 1841                        editor.update_restoration_data(cx, move |data| {
 1842                            data.scroll_position = (
 1843                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1844                                new_anchor.offset,
 1845                            );
 1846                        });
 1847                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1848                        editor.inline_blame_popover.take();
 1849                    }
 1850                }
 1851                EditorEvent::Edited { .. } => {
 1852                    if !vim_enabled(cx) {
 1853                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1854                        let pop_state = editor
 1855                            .change_list
 1856                            .last()
 1857                            .map(|previous| {
 1858                                previous.len() == selections.len()
 1859                                    && previous.iter().enumerate().all(|(ix, p)| {
 1860                                        p.to_display_point(&map).row()
 1861                                            == selections[ix].head().row()
 1862                                    })
 1863                            })
 1864                            .unwrap_or(false);
 1865                        let new_positions = selections
 1866                            .into_iter()
 1867                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1868                            .collect();
 1869                        editor
 1870                            .change_list
 1871                            .push_to_change_list(pop_state, new_positions);
 1872                    }
 1873                }
 1874                _ => (),
 1875            },
 1876        ));
 1877
 1878        if let Some(dap_store) = this
 1879            .project
 1880            .as_ref()
 1881            .map(|project| project.read(cx).dap_store())
 1882        {
 1883            let weak_editor = cx.weak_entity();
 1884
 1885            this._subscriptions
 1886                .push(
 1887                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1888                        let session_entity = cx.entity();
 1889                        weak_editor
 1890                            .update(cx, |editor, cx| {
 1891                                editor._subscriptions.push(
 1892                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1893                                );
 1894                            })
 1895                            .ok();
 1896                    }),
 1897                );
 1898
 1899            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1900                this._subscriptions
 1901                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1902            }
 1903        }
 1904
 1905        this.end_selection(window, cx);
 1906        this.scroll_manager.show_scrollbars(window, cx);
 1907        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1908
 1909        if mode.is_full() {
 1910            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1911            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1912
 1913            if this.git_blame_inline_enabled {
 1914                this.git_blame_inline_enabled = true;
 1915                this.start_git_blame_inline(false, window, cx);
 1916            }
 1917
 1918            this.go_to_active_debug_line(window, cx);
 1919
 1920            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1921                if let Some(project) = this.project.as_ref() {
 1922                    let handle = project.update(cx, |project, cx| {
 1923                        project.register_buffer_with_language_servers(&buffer, cx)
 1924                    });
 1925                    this.registered_buffers
 1926                        .insert(buffer.read(cx).remote_id(), handle);
 1927                }
 1928            }
 1929        }
 1930
 1931        this.report_editor_event("Editor Opened", None, cx);
 1932        this
 1933    }
 1934
 1935    pub fn deploy_mouse_context_menu(
 1936        &mut self,
 1937        position: gpui::Point<Pixels>,
 1938        context_menu: Entity<ContextMenu>,
 1939        window: &mut Window,
 1940        cx: &mut Context<Self>,
 1941    ) {
 1942        self.mouse_context_menu = Some(MouseContextMenu::new(
 1943            self,
 1944            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1945            context_menu,
 1946            window,
 1947            cx,
 1948        ));
 1949    }
 1950
 1951    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1952        self.mouse_context_menu
 1953            .as_ref()
 1954            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1955    }
 1956
 1957    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1958        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1959    }
 1960
 1961    fn key_context_internal(
 1962        &self,
 1963        has_active_edit_prediction: bool,
 1964        window: &Window,
 1965        cx: &App,
 1966    ) -> KeyContext {
 1967        let mut key_context = KeyContext::new_with_defaults();
 1968        key_context.add("Editor");
 1969        let mode = match self.mode {
 1970            EditorMode::SingleLine { .. } => "single_line",
 1971            EditorMode::AutoHeight { .. } => "auto_height",
 1972            EditorMode::Full { .. } => "full",
 1973        };
 1974
 1975        if EditorSettings::jupyter_enabled(cx) {
 1976            key_context.add("jupyter");
 1977        }
 1978
 1979        key_context.set("mode", mode);
 1980        if self.pending_rename.is_some() {
 1981            key_context.add("renaming");
 1982        }
 1983
 1984        match self.context_menu.borrow().as_ref() {
 1985            Some(CodeContextMenu::Completions(_)) => {
 1986                key_context.add("menu");
 1987                key_context.add("showing_completions");
 1988            }
 1989            Some(CodeContextMenu::CodeActions(_)) => {
 1990                key_context.add("menu");
 1991                key_context.add("showing_code_actions")
 1992            }
 1993            None => {}
 1994        }
 1995
 1996        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1997        if !self.focus_handle(cx).contains_focused(window, cx)
 1998            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1999        {
 2000            for addon in self.addons.values() {
 2001                addon.extend_key_context(&mut key_context, cx)
 2002            }
 2003        }
 2004
 2005        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 2006            if let Some(extension) = singleton_buffer
 2007                .read(cx)
 2008                .file()
 2009                .and_then(|file| file.path().extension()?.to_str())
 2010            {
 2011                key_context.set("extension", extension.to_string());
 2012            }
 2013        } else {
 2014            key_context.add("multibuffer");
 2015        }
 2016
 2017        if has_active_edit_prediction {
 2018            if self.edit_prediction_in_conflict() {
 2019                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2020            } else {
 2021                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2022                key_context.add("copilot_suggestion");
 2023            }
 2024        }
 2025
 2026        if self.selection_mark_mode {
 2027            key_context.add("selection_mode");
 2028        }
 2029
 2030        key_context
 2031    }
 2032
 2033    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2034        self.mouse_cursor_hidden = match origin {
 2035            HideMouseCursorOrigin::TypingAction => {
 2036                matches!(
 2037                    self.hide_mouse_mode,
 2038                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2039                )
 2040            }
 2041            HideMouseCursorOrigin::MovementAction => {
 2042                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2043            }
 2044        };
 2045    }
 2046
 2047    pub fn edit_prediction_in_conflict(&self) -> bool {
 2048        if !self.show_edit_predictions_in_menu() {
 2049            return false;
 2050        }
 2051
 2052        let showing_completions = self
 2053            .context_menu
 2054            .borrow()
 2055            .as_ref()
 2056            .map_or(false, |context| {
 2057                matches!(context, CodeContextMenu::Completions(_))
 2058            });
 2059
 2060        showing_completions
 2061            || self.edit_prediction_requires_modifier()
 2062            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2063            // bindings to insert tab characters.
 2064            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2065    }
 2066
 2067    pub fn accept_edit_prediction_keybind(
 2068        &self,
 2069        window: &Window,
 2070        cx: &App,
 2071    ) -> AcceptEditPredictionBinding {
 2072        let key_context = self.key_context_internal(true, window, cx);
 2073        let in_conflict = self.edit_prediction_in_conflict();
 2074
 2075        AcceptEditPredictionBinding(
 2076            window
 2077                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2078                .into_iter()
 2079                .filter(|binding| {
 2080                    !in_conflict
 2081                        || binding
 2082                            .keystrokes()
 2083                            .first()
 2084                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2085                })
 2086                .rev()
 2087                .min_by_key(|binding| {
 2088                    binding
 2089                        .keystrokes()
 2090                        .first()
 2091                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2092                }),
 2093        )
 2094    }
 2095
 2096    pub fn new_file(
 2097        workspace: &mut Workspace,
 2098        _: &workspace::NewFile,
 2099        window: &mut Window,
 2100        cx: &mut Context<Workspace>,
 2101    ) {
 2102        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2103            "Failed to create buffer",
 2104            window,
 2105            cx,
 2106            |e, _, _| match e.error_code() {
 2107                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2108                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2109                e.error_tag("required").unwrap_or("the latest version")
 2110            )),
 2111                _ => None,
 2112            },
 2113        );
 2114    }
 2115
 2116    pub fn new_in_workspace(
 2117        workspace: &mut Workspace,
 2118        window: &mut Window,
 2119        cx: &mut Context<Workspace>,
 2120    ) -> Task<Result<Entity<Editor>>> {
 2121        let project = workspace.project().clone();
 2122        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2123
 2124        cx.spawn_in(window, async move |workspace, cx| {
 2125            let buffer = create.await?;
 2126            workspace.update_in(cx, |workspace, window, cx| {
 2127                let editor =
 2128                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2129                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2130                editor
 2131            })
 2132        })
 2133    }
 2134
 2135    fn new_file_vertical(
 2136        workspace: &mut Workspace,
 2137        _: &workspace::NewFileSplitVertical,
 2138        window: &mut Window,
 2139        cx: &mut Context<Workspace>,
 2140    ) {
 2141        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2142    }
 2143
 2144    fn new_file_horizontal(
 2145        workspace: &mut Workspace,
 2146        _: &workspace::NewFileSplitHorizontal,
 2147        window: &mut Window,
 2148        cx: &mut Context<Workspace>,
 2149    ) {
 2150        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2151    }
 2152
 2153    fn new_file_in_direction(
 2154        workspace: &mut Workspace,
 2155        direction: SplitDirection,
 2156        window: &mut Window,
 2157        cx: &mut Context<Workspace>,
 2158    ) {
 2159        let project = workspace.project().clone();
 2160        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2161
 2162        cx.spawn_in(window, async move |workspace, cx| {
 2163            let buffer = create.await?;
 2164            workspace.update_in(cx, move |workspace, window, cx| {
 2165                workspace.split_item(
 2166                    direction,
 2167                    Box::new(
 2168                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2169                    ),
 2170                    window,
 2171                    cx,
 2172                )
 2173            })?;
 2174            anyhow::Ok(())
 2175        })
 2176        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2177            match e.error_code() {
 2178                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2179                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2180                e.error_tag("required").unwrap_or("the latest version")
 2181            )),
 2182                _ => None,
 2183            }
 2184        });
 2185    }
 2186
 2187    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2188        self.leader_id
 2189    }
 2190
 2191    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2192        &self.buffer
 2193    }
 2194
 2195    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2196        self.workspace.as_ref()?.0.upgrade()
 2197    }
 2198
 2199    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2200        self.buffer().read(cx).title(cx)
 2201    }
 2202
 2203    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2204        let git_blame_gutter_max_author_length = self
 2205            .render_git_blame_gutter(cx)
 2206            .then(|| {
 2207                if let Some(blame) = self.blame.as_ref() {
 2208                    let max_author_length =
 2209                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2210                    Some(max_author_length)
 2211                } else {
 2212                    None
 2213                }
 2214            })
 2215            .flatten();
 2216
 2217        EditorSnapshot {
 2218            mode: self.mode,
 2219            show_gutter: self.show_gutter,
 2220            show_line_numbers: self.show_line_numbers,
 2221            show_git_diff_gutter: self.show_git_diff_gutter,
 2222            show_runnables: self.show_runnables,
 2223            show_breakpoints: self.show_breakpoints,
 2224            git_blame_gutter_max_author_length,
 2225            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2226            scroll_anchor: self.scroll_manager.anchor(),
 2227            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2228            placeholder_text: self.placeholder_text.clone(),
 2229            is_focused: self.focus_handle.is_focused(window),
 2230            current_line_highlight: self
 2231                .current_line_highlight
 2232                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2233            gutter_hovered: self.gutter_hovered,
 2234        }
 2235    }
 2236
 2237    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2238        self.buffer.read(cx).language_at(point, cx)
 2239    }
 2240
 2241    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2242        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2243    }
 2244
 2245    pub fn active_excerpt(
 2246        &self,
 2247        cx: &App,
 2248    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2249        self.buffer
 2250            .read(cx)
 2251            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2252    }
 2253
 2254    pub fn mode(&self) -> EditorMode {
 2255        self.mode
 2256    }
 2257
 2258    pub fn set_mode(&mut self, mode: EditorMode) {
 2259        self.mode = mode;
 2260    }
 2261
 2262    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2263        self.collaboration_hub.as_deref()
 2264    }
 2265
 2266    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2267        self.collaboration_hub = Some(hub);
 2268    }
 2269
 2270    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2271        self.in_project_search = in_project_search;
 2272    }
 2273
 2274    pub fn set_custom_context_menu(
 2275        &mut self,
 2276        f: impl 'static
 2277        + Fn(
 2278            &mut Self,
 2279            DisplayPoint,
 2280            &mut Window,
 2281            &mut Context<Self>,
 2282        ) -> Option<Entity<ui::ContextMenu>>,
 2283    ) {
 2284        self.custom_context_menu = Some(Box::new(f))
 2285    }
 2286
 2287    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2288        self.completion_provider = provider;
 2289    }
 2290
 2291    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2292        self.semantics_provider.clone()
 2293    }
 2294
 2295    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2296        self.semantics_provider = provider;
 2297    }
 2298
 2299    pub fn set_edit_prediction_provider<T>(
 2300        &mut self,
 2301        provider: Option<Entity<T>>,
 2302        window: &mut Window,
 2303        cx: &mut Context<Self>,
 2304    ) where
 2305        T: EditPredictionProvider,
 2306    {
 2307        self.edit_prediction_provider =
 2308            provider.map(|provider| RegisteredInlineCompletionProvider {
 2309                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2310                    if this.focus_handle.is_focused(window) {
 2311                        this.update_visible_inline_completion(window, cx);
 2312                    }
 2313                }),
 2314                provider: Arc::new(provider),
 2315            });
 2316        self.update_edit_prediction_settings(cx);
 2317        self.refresh_inline_completion(false, false, window, cx);
 2318    }
 2319
 2320    pub fn placeholder_text(&self) -> Option<&str> {
 2321        self.placeholder_text.as_deref()
 2322    }
 2323
 2324    pub fn set_placeholder_text(
 2325        &mut self,
 2326        placeholder_text: impl Into<Arc<str>>,
 2327        cx: &mut Context<Self>,
 2328    ) {
 2329        let placeholder_text = Some(placeholder_text.into());
 2330        if self.placeholder_text != placeholder_text {
 2331            self.placeholder_text = placeholder_text;
 2332            cx.notify();
 2333        }
 2334    }
 2335
 2336    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2337        self.cursor_shape = cursor_shape;
 2338
 2339        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2340        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2341
 2342        cx.notify();
 2343    }
 2344
 2345    pub fn set_current_line_highlight(
 2346        &mut self,
 2347        current_line_highlight: Option<CurrentLineHighlight>,
 2348    ) {
 2349        self.current_line_highlight = current_line_highlight;
 2350    }
 2351
 2352    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2353        self.collapse_matches = collapse_matches;
 2354    }
 2355
 2356    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2357        let buffers = self.buffer.read(cx).all_buffers();
 2358        let Some(project) = self.project.as_ref() else {
 2359            return;
 2360        };
 2361        project.update(cx, |project, cx| {
 2362            for buffer in buffers {
 2363                self.registered_buffers
 2364                    .entry(buffer.read(cx).remote_id())
 2365                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2366            }
 2367        })
 2368    }
 2369
 2370    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2371        if self.collapse_matches {
 2372            return range.start..range.start;
 2373        }
 2374        range.clone()
 2375    }
 2376
 2377    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2378        if self.display_map.read(cx).clip_at_line_ends != clip {
 2379            self.display_map
 2380                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2381        }
 2382    }
 2383
 2384    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2385        self.input_enabled = input_enabled;
 2386    }
 2387
 2388    pub fn set_inline_completions_hidden_for_vim_mode(
 2389        &mut self,
 2390        hidden: bool,
 2391        window: &mut Window,
 2392        cx: &mut Context<Self>,
 2393    ) {
 2394        if hidden != self.inline_completions_hidden_for_vim_mode {
 2395            self.inline_completions_hidden_for_vim_mode = hidden;
 2396            if hidden {
 2397                self.update_visible_inline_completion(window, cx);
 2398            } else {
 2399                self.refresh_inline_completion(true, false, window, cx);
 2400            }
 2401        }
 2402    }
 2403
 2404    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2405        self.menu_inline_completions_policy = value;
 2406    }
 2407
 2408    pub fn set_autoindent(&mut self, autoindent: bool) {
 2409        if autoindent {
 2410            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2411        } else {
 2412            self.autoindent_mode = None;
 2413        }
 2414    }
 2415
 2416    pub fn read_only(&self, cx: &App) -> bool {
 2417        self.read_only || self.buffer.read(cx).read_only()
 2418    }
 2419
 2420    pub fn set_read_only(&mut self, read_only: bool) {
 2421        self.read_only = read_only;
 2422    }
 2423
 2424    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2425        self.use_autoclose = autoclose;
 2426    }
 2427
 2428    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2429        self.use_auto_surround = auto_surround;
 2430    }
 2431
 2432    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2433        self.auto_replace_emoji_shortcode = auto_replace;
 2434    }
 2435
 2436    pub fn toggle_edit_predictions(
 2437        &mut self,
 2438        _: &ToggleEditPrediction,
 2439        window: &mut Window,
 2440        cx: &mut Context<Self>,
 2441    ) {
 2442        if self.show_inline_completions_override.is_some() {
 2443            self.set_show_edit_predictions(None, window, cx);
 2444        } else {
 2445            let show_edit_predictions = !self.edit_predictions_enabled();
 2446            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2447        }
 2448    }
 2449
 2450    pub fn set_show_edit_predictions(
 2451        &mut self,
 2452        show_edit_predictions: Option<bool>,
 2453        window: &mut Window,
 2454        cx: &mut Context<Self>,
 2455    ) {
 2456        self.show_inline_completions_override = show_edit_predictions;
 2457        self.update_edit_prediction_settings(cx);
 2458
 2459        if let Some(false) = show_edit_predictions {
 2460            self.discard_inline_completion(false, cx);
 2461        } else {
 2462            self.refresh_inline_completion(false, true, window, cx);
 2463        }
 2464    }
 2465
 2466    fn inline_completions_disabled_in_scope(
 2467        &self,
 2468        buffer: &Entity<Buffer>,
 2469        buffer_position: language::Anchor,
 2470        cx: &App,
 2471    ) -> bool {
 2472        let snapshot = buffer.read(cx).snapshot();
 2473        let settings = snapshot.settings_at(buffer_position, cx);
 2474
 2475        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2476            return false;
 2477        };
 2478
 2479        scope.override_name().map_or(false, |scope_name| {
 2480            settings
 2481                .edit_predictions_disabled_in
 2482                .iter()
 2483                .any(|s| s == scope_name)
 2484        })
 2485    }
 2486
 2487    pub fn set_use_modal_editing(&mut self, to: bool) {
 2488        self.use_modal_editing = to;
 2489    }
 2490
 2491    pub fn use_modal_editing(&self) -> bool {
 2492        self.use_modal_editing
 2493    }
 2494
 2495    fn selections_did_change(
 2496        &mut self,
 2497        local: bool,
 2498        old_cursor_position: &Anchor,
 2499        show_completions: bool,
 2500        window: &mut Window,
 2501        cx: &mut Context<Self>,
 2502    ) {
 2503        window.invalidate_character_coordinates();
 2504
 2505        // Copy selections to primary selection buffer
 2506        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2507        if local {
 2508            let selections = self.selections.all::<usize>(cx);
 2509            let buffer_handle = self.buffer.read(cx).read(cx);
 2510
 2511            let mut text = String::new();
 2512            for (index, selection) in selections.iter().enumerate() {
 2513                let text_for_selection = buffer_handle
 2514                    .text_for_range(selection.start..selection.end)
 2515                    .collect::<String>();
 2516
 2517                text.push_str(&text_for_selection);
 2518                if index != selections.len() - 1 {
 2519                    text.push('\n');
 2520                }
 2521            }
 2522
 2523            if !text.is_empty() {
 2524                cx.write_to_primary(ClipboardItem::new_string(text));
 2525            }
 2526        }
 2527
 2528        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2529            self.buffer.update(cx, |buffer, cx| {
 2530                buffer.set_active_selections(
 2531                    &self.selections.disjoint_anchors(),
 2532                    self.selections.line_mode,
 2533                    self.cursor_shape,
 2534                    cx,
 2535                )
 2536            });
 2537        }
 2538        let display_map = self
 2539            .display_map
 2540            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2541        let buffer = &display_map.buffer_snapshot;
 2542        self.add_selections_state = None;
 2543        self.select_next_state = None;
 2544        self.select_prev_state = None;
 2545        self.select_syntax_node_history.try_clear();
 2546        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2547        self.snippet_stack
 2548            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2549        self.take_rename(false, window, cx);
 2550
 2551        let new_cursor_position = self.selections.newest_anchor().head();
 2552
 2553        self.push_to_nav_history(
 2554            *old_cursor_position,
 2555            Some(new_cursor_position.to_point(buffer)),
 2556            false,
 2557            cx,
 2558        );
 2559
 2560        if local {
 2561            let new_cursor_position = self.selections.newest_anchor().head();
 2562            let mut context_menu = self.context_menu.borrow_mut();
 2563            let completion_menu = match context_menu.as_ref() {
 2564                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2565                _ => {
 2566                    *context_menu = None;
 2567                    None
 2568                }
 2569            };
 2570            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2571                if !self.registered_buffers.contains_key(&buffer_id) {
 2572                    if let Some(project) = self.project.as_ref() {
 2573                        project.update(cx, |project, cx| {
 2574                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2575                                return;
 2576                            };
 2577                            self.registered_buffers.insert(
 2578                                buffer_id,
 2579                                project.register_buffer_with_language_servers(&buffer, cx),
 2580                            );
 2581                        })
 2582                    }
 2583                }
 2584            }
 2585
 2586            if let Some(completion_menu) = completion_menu {
 2587                let cursor_position = new_cursor_position.to_offset(buffer);
 2588                let (word_range, kind) =
 2589                    buffer.surrounding_word(completion_menu.initial_position, true);
 2590                if kind == Some(CharKind::Word)
 2591                    && word_range.to_inclusive().contains(&cursor_position)
 2592                {
 2593                    let mut completion_menu = completion_menu.clone();
 2594                    drop(context_menu);
 2595
 2596                    let query = Self::completion_query(buffer, cursor_position);
 2597                    cx.spawn(async move |this, cx| {
 2598                        completion_menu
 2599                            .filter(query.as_deref(), cx.background_executor().clone())
 2600                            .await;
 2601
 2602                        this.update(cx, |this, cx| {
 2603                            let mut context_menu = this.context_menu.borrow_mut();
 2604                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2605                            else {
 2606                                return;
 2607                            };
 2608
 2609                            if menu.id > completion_menu.id {
 2610                                return;
 2611                            }
 2612
 2613                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2614                            drop(context_menu);
 2615                            cx.notify();
 2616                        })
 2617                    })
 2618                    .detach();
 2619
 2620                    if show_completions {
 2621                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2622                    }
 2623                } else {
 2624                    drop(context_menu);
 2625                    self.hide_context_menu(window, cx);
 2626                }
 2627            } else {
 2628                drop(context_menu);
 2629            }
 2630
 2631            hide_hover(self, cx);
 2632
 2633            if old_cursor_position.to_display_point(&display_map).row()
 2634                != new_cursor_position.to_display_point(&display_map).row()
 2635            {
 2636                self.available_code_actions.take();
 2637            }
 2638            self.refresh_code_actions(window, cx);
 2639            self.refresh_document_highlights(cx);
 2640            self.refresh_selected_text_highlights(false, window, cx);
 2641            refresh_matching_bracket_highlights(self, window, cx);
 2642            self.update_visible_inline_completion(window, cx);
 2643            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2644            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2645            self.inline_blame_popover.take();
 2646            if self.git_blame_inline_enabled {
 2647                self.start_inline_blame_timer(window, cx);
 2648            }
 2649        }
 2650
 2651        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2652        cx.emit(EditorEvent::SelectionsChanged { local });
 2653
 2654        let selections = &self.selections.disjoint;
 2655        if selections.len() == 1 {
 2656            cx.emit(SearchEvent::ActiveMatchChanged)
 2657        }
 2658        if local {
 2659            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2660                let inmemory_selections = selections
 2661                    .iter()
 2662                    .map(|s| {
 2663                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2664                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2665                    })
 2666                    .collect();
 2667                self.update_restoration_data(cx, |data| {
 2668                    data.selections = inmemory_selections;
 2669                });
 2670
 2671                if WorkspaceSettings::get(None, cx).restore_on_startup
 2672                    != RestoreOnStartupBehavior::None
 2673                {
 2674                    if let Some(workspace_id) =
 2675                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2676                    {
 2677                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2678                        let selections = selections.clone();
 2679                        let background_executor = cx.background_executor().clone();
 2680                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2681                        self.serialize_selections = cx.background_spawn(async move {
 2682                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2683                    let db_selections = selections
 2684                        .iter()
 2685                        .map(|selection| {
 2686                            (
 2687                                selection.start.to_offset(&snapshot),
 2688                                selection.end.to_offset(&snapshot),
 2689                            )
 2690                        })
 2691                        .collect();
 2692
 2693                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2694                        .await
 2695                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2696                        .log_err();
 2697                });
 2698                    }
 2699                }
 2700            }
 2701        }
 2702
 2703        cx.notify();
 2704    }
 2705
 2706    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2707        use text::ToOffset as _;
 2708        use text::ToPoint as _;
 2709
 2710        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2711            return;
 2712        }
 2713
 2714        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2715            return;
 2716        };
 2717
 2718        let snapshot = singleton.read(cx).snapshot();
 2719        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2720            let display_snapshot = display_map.snapshot(cx);
 2721
 2722            display_snapshot
 2723                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2724                .map(|fold| {
 2725                    fold.range.start.text_anchor.to_point(&snapshot)
 2726                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2727                })
 2728                .collect()
 2729        });
 2730        self.update_restoration_data(cx, |data| {
 2731            data.folds = inmemory_folds;
 2732        });
 2733
 2734        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2735            return;
 2736        };
 2737        let background_executor = cx.background_executor().clone();
 2738        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2739        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2740            display_map
 2741                .snapshot(cx)
 2742                .folds_in_range(0..snapshot.len())
 2743                .map(|fold| {
 2744                    (
 2745                        fold.range.start.text_anchor.to_offset(&snapshot),
 2746                        fold.range.end.text_anchor.to_offset(&snapshot),
 2747                    )
 2748                })
 2749                .collect()
 2750        });
 2751        self.serialize_folds = cx.background_spawn(async move {
 2752            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2753            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2754                .await
 2755                .with_context(|| {
 2756                    format!(
 2757                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2758                    )
 2759                })
 2760                .log_err();
 2761        });
 2762    }
 2763
 2764    pub fn sync_selections(
 2765        &mut self,
 2766        other: Entity<Editor>,
 2767        cx: &mut Context<Self>,
 2768    ) -> gpui::Subscription {
 2769        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2770        self.selections.change_with(cx, |selections| {
 2771            selections.select_anchors(other_selections);
 2772        });
 2773
 2774        let other_subscription =
 2775            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2776                EditorEvent::SelectionsChanged { local: true } => {
 2777                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2778                    if other_selections.is_empty() {
 2779                        return;
 2780                    }
 2781                    this.selections.change_with(cx, |selections| {
 2782                        selections.select_anchors(other_selections);
 2783                    });
 2784                }
 2785                _ => {}
 2786            });
 2787
 2788        let this_subscription =
 2789            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2790                EditorEvent::SelectionsChanged { local: true } => {
 2791                    let these_selections = this.selections.disjoint.to_vec();
 2792                    if these_selections.is_empty() {
 2793                        return;
 2794                    }
 2795                    other.update(cx, |other_editor, cx| {
 2796                        other_editor.selections.change_with(cx, |selections| {
 2797                            selections.select_anchors(these_selections);
 2798                        })
 2799                    });
 2800                }
 2801                _ => {}
 2802            });
 2803
 2804        Subscription::join(other_subscription, this_subscription)
 2805    }
 2806
 2807    pub fn change_selections<R>(
 2808        &mut self,
 2809        autoscroll: Option<Autoscroll>,
 2810        window: &mut Window,
 2811        cx: &mut Context<Self>,
 2812        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2813    ) -> R {
 2814        self.change_selections_inner(autoscroll, true, window, cx, change)
 2815    }
 2816
 2817    fn change_selections_inner<R>(
 2818        &mut self,
 2819        autoscroll: Option<Autoscroll>,
 2820        request_completions: bool,
 2821        window: &mut Window,
 2822        cx: &mut Context<Self>,
 2823        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2824    ) -> R {
 2825        let old_cursor_position = self.selections.newest_anchor().head();
 2826        self.push_to_selection_history();
 2827
 2828        let (changed, result) = self.selections.change_with(cx, change);
 2829
 2830        if changed {
 2831            if let Some(autoscroll) = autoscroll {
 2832                self.request_autoscroll(autoscroll, cx);
 2833            }
 2834            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2835
 2836            if self.should_open_signature_help_automatically(
 2837                &old_cursor_position,
 2838                self.signature_help_state.backspace_pressed(),
 2839                cx,
 2840            ) {
 2841                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2842            }
 2843            self.signature_help_state.set_backspace_pressed(false);
 2844        }
 2845
 2846        result
 2847    }
 2848
 2849    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2850    where
 2851        I: IntoIterator<Item = (Range<S>, T)>,
 2852        S: ToOffset,
 2853        T: Into<Arc<str>>,
 2854    {
 2855        if self.read_only(cx) {
 2856            return;
 2857        }
 2858
 2859        self.buffer
 2860            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2861    }
 2862
 2863    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2864    where
 2865        I: IntoIterator<Item = (Range<S>, T)>,
 2866        S: ToOffset,
 2867        T: Into<Arc<str>>,
 2868    {
 2869        if self.read_only(cx) {
 2870            return;
 2871        }
 2872
 2873        self.buffer.update(cx, |buffer, cx| {
 2874            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2875        });
 2876    }
 2877
 2878    pub fn edit_with_block_indent<I, S, T>(
 2879        &mut self,
 2880        edits: I,
 2881        original_indent_columns: Vec<Option<u32>>,
 2882        cx: &mut Context<Self>,
 2883    ) where
 2884        I: IntoIterator<Item = (Range<S>, T)>,
 2885        S: ToOffset,
 2886        T: Into<Arc<str>>,
 2887    {
 2888        if self.read_only(cx) {
 2889            return;
 2890        }
 2891
 2892        self.buffer.update(cx, |buffer, cx| {
 2893            buffer.edit(
 2894                edits,
 2895                Some(AutoindentMode::Block {
 2896                    original_indent_columns,
 2897                }),
 2898                cx,
 2899            )
 2900        });
 2901    }
 2902
 2903    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2904        self.hide_context_menu(window, cx);
 2905
 2906        match phase {
 2907            SelectPhase::Begin {
 2908                position,
 2909                add,
 2910                click_count,
 2911            } => self.begin_selection(position, add, click_count, window, cx),
 2912            SelectPhase::BeginColumnar {
 2913                position,
 2914                goal_column,
 2915                reset,
 2916            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2917            SelectPhase::Extend {
 2918                position,
 2919                click_count,
 2920            } => self.extend_selection(position, click_count, window, cx),
 2921            SelectPhase::Update {
 2922                position,
 2923                goal_column,
 2924                scroll_delta,
 2925            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2926            SelectPhase::End => self.end_selection(window, cx),
 2927        }
 2928    }
 2929
 2930    fn extend_selection(
 2931        &mut self,
 2932        position: DisplayPoint,
 2933        click_count: usize,
 2934        window: &mut Window,
 2935        cx: &mut Context<Self>,
 2936    ) {
 2937        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2938        let tail = self.selections.newest::<usize>(cx).tail();
 2939        self.begin_selection(position, false, click_count, window, cx);
 2940
 2941        let position = position.to_offset(&display_map, Bias::Left);
 2942        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2943
 2944        let mut pending_selection = self
 2945            .selections
 2946            .pending_anchor()
 2947            .expect("extend_selection not called with pending selection");
 2948        if position >= tail {
 2949            pending_selection.start = tail_anchor;
 2950        } else {
 2951            pending_selection.end = tail_anchor;
 2952            pending_selection.reversed = true;
 2953        }
 2954
 2955        let mut pending_mode = self.selections.pending_mode().unwrap();
 2956        match &mut pending_mode {
 2957            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2958            _ => {}
 2959        }
 2960
 2961        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 2962
 2963        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 2964            s.set_pending(pending_selection, pending_mode)
 2965        });
 2966    }
 2967
 2968    fn begin_selection(
 2969        &mut self,
 2970        position: DisplayPoint,
 2971        add: bool,
 2972        click_count: usize,
 2973        window: &mut Window,
 2974        cx: &mut Context<Self>,
 2975    ) {
 2976        if !self.focus_handle.is_focused(window) {
 2977            self.last_focused_descendant = None;
 2978            window.focus(&self.focus_handle);
 2979        }
 2980
 2981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2982        let buffer = &display_map.buffer_snapshot;
 2983        let position = display_map.clip_point(position, Bias::Left);
 2984
 2985        let start;
 2986        let end;
 2987        let mode;
 2988        let mut auto_scroll;
 2989        match click_count {
 2990            1 => {
 2991                start = buffer.anchor_before(position.to_point(&display_map));
 2992                end = start;
 2993                mode = SelectMode::Character;
 2994                auto_scroll = true;
 2995            }
 2996            2 => {
 2997                let range = movement::surrounding_word(&display_map, position);
 2998                start = buffer.anchor_before(range.start.to_point(&display_map));
 2999                end = buffer.anchor_before(range.end.to_point(&display_map));
 3000                mode = SelectMode::Word(start..end);
 3001                auto_scroll = true;
 3002            }
 3003            3 => {
 3004                let position = display_map
 3005                    .clip_point(position, Bias::Left)
 3006                    .to_point(&display_map);
 3007                let line_start = display_map.prev_line_boundary(position).0;
 3008                let next_line_start = buffer.clip_point(
 3009                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3010                    Bias::Left,
 3011                );
 3012                start = buffer.anchor_before(line_start);
 3013                end = buffer.anchor_before(next_line_start);
 3014                mode = SelectMode::Line(start..end);
 3015                auto_scroll = true;
 3016            }
 3017            _ => {
 3018                start = buffer.anchor_before(0);
 3019                end = buffer.anchor_before(buffer.len());
 3020                mode = SelectMode::All;
 3021                auto_scroll = false;
 3022            }
 3023        }
 3024        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3025
 3026        let point_to_delete: Option<usize> = {
 3027            let selected_points: Vec<Selection<Point>> =
 3028                self.selections.disjoint_in_range(start..end, cx);
 3029
 3030            if !add || click_count > 1 {
 3031                None
 3032            } else if !selected_points.is_empty() {
 3033                Some(selected_points[0].id)
 3034            } else {
 3035                let clicked_point_already_selected =
 3036                    self.selections.disjoint.iter().find(|selection| {
 3037                        selection.start.to_point(buffer) == start.to_point(buffer)
 3038                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3039                    });
 3040
 3041                clicked_point_already_selected.map(|selection| selection.id)
 3042            }
 3043        };
 3044
 3045        let selections_count = self.selections.count();
 3046
 3047        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3048            if let Some(point_to_delete) = point_to_delete {
 3049                s.delete(point_to_delete);
 3050
 3051                if selections_count == 1 {
 3052                    s.set_pending_anchor_range(start..end, mode);
 3053                }
 3054            } else {
 3055                if !add {
 3056                    s.clear_disjoint();
 3057                }
 3058
 3059                s.set_pending_anchor_range(start..end, mode);
 3060            }
 3061        });
 3062    }
 3063
 3064    fn begin_columnar_selection(
 3065        &mut self,
 3066        position: DisplayPoint,
 3067        goal_column: u32,
 3068        reset: bool,
 3069        window: &mut Window,
 3070        cx: &mut Context<Self>,
 3071    ) {
 3072        if !self.focus_handle.is_focused(window) {
 3073            self.last_focused_descendant = None;
 3074            window.focus(&self.focus_handle);
 3075        }
 3076
 3077        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3078
 3079        if reset {
 3080            let pointer_position = display_map
 3081                .buffer_snapshot
 3082                .anchor_before(position.to_point(&display_map));
 3083
 3084            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3085                s.clear_disjoint();
 3086                s.set_pending_anchor_range(
 3087                    pointer_position..pointer_position,
 3088                    SelectMode::Character,
 3089                );
 3090            });
 3091        }
 3092
 3093        let tail = self.selections.newest::<Point>(cx).tail();
 3094        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3095
 3096        if !reset {
 3097            self.select_columns(
 3098                tail.to_display_point(&display_map),
 3099                position,
 3100                goal_column,
 3101                &display_map,
 3102                window,
 3103                cx,
 3104            );
 3105        }
 3106    }
 3107
 3108    fn update_selection(
 3109        &mut self,
 3110        position: DisplayPoint,
 3111        goal_column: u32,
 3112        scroll_delta: gpui::Point<f32>,
 3113        window: &mut Window,
 3114        cx: &mut Context<Self>,
 3115    ) {
 3116        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3117
 3118        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3119            let tail = tail.to_display_point(&display_map);
 3120            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3121        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3122            let buffer = self.buffer.read(cx).snapshot(cx);
 3123            let head;
 3124            let tail;
 3125            let mode = self.selections.pending_mode().unwrap();
 3126            match &mode {
 3127                SelectMode::Character => {
 3128                    head = position.to_point(&display_map);
 3129                    tail = pending.tail().to_point(&buffer);
 3130                }
 3131                SelectMode::Word(original_range) => {
 3132                    let original_display_range = original_range.start.to_display_point(&display_map)
 3133                        ..original_range.end.to_display_point(&display_map);
 3134                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3135                        ..original_display_range.end.to_point(&display_map);
 3136                    if movement::is_inside_word(&display_map, position)
 3137                        || original_display_range.contains(&position)
 3138                    {
 3139                        let word_range = movement::surrounding_word(&display_map, position);
 3140                        if word_range.start < original_display_range.start {
 3141                            head = word_range.start.to_point(&display_map);
 3142                        } else {
 3143                            head = word_range.end.to_point(&display_map);
 3144                        }
 3145                    } else {
 3146                        head = position.to_point(&display_map);
 3147                    }
 3148
 3149                    if head <= original_buffer_range.start {
 3150                        tail = original_buffer_range.end;
 3151                    } else {
 3152                        tail = original_buffer_range.start;
 3153                    }
 3154                }
 3155                SelectMode::Line(original_range) => {
 3156                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3157
 3158                    let position = display_map
 3159                        .clip_point(position, Bias::Left)
 3160                        .to_point(&display_map);
 3161                    let line_start = display_map.prev_line_boundary(position).0;
 3162                    let next_line_start = buffer.clip_point(
 3163                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3164                        Bias::Left,
 3165                    );
 3166
 3167                    if line_start < original_range.start {
 3168                        head = line_start
 3169                    } else {
 3170                        head = next_line_start
 3171                    }
 3172
 3173                    if head <= original_range.start {
 3174                        tail = original_range.end;
 3175                    } else {
 3176                        tail = original_range.start;
 3177                    }
 3178                }
 3179                SelectMode::All => {
 3180                    return;
 3181                }
 3182            };
 3183
 3184            if head < tail {
 3185                pending.start = buffer.anchor_before(head);
 3186                pending.end = buffer.anchor_before(tail);
 3187                pending.reversed = true;
 3188            } else {
 3189                pending.start = buffer.anchor_before(tail);
 3190                pending.end = buffer.anchor_before(head);
 3191                pending.reversed = false;
 3192            }
 3193
 3194            self.change_selections(None, window, cx, |s| {
 3195                s.set_pending(pending, mode);
 3196            });
 3197        } else {
 3198            log::error!("update_selection dispatched with no pending selection");
 3199            return;
 3200        }
 3201
 3202        self.apply_scroll_delta(scroll_delta, window, cx);
 3203        cx.notify();
 3204    }
 3205
 3206    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3207        self.columnar_selection_tail.take();
 3208        if self.selections.pending_anchor().is_some() {
 3209            let selections = self.selections.all::<usize>(cx);
 3210            self.change_selections(None, window, cx, |s| {
 3211                s.select(selections);
 3212                s.clear_pending();
 3213            });
 3214        }
 3215    }
 3216
 3217    fn select_columns(
 3218        &mut self,
 3219        tail: DisplayPoint,
 3220        head: DisplayPoint,
 3221        goal_column: u32,
 3222        display_map: &DisplaySnapshot,
 3223        window: &mut Window,
 3224        cx: &mut Context<Self>,
 3225    ) {
 3226        let start_row = cmp::min(tail.row(), head.row());
 3227        let end_row = cmp::max(tail.row(), head.row());
 3228        let start_column = cmp::min(tail.column(), goal_column);
 3229        let end_column = cmp::max(tail.column(), goal_column);
 3230        let reversed = start_column < tail.column();
 3231
 3232        let selection_ranges = (start_row.0..=end_row.0)
 3233            .map(DisplayRow)
 3234            .filter_map(|row| {
 3235                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3236                    let start = display_map
 3237                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3238                        .to_point(display_map);
 3239                    let end = display_map
 3240                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3241                        .to_point(display_map);
 3242                    if reversed {
 3243                        Some(end..start)
 3244                    } else {
 3245                        Some(start..end)
 3246                    }
 3247                } else {
 3248                    None
 3249                }
 3250            })
 3251            .collect::<Vec<_>>();
 3252
 3253        self.change_selections(None, window, cx, |s| {
 3254            s.select_ranges(selection_ranges);
 3255        });
 3256        cx.notify();
 3257    }
 3258
 3259    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3260        self.selections
 3261            .all_adjusted(cx)
 3262            .iter()
 3263            .any(|selection| !selection.is_empty())
 3264    }
 3265
 3266    pub fn has_pending_nonempty_selection(&self) -> bool {
 3267        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3268            Some(Selection { start, end, .. }) => start != end,
 3269            None => false,
 3270        };
 3271
 3272        pending_nonempty_selection
 3273            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3274    }
 3275
 3276    pub fn has_pending_selection(&self) -> bool {
 3277        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3278    }
 3279
 3280    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3281        self.selection_mark_mode = false;
 3282
 3283        if self.clear_expanded_diff_hunks(cx) {
 3284            cx.notify();
 3285            return;
 3286        }
 3287        if self.dismiss_menus_and_popups(true, window, cx) {
 3288            return;
 3289        }
 3290
 3291        if self.mode.is_full()
 3292            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3293        {
 3294            return;
 3295        }
 3296
 3297        cx.propagate();
 3298    }
 3299
 3300    pub fn dismiss_menus_and_popups(
 3301        &mut self,
 3302        is_user_requested: bool,
 3303        window: &mut Window,
 3304        cx: &mut Context<Self>,
 3305    ) -> bool {
 3306        if self.take_rename(false, window, cx).is_some() {
 3307            return true;
 3308        }
 3309
 3310        if hide_hover(self, cx) {
 3311            return true;
 3312        }
 3313
 3314        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3315            return true;
 3316        }
 3317
 3318        if self.hide_context_menu(window, cx).is_some() {
 3319            return true;
 3320        }
 3321
 3322        if self.mouse_context_menu.take().is_some() {
 3323            return true;
 3324        }
 3325
 3326        if is_user_requested && self.discard_inline_completion(true, cx) {
 3327            return true;
 3328        }
 3329
 3330        if self.snippet_stack.pop().is_some() {
 3331            return true;
 3332        }
 3333
 3334        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3335            self.dismiss_diagnostics(cx);
 3336            return true;
 3337        }
 3338
 3339        false
 3340    }
 3341
 3342    fn linked_editing_ranges_for(
 3343        &self,
 3344        selection: Range<text::Anchor>,
 3345        cx: &App,
 3346    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3347        if self.linked_edit_ranges.is_empty() {
 3348            return None;
 3349        }
 3350        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3351            selection.end.buffer_id.and_then(|end_buffer_id| {
 3352                if selection.start.buffer_id != Some(end_buffer_id) {
 3353                    return None;
 3354                }
 3355                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3356                let snapshot = buffer.read(cx).snapshot();
 3357                self.linked_edit_ranges
 3358                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3359                    .map(|ranges| (ranges, snapshot, buffer))
 3360            })?;
 3361        use text::ToOffset as TO;
 3362        // find offset from the start of current range to current cursor position
 3363        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3364
 3365        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3366        let start_difference = start_offset - start_byte_offset;
 3367        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3368        let end_difference = end_offset - start_byte_offset;
 3369        // Current range has associated linked ranges.
 3370        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3371        for range in linked_ranges.iter() {
 3372            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3373            let end_offset = start_offset + end_difference;
 3374            let start_offset = start_offset + start_difference;
 3375            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3376                continue;
 3377            }
 3378            if self.selections.disjoint_anchor_ranges().any(|s| {
 3379                if s.start.buffer_id != selection.start.buffer_id
 3380                    || s.end.buffer_id != selection.end.buffer_id
 3381                {
 3382                    return false;
 3383                }
 3384                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3385                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3386            }) {
 3387                continue;
 3388            }
 3389            let start = buffer_snapshot.anchor_after(start_offset);
 3390            let end = buffer_snapshot.anchor_after(end_offset);
 3391            linked_edits
 3392                .entry(buffer.clone())
 3393                .or_default()
 3394                .push(start..end);
 3395        }
 3396        Some(linked_edits)
 3397    }
 3398
 3399    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3400        let text: Arc<str> = text.into();
 3401
 3402        if self.read_only(cx) {
 3403            return;
 3404        }
 3405
 3406        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3407
 3408        let selections = self.selections.all_adjusted(cx);
 3409        let mut bracket_inserted = false;
 3410        let mut edits = Vec::new();
 3411        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3412        let mut new_selections = Vec::with_capacity(selections.len());
 3413        let mut new_autoclose_regions = Vec::new();
 3414        let snapshot = self.buffer.read(cx).read(cx);
 3415        let mut clear_linked_edit_ranges = false;
 3416
 3417        for (selection, autoclose_region) in
 3418            self.selections_with_autoclose_regions(selections, &snapshot)
 3419        {
 3420            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3421                // Determine if the inserted text matches the opening or closing
 3422                // bracket of any of this language's bracket pairs.
 3423                let mut bracket_pair = None;
 3424                let mut is_bracket_pair_start = false;
 3425                let mut is_bracket_pair_end = false;
 3426                if !text.is_empty() {
 3427                    let mut bracket_pair_matching_end = None;
 3428                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3429                    //  and they are removing the character that triggered IME popup.
 3430                    for (pair, enabled) in scope.brackets() {
 3431                        if !pair.close && !pair.surround {
 3432                            continue;
 3433                        }
 3434
 3435                        if enabled && pair.start.ends_with(text.as_ref()) {
 3436                            let prefix_len = pair.start.len() - text.len();
 3437                            let preceding_text_matches_prefix = prefix_len == 0
 3438                                || (selection.start.column >= (prefix_len as u32)
 3439                                    && snapshot.contains_str_at(
 3440                                        Point::new(
 3441                                            selection.start.row,
 3442                                            selection.start.column - (prefix_len as u32),
 3443                                        ),
 3444                                        &pair.start[..prefix_len],
 3445                                    ));
 3446                            if preceding_text_matches_prefix {
 3447                                bracket_pair = Some(pair.clone());
 3448                                is_bracket_pair_start = true;
 3449                                break;
 3450                            }
 3451                        }
 3452                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3453                        {
 3454                            // take first bracket pair matching end, but don't break in case a later bracket
 3455                            // pair matches start
 3456                            bracket_pair_matching_end = Some(pair.clone());
 3457                        }
 3458                    }
 3459                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3460                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3461                        is_bracket_pair_end = true;
 3462                    }
 3463                }
 3464
 3465                if let Some(bracket_pair) = bracket_pair {
 3466                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3467                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3468                    let auto_surround =
 3469                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3470                    if selection.is_empty() {
 3471                        if is_bracket_pair_start {
 3472                            // If the inserted text is a suffix of an opening bracket and the
 3473                            // selection is preceded by the rest of the opening bracket, then
 3474                            // insert the closing bracket.
 3475                            let following_text_allows_autoclose = snapshot
 3476                                .chars_at(selection.start)
 3477                                .next()
 3478                                .map_or(true, |c| scope.should_autoclose_before(c));
 3479
 3480                            let preceding_text_allows_autoclose = selection.start.column == 0
 3481                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3482                                    true,
 3483                                    |c| {
 3484                                        bracket_pair.start != bracket_pair.end
 3485                                            || !snapshot
 3486                                                .char_classifier_at(selection.start)
 3487                                                .is_word(c)
 3488                                    },
 3489                                );
 3490
 3491                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3492                                && bracket_pair.start.len() == 1
 3493                            {
 3494                                let target = bracket_pair.start.chars().next().unwrap();
 3495                                let current_line_count = snapshot
 3496                                    .reversed_chars_at(selection.start)
 3497                                    .take_while(|&c| c != '\n')
 3498                                    .filter(|&c| c == target)
 3499                                    .count();
 3500                                current_line_count % 2 == 1
 3501                            } else {
 3502                                false
 3503                            };
 3504
 3505                            if autoclose
 3506                                && bracket_pair.close
 3507                                && following_text_allows_autoclose
 3508                                && preceding_text_allows_autoclose
 3509                                && !is_closing_quote
 3510                            {
 3511                                let anchor = snapshot.anchor_before(selection.end);
 3512                                new_selections.push((selection.map(|_| anchor), text.len()));
 3513                                new_autoclose_regions.push((
 3514                                    anchor,
 3515                                    text.len(),
 3516                                    selection.id,
 3517                                    bracket_pair.clone(),
 3518                                ));
 3519                                edits.push((
 3520                                    selection.range(),
 3521                                    format!("{}{}", text, bracket_pair.end).into(),
 3522                                ));
 3523                                bracket_inserted = true;
 3524                                continue;
 3525                            }
 3526                        }
 3527
 3528                        if let Some(region) = autoclose_region {
 3529                            // If the selection is followed by an auto-inserted closing bracket,
 3530                            // then don't insert that closing bracket again; just move the selection
 3531                            // past the closing bracket.
 3532                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3533                                && text.as_ref() == region.pair.end.as_str();
 3534                            if should_skip {
 3535                                let anchor = snapshot.anchor_after(selection.end);
 3536                                new_selections
 3537                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3538                                continue;
 3539                            }
 3540                        }
 3541
 3542                        let always_treat_brackets_as_autoclosed = snapshot
 3543                            .language_settings_at(selection.start, cx)
 3544                            .always_treat_brackets_as_autoclosed;
 3545                        if always_treat_brackets_as_autoclosed
 3546                            && is_bracket_pair_end
 3547                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3548                        {
 3549                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3550                            // and the inserted text is a closing bracket and the selection is followed
 3551                            // by the closing bracket then move the selection past the closing bracket.
 3552                            let anchor = snapshot.anchor_after(selection.end);
 3553                            new_selections.push((selection.map(|_| anchor), text.len()));
 3554                            continue;
 3555                        }
 3556                    }
 3557                    // If an opening bracket is 1 character long and is typed while
 3558                    // text is selected, then surround that text with the bracket pair.
 3559                    else if auto_surround
 3560                        && bracket_pair.surround
 3561                        && is_bracket_pair_start
 3562                        && bracket_pair.start.chars().count() == 1
 3563                    {
 3564                        edits.push((selection.start..selection.start, text.clone()));
 3565                        edits.push((
 3566                            selection.end..selection.end,
 3567                            bracket_pair.end.as_str().into(),
 3568                        ));
 3569                        bracket_inserted = true;
 3570                        new_selections.push((
 3571                            Selection {
 3572                                id: selection.id,
 3573                                start: snapshot.anchor_after(selection.start),
 3574                                end: snapshot.anchor_before(selection.end),
 3575                                reversed: selection.reversed,
 3576                                goal: selection.goal,
 3577                            },
 3578                            0,
 3579                        ));
 3580                        continue;
 3581                    }
 3582                }
 3583            }
 3584
 3585            if self.auto_replace_emoji_shortcode
 3586                && selection.is_empty()
 3587                && text.as_ref().ends_with(':')
 3588            {
 3589                if let Some(possible_emoji_short_code) =
 3590                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3591                {
 3592                    if !possible_emoji_short_code.is_empty() {
 3593                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3594                            let emoji_shortcode_start = Point::new(
 3595                                selection.start.row,
 3596                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3597                            );
 3598
 3599                            // Remove shortcode from buffer
 3600                            edits.push((
 3601                                emoji_shortcode_start..selection.start,
 3602                                "".to_string().into(),
 3603                            ));
 3604                            new_selections.push((
 3605                                Selection {
 3606                                    id: selection.id,
 3607                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3608                                    end: snapshot.anchor_before(selection.start),
 3609                                    reversed: selection.reversed,
 3610                                    goal: selection.goal,
 3611                                },
 3612                                0,
 3613                            ));
 3614
 3615                            // Insert emoji
 3616                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3617                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3618                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3619
 3620                            continue;
 3621                        }
 3622                    }
 3623                }
 3624            }
 3625
 3626            // If not handling any auto-close operation, then just replace the selected
 3627            // text with the given input and move the selection to the end of the
 3628            // newly inserted text.
 3629            let anchor = snapshot.anchor_after(selection.end);
 3630            if !self.linked_edit_ranges.is_empty() {
 3631                let start_anchor = snapshot.anchor_before(selection.start);
 3632
 3633                let is_word_char = text.chars().next().map_or(true, |char| {
 3634                    let classifier = snapshot
 3635                        .char_classifier_at(start_anchor.to_offset(&snapshot))
 3636                        .ignore_punctuation(true);
 3637                    classifier.is_word(char)
 3638                });
 3639
 3640                if is_word_char {
 3641                    if let Some(ranges) = self
 3642                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3643                    {
 3644                        for (buffer, edits) in ranges {
 3645                            linked_edits
 3646                                .entry(buffer.clone())
 3647                                .or_default()
 3648                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3649                        }
 3650                    }
 3651                } else {
 3652                    clear_linked_edit_ranges = true;
 3653                }
 3654            }
 3655
 3656            new_selections.push((selection.map(|_| anchor), 0));
 3657            edits.push((selection.start..selection.end, text.clone()));
 3658        }
 3659
 3660        drop(snapshot);
 3661
 3662        self.transact(window, cx, |this, window, cx| {
 3663            if clear_linked_edit_ranges {
 3664                this.linked_edit_ranges.clear();
 3665            }
 3666            let initial_buffer_versions =
 3667                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3668
 3669            this.buffer.update(cx, |buffer, cx| {
 3670                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3671            });
 3672            for (buffer, edits) in linked_edits {
 3673                buffer.update(cx, |buffer, cx| {
 3674                    let snapshot = buffer.snapshot();
 3675                    let edits = edits
 3676                        .into_iter()
 3677                        .map(|(range, text)| {
 3678                            use text::ToPoint as TP;
 3679                            let end_point = TP::to_point(&range.end, &snapshot);
 3680                            let start_point = TP::to_point(&range.start, &snapshot);
 3681                            (start_point..end_point, text)
 3682                        })
 3683                        .sorted_by_key(|(range, _)| range.start);
 3684                    buffer.edit(edits, None, cx);
 3685                })
 3686            }
 3687            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3688            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3689            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3690            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3691                .zip(new_selection_deltas)
 3692                .map(|(selection, delta)| Selection {
 3693                    id: selection.id,
 3694                    start: selection.start + delta,
 3695                    end: selection.end + delta,
 3696                    reversed: selection.reversed,
 3697                    goal: SelectionGoal::None,
 3698                })
 3699                .collect::<Vec<_>>();
 3700
 3701            let mut i = 0;
 3702            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3703                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3704                let start = map.buffer_snapshot.anchor_before(position);
 3705                let end = map.buffer_snapshot.anchor_after(position);
 3706                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3707                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3708                        Ordering::Less => i += 1,
 3709                        Ordering::Greater => break,
 3710                        Ordering::Equal => {
 3711                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3712                                Ordering::Less => i += 1,
 3713                                Ordering::Equal => break,
 3714                                Ordering::Greater => break,
 3715                            }
 3716                        }
 3717                    }
 3718                }
 3719                this.autoclose_regions.insert(
 3720                    i,
 3721                    AutocloseRegion {
 3722                        selection_id,
 3723                        range: start..end,
 3724                        pair,
 3725                    },
 3726                );
 3727            }
 3728
 3729            let had_active_inline_completion = this.has_active_inline_completion();
 3730            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3731                s.select(new_selections)
 3732            });
 3733
 3734            if !bracket_inserted {
 3735                if let Some(on_type_format_task) =
 3736                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3737                {
 3738                    on_type_format_task.detach_and_log_err(cx);
 3739                }
 3740            }
 3741
 3742            let editor_settings = EditorSettings::get_global(cx);
 3743            if bracket_inserted
 3744                && (editor_settings.auto_signature_help
 3745                    || editor_settings.show_signature_help_after_edits)
 3746            {
 3747                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3748            }
 3749
 3750            let trigger_in_words =
 3751                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3752            if this.hard_wrap.is_some() {
 3753                let latest: Range<Point> = this.selections.newest(cx).range();
 3754                if latest.is_empty()
 3755                    && this
 3756                        .buffer()
 3757                        .read(cx)
 3758                        .snapshot(cx)
 3759                        .line_len(MultiBufferRow(latest.start.row))
 3760                        == latest.start.column
 3761                {
 3762                    this.rewrap_impl(
 3763                        RewrapOptions {
 3764                            override_language_settings: true,
 3765                            preserve_existing_whitespace: true,
 3766                        },
 3767                        cx,
 3768                    )
 3769                }
 3770            }
 3771            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3772            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3773            this.refresh_inline_completion(true, false, window, cx);
 3774            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3775        });
 3776    }
 3777
 3778    fn find_possible_emoji_shortcode_at_position(
 3779        snapshot: &MultiBufferSnapshot,
 3780        position: Point,
 3781    ) -> Option<String> {
 3782        let mut chars = Vec::new();
 3783        let mut found_colon = false;
 3784        for char in snapshot.reversed_chars_at(position).take(100) {
 3785            // Found a possible emoji shortcode in the middle of the buffer
 3786            if found_colon {
 3787                if char.is_whitespace() {
 3788                    chars.reverse();
 3789                    return Some(chars.iter().collect());
 3790                }
 3791                // If the previous character is not a whitespace, we are in the middle of a word
 3792                // and we only want to complete the shortcode if the word is made up of other emojis
 3793                let mut containing_word = String::new();
 3794                for ch in snapshot
 3795                    .reversed_chars_at(position)
 3796                    .skip(chars.len() + 1)
 3797                    .take(100)
 3798                {
 3799                    if ch.is_whitespace() {
 3800                        break;
 3801                    }
 3802                    containing_word.push(ch);
 3803                }
 3804                let containing_word = containing_word.chars().rev().collect::<String>();
 3805                if util::word_consists_of_emojis(containing_word.as_str()) {
 3806                    chars.reverse();
 3807                    return Some(chars.iter().collect());
 3808                }
 3809            }
 3810
 3811            if char.is_whitespace() || !char.is_ascii() {
 3812                return None;
 3813            }
 3814            if char == ':' {
 3815                found_colon = true;
 3816            } else {
 3817                chars.push(char);
 3818            }
 3819        }
 3820        // Found a possible emoji shortcode at the beginning of the buffer
 3821        chars.reverse();
 3822        Some(chars.iter().collect())
 3823    }
 3824
 3825    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3826        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3827        self.transact(window, cx, |this, window, cx| {
 3828            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3829                let selections = this.selections.all::<usize>(cx);
 3830                let multi_buffer = this.buffer.read(cx);
 3831                let buffer = multi_buffer.snapshot(cx);
 3832                selections
 3833                    .iter()
 3834                    .map(|selection| {
 3835                        let start_point = selection.start.to_point(&buffer);
 3836                        let mut indent =
 3837                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3838                        indent.len = cmp::min(indent.len, start_point.column);
 3839                        let start = selection.start;
 3840                        let end = selection.end;
 3841                        let selection_is_empty = start == end;
 3842                        let language_scope = buffer.language_scope_at(start);
 3843                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3844                            &language_scope
 3845                        {
 3846                            let insert_extra_newline =
 3847                                insert_extra_newline_brackets(&buffer, start..end, language)
 3848                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3849
 3850                            // Comment extension on newline is allowed only for cursor selections
 3851                            let comment_delimiter = maybe!({
 3852                                if !selection_is_empty {
 3853                                    return None;
 3854                                }
 3855
 3856                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3857                                    return None;
 3858                                }
 3859
 3860                                let delimiters = language.line_comment_prefixes();
 3861                                let max_len_of_delimiter =
 3862                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3863                                let (snapshot, range) =
 3864                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3865
 3866                                let mut index_of_first_non_whitespace = 0;
 3867                                let comment_candidate = snapshot
 3868                                    .chars_for_range(range)
 3869                                    .skip_while(|c| {
 3870                                        let should_skip = c.is_whitespace();
 3871                                        if should_skip {
 3872                                            index_of_first_non_whitespace += 1;
 3873                                        }
 3874                                        should_skip
 3875                                    })
 3876                                    .take(max_len_of_delimiter)
 3877                                    .collect::<String>();
 3878                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3879                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3880                                })?;
 3881                                let cursor_is_placed_after_comment_marker =
 3882                                    index_of_first_non_whitespace + comment_prefix.len()
 3883                                        <= start_point.column as usize;
 3884                                if cursor_is_placed_after_comment_marker {
 3885                                    Some(comment_prefix.clone())
 3886                                } else {
 3887                                    None
 3888                                }
 3889                            });
 3890                            (comment_delimiter, insert_extra_newline)
 3891                        } else {
 3892                            (None, false)
 3893                        };
 3894
 3895                        let capacity_for_delimiter = comment_delimiter
 3896                            .as_deref()
 3897                            .map(str::len)
 3898                            .unwrap_or_default();
 3899                        let mut new_text =
 3900                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3901                        new_text.push('\n');
 3902                        new_text.extend(indent.chars());
 3903                        if let Some(delimiter) = &comment_delimiter {
 3904                            new_text.push_str(delimiter);
 3905                        }
 3906                        if insert_extra_newline {
 3907                            new_text = new_text.repeat(2);
 3908                        }
 3909
 3910                        let anchor = buffer.anchor_after(end);
 3911                        let new_selection = selection.map(|_| anchor);
 3912                        (
 3913                            (start..end, new_text),
 3914                            (insert_extra_newline, new_selection),
 3915                        )
 3916                    })
 3917                    .unzip()
 3918            };
 3919
 3920            this.edit_with_autoindent(edits, cx);
 3921            let buffer = this.buffer.read(cx).snapshot(cx);
 3922            let new_selections = selection_fixup_info
 3923                .into_iter()
 3924                .map(|(extra_newline_inserted, new_selection)| {
 3925                    let mut cursor = new_selection.end.to_point(&buffer);
 3926                    if extra_newline_inserted {
 3927                        cursor.row -= 1;
 3928                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3929                    }
 3930                    new_selection.map(|_| cursor)
 3931                })
 3932                .collect();
 3933
 3934            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3935                s.select(new_selections)
 3936            });
 3937            this.refresh_inline_completion(true, false, window, cx);
 3938        });
 3939    }
 3940
 3941    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3942        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3943
 3944        let buffer = self.buffer.read(cx);
 3945        let snapshot = buffer.snapshot(cx);
 3946
 3947        let mut edits = Vec::new();
 3948        let mut rows = Vec::new();
 3949
 3950        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3951            let cursor = selection.head();
 3952            let row = cursor.row;
 3953
 3954            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3955
 3956            let newline = "\n".to_string();
 3957            edits.push((start_of_line..start_of_line, newline));
 3958
 3959            rows.push(row + rows_inserted as u32);
 3960        }
 3961
 3962        self.transact(window, cx, |editor, window, cx| {
 3963            editor.edit(edits, cx);
 3964
 3965            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3966                let mut index = 0;
 3967                s.move_cursors_with(|map, _, _| {
 3968                    let row = rows[index];
 3969                    index += 1;
 3970
 3971                    let point = Point::new(row, 0);
 3972                    let boundary = map.next_line_boundary(point).1;
 3973                    let clipped = map.clip_point(boundary, Bias::Left);
 3974
 3975                    (clipped, SelectionGoal::None)
 3976                });
 3977            });
 3978
 3979            let mut indent_edits = Vec::new();
 3980            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3981            for row in rows {
 3982                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3983                for (row, indent) in indents {
 3984                    if indent.len == 0 {
 3985                        continue;
 3986                    }
 3987
 3988                    let text = match indent.kind {
 3989                        IndentKind::Space => " ".repeat(indent.len as usize),
 3990                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3991                    };
 3992                    let point = Point::new(row.0, 0);
 3993                    indent_edits.push((point..point, text));
 3994                }
 3995            }
 3996            editor.edit(indent_edits, cx);
 3997        });
 3998    }
 3999
 4000    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 4001        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4002
 4003        let buffer = self.buffer.read(cx);
 4004        let snapshot = buffer.snapshot(cx);
 4005
 4006        let mut edits = Vec::new();
 4007        let mut rows = Vec::new();
 4008        let mut rows_inserted = 0;
 4009
 4010        for selection in self.selections.all_adjusted(cx) {
 4011            let cursor = selection.head();
 4012            let row = cursor.row;
 4013
 4014            let point = Point::new(row + 1, 0);
 4015            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4016
 4017            let newline = "\n".to_string();
 4018            edits.push((start_of_line..start_of_line, newline));
 4019
 4020            rows_inserted += 1;
 4021            rows.push(row + rows_inserted);
 4022        }
 4023
 4024        self.transact(window, cx, |editor, window, cx| {
 4025            editor.edit(edits, cx);
 4026
 4027            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4028                let mut index = 0;
 4029                s.move_cursors_with(|map, _, _| {
 4030                    let row = rows[index];
 4031                    index += 1;
 4032
 4033                    let point = Point::new(row, 0);
 4034                    let boundary = map.next_line_boundary(point).1;
 4035                    let clipped = map.clip_point(boundary, Bias::Left);
 4036
 4037                    (clipped, SelectionGoal::None)
 4038                });
 4039            });
 4040
 4041            let mut indent_edits = Vec::new();
 4042            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4043            for row in rows {
 4044                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4045                for (row, indent) in indents {
 4046                    if indent.len == 0 {
 4047                        continue;
 4048                    }
 4049
 4050                    let text = match indent.kind {
 4051                        IndentKind::Space => " ".repeat(indent.len as usize),
 4052                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4053                    };
 4054                    let point = Point::new(row.0, 0);
 4055                    indent_edits.push((point..point, text));
 4056                }
 4057            }
 4058            editor.edit(indent_edits, cx);
 4059        });
 4060    }
 4061
 4062    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4063        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4064            original_indent_columns: Vec::new(),
 4065        });
 4066        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4067    }
 4068
 4069    fn insert_with_autoindent_mode(
 4070        &mut self,
 4071        text: &str,
 4072        autoindent_mode: Option<AutoindentMode>,
 4073        window: &mut Window,
 4074        cx: &mut Context<Self>,
 4075    ) {
 4076        if self.read_only(cx) {
 4077            return;
 4078        }
 4079
 4080        let text: Arc<str> = text.into();
 4081        self.transact(window, cx, |this, window, cx| {
 4082            let old_selections = this.selections.all_adjusted(cx);
 4083            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4084                let anchors = {
 4085                    let snapshot = buffer.read(cx);
 4086                    old_selections
 4087                        .iter()
 4088                        .map(|s| {
 4089                            let anchor = snapshot.anchor_after(s.head());
 4090                            s.map(|_| anchor)
 4091                        })
 4092                        .collect::<Vec<_>>()
 4093                };
 4094                buffer.edit(
 4095                    old_selections
 4096                        .iter()
 4097                        .map(|s| (s.start..s.end, text.clone())),
 4098                    autoindent_mode,
 4099                    cx,
 4100                );
 4101                anchors
 4102            });
 4103
 4104            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4105                s.select_anchors(selection_anchors);
 4106            });
 4107
 4108            cx.notify();
 4109        });
 4110    }
 4111
 4112    fn trigger_completion_on_input(
 4113        &mut self,
 4114        text: &str,
 4115        trigger_in_words: bool,
 4116        window: &mut Window,
 4117        cx: &mut Context<Self>,
 4118    ) {
 4119        let ignore_completion_provider = self
 4120            .context_menu
 4121            .borrow()
 4122            .as_ref()
 4123            .map(|menu| match menu {
 4124                CodeContextMenu::Completions(completions_menu) => {
 4125                    completions_menu.ignore_completion_provider
 4126                }
 4127                CodeContextMenu::CodeActions(_) => false,
 4128            })
 4129            .unwrap_or(false);
 4130
 4131        if ignore_completion_provider {
 4132            self.show_word_completions(&ShowWordCompletions, window, cx);
 4133        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4134            self.show_completions(
 4135                &ShowCompletions {
 4136                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4137                },
 4138                window,
 4139                cx,
 4140            );
 4141        } else {
 4142            self.hide_context_menu(window, cx);
 4143        }
 4144    }
 4145
 4146    fn is_completion_trigger(
 4147        &self,
 4148        text: &str,
 4149        trigger_in_words: bool,
 4150        cx: &mut Context<Self>,
 4151    ) -> bool {
 4152        let position = self.selections.newest_anchor().head();
 4153        let multibuffer = self.buffer.read(cx);
 4154        let Some(buffer) = position
 4155            .buffer_id
 4156            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4157        else {
 4158            return false;
 4159        };
 4160
 4161        if let Some(completion_provider) = &self.completion_provider {
 4162            completion_provider.is_completion_trigger(
 4163                &buffer,
 4164                position.text_anchor,
 4165                text,
 4166                trigger_in_words,
 4167                cx,
 4168            )
 4169        } else {
 4170            false
 4171        }
 4172    }
 4173
 4174    /// If any empty selections is touching the start of its innermost containing autoclose
 4175    /// region, expand it to select the brackets.
 4176    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4177        let selections = self.selections.all::<usize>(cx);
 4178        let buffer = self.buffer.read(cx).read(cx);
 4179        let new_selections = self
 4180            .selections_with_autoclose_regions(selections, &buffer)
 4181            .map(|(mut selection, region)| {
 4182                if !selection.is_empty() {
 4183                    return selection;
 4184                }
 4185
 4186                if let Some(region) = region {
 4187                    let mut range = region.range.to_offset(&buffer);
 4188                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4189                        range.start -= region.pair.start.len();
 4190                        if buffer.contains_str_at(range.start, &region.pair.start)
 4191                            && buffer.contains_str_at(range.end, &region.pair.end)
 4192                        {
 4193                            range.end += region.pair.end.len();
 4194                            selection.start = range.start;
 4195                            selection.end = range.end;
 4196
 4197                            return selection;
 4198                        }
 4199                    }
 4200                }
 4201
 4202                let always_treat_brackets_as_autoclosed = buffer
 4203                    .language_settings_at(selection.start, cx)
 4204                    .always_treat_brackets_as_autoclosed;
 4205
 4206                if !always_treat_brackets_as_autoclosed {
 4207                    return selection;
 4208                }
 4209
 4210                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4211                    for (pair, enabled) in scope.brackets() {
 4212                        if !enabled || !pair.close {
 4213                            continue;
 4214                        }
 4215
 4216                        if buffer.contains_str_at(selection.start, &pair.end) {
 4217                            let pair_start_len = pair.start.len();
 4218                            if buffer.contains_str_at(
 4219                                selection.start.saturating_sub(pair_start_len),
 4220                                &pair.start,
 4221                            ) {
 4222                                selection.start -= pair_start_len;
 4223                                selection.end += pair.end.len();
 4224
 4225                                return selection;
 4226                            }
 4227                        }
 4228                    }
 4229                }
 4230
 4231                selection
 4232            })
 4233            .collect();
 4234
 4235        drop(buffer);
 4236        self.change_selections(None, window, cx, |selections| {
 4237            selections.select(new_selections)
 4238        });
 4239    }
 4240
 4241    /// Iterate the given selections, and for each one, find the smallest surrounding
 4242    /// autoclose region. This uses the ordering of the selections and the autoclose
 4243    /// regions to avoid repeated comparisons.
 4244    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4245        &'a self,
 4246        selections: impl IntoIterator<Item = Selection<D>>,
 4247        buffer: &'a MultiBufferSnapshot,
 4248    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4249        let mut i = 0;
 4250        let mut regions = self.autoclose_regions.as_slice();
 4251        selections.into_iter().map(move |selection| {
 4252            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4253
 4254            let mut enclosing = None;
 4255            while let Some(pair_state) = regions.get(i) {
 4256                if pair_state.range.end.to_offset(buffer) < range.start {
 4257                    regions = &regions[i + 1..];
 4258                    i = 0;
 4259                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4260                    break;
 4261                } else {
 4262                    if pair_state.selection_id == selection.id {
 4263                        enclosing = Some(pair_state);
 4264                    }
 4265                    i += 1;
 4266                }
 4267            }
 4268
 4269            (selection, enclosing)
 4270        })
 4271    }
 4272
 4273    /// Remove any autoclose regions that no longer contain their selection.
 4274    fn invalidate_autoclose_regions(
 4275        &mut self,
 4276        mut selections: &[Selection<Anchor>],
 4277        buffer: &MultiBufferSnapshot,
 4278    ) {
 4279        self.autoclose_regions.retain(|state| {
 4280            let mut i = 0;
 4281            while let Some(selection) = selections.get(i) {
 4282                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4283                    selections = &selections[1..];
 4284                    continue;
 4285                }
 4286                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4287                    break;
 4288                }
 4289                if selection.id == state.selection_id {
 4290                    return true;
 4291                } else {
 4292                    i += 1;
 4293                }
 4294            }
 4295            false
 4296        });
 4297    }
 4298
 4299    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4300        let offset = position.to_offset(buffer);
 4301        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4302        if offset > word_range.start && kind == Some(CharKind::Word) {
 4303            Some(
 4304                buffer
 4305                    .text_for_range(word_range.start..offset)
 4306                    .collect::<String>(),
 4307            )
 4308        } else {
 4309            None
 4310        }
 4311    }
 4312
 4313    pub fn toggle_inline_values(
 4314        &mut self,
 4315        _: &ToggleInlineValues,
 4316        _: &mut Window,
 4317        cx: &mut Context<Self>,
 4318    ) {
 4319        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4320
 4321        self.refresh_inline_values(cx);
 4322    }
 4323
 4324    pub fn toggle_inlay_hints(
 4325        &mut self,
 4326        _: &ToggleInlayHints,
 4327        _: &mut Window,
 4328        cx: &mut Context<Self>,
 4329    ) {
 4330        self.refresh_inlay_hints(
 4331            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4332            cx,
 4333        );
 4334    }
 4335
 4336    pub fn inlay_hints_enabled(&self) -> bool {
 4337        self.inlay_hint_cache.enabled
 4338    }
 4339
 4340    pub fn inline_values_enabled(&self) -> bool {
 4341        self.inline_value_cache.enabled
 4342    }
 4343
 4344    #[cfg(any(test, feature = "test-support"))]
 4345    pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
 4346        self.display_map
 4347            .read(cx)
 4348            .current_inlays()
 4349            .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
 4350            .cloned()
 4351            .collect()
 4352    }
 4353
 4354    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4355        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4356            return;
 4357        }
 4358
 4359        let reason_description = reason.description();
 4360        let ignore_debounce = matches!(
 4361            reason,
 4362            InlayHintRefreshReason::SettingsChange(_)
 4363                | InlayHintRefreshReason::Toggle(_)
 4364                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4365                | InlayHintRefreshReason::ModifiersChanged(_)
 4366        );
 4367        let (invalidate_cache, required_languages) = match reason {
 4368            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4369                match self.inlay_hint_cache.modifiers_override(enabled) {
 4370                    Some(enabled) => {
 4371                        if enabled {
 4372                            (InvalidationStrategy::RefreshRequested, None)
 4373                        } else {
 4374                            self.splice_inlays(
 4375                                &self
 4376                                    .visible_inlay_hints(cx)
 4377                                    .iter()
 4378                                    .map(|inlay| inlay.id)
 4379                                    .collect::<Vec<InlayId>>(),
 4380                                Vec::new(),
 4381                                cx,
 4382                            );
 4383                            return;
 4384                        }
 4385                    }
 4386                    None => return,
 4387                }
 4388            }
 4389            InlayHintRefreshReason::Toggle(enabled) => {
 4390                if self.inlay_hint_cache.toggle(enabled) {
 4391                    if enabled {
 4392                        (InvalidationStrategy::RefreshRequested, None)
 4393                    } else {
 4394                        self.splice_inlays(
 4395                            &self
 4396                                .visible_inlay_hints(cx)
 4397                                .iter()
 4398                                .map(|inlay| inlay.id)
 4399                                .collect::<Vec<InlayId>>(),
 4400                            Vec::new(),
 4401                            cx,
 4402                        );
 4403                        return;
 4404                    }
 4405                } else {
 4406                    return;
 4407                }
 4408            }
 4409            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4410                match self.inlay_hint_cache.update_settings(
 4411                    &self.buffer,
 4412                    new_settings,
 4413                    self.visible_inlay_hints(cx),
 4414                    cx,
 4415                ) {
 4416                    ControlFlow::Break(Some(InlaySplice {
 4417                        to_remove,
 4418                        to_insert,
 4419                    })) => {
 4420                        self.splice_inlays(&to_remove, to_insert, cx);
 4421                        return;
 4422                    }
 4423                    ControlFlow::Break(None) => return,
 4424                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4425                }
 4426            }
 4427            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4428                if let Some(InlaySplice {
 4429                    to_remove,
 4430                    to_insert,
 4431                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4432                {
 4433                    self.splice_inlays(&to_remove, to_insert, cx);
 4434                }
 4435                self.display_map.update(cx, |display_map, _| {
 4436                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4437                });
 4438                return;
 4439            }
 4440            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4441            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4442                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4443            }
 4444            InlayHintRefreshReason::RefreshRequested => {
 4445                (InvalidationStrategy::RefreshRequested, None)
 4446            }
 4447        };
 4448
 4449        if let Some(InlaySplice {
 4450            to_remove,
 4451            to_insert,
 4452        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4453            reason_description,
 4454            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4455            invalidate_cache,
 4456            ignore_debounce,
 4457            cx,
 4458        ) {
 4459            self.splice_inlays(&to_remove, to_insert, cx);
 4460        }
 4461    }
 4462
 4463    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4464        self.display_map
 4465            .read(cx)
 4466            .current_inlays()
 4467            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4468            .cloned()
 4469            .collect()
 4470    }
 4471
 4472    pub fn excerpts_for_inlay_hints_query(
 4473        &self,
 4474        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4475        cx: &mut Context<Editor>,
 4476    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4477        let Some(project) = self.project.as_ref() else {
 4478            return HashMap::default();
 4479        };
 4480        let project = project.read(cx);
 4481        let multi_buffer = self.buffer().read(cx);
 4482        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4483        let multi_buffer_visible_start = self
 4484            .scroll_manager
 4485            .anchor()
 4486            .anchor
 4487            .to_point(&multi_buffer_snapshot);
 4488        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4489            multi_buffer_visible_start
 4490                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4491            Bias::Left,
 4492        );
 4493        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4494        multi_buffer_snapshot
 4495            .range_to_buffer_ranges(multi_buffer_visible_range)
 4496            .into_iter()
 4497            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4498            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4499                let buffer_file = project::File::from_dyn(buffer.file())?;
 4500                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4501                let worktree_entry = buffer_worktree
 4502                    .read(cx)
 4503                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4504                if worktree_entry.is_ignored {
 4505                    return None;
 4506                }
 4507
 4508                let language = buffer.language()?;
 4509                if let Some(restrict_to_languages) = restrict_to_languages {
 4510                    if !restrict_to_languages.contains(language) {
 4511                        return None;
 4512                    }
 4513                }
 4514                Some((
 4515                    excerpt_id,
 4516                    (
 4517                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4518                        buffer.version().clone(),
 4519                        excerpt_visible_range,
 4520                    ),
 4521                ))
 4522            })
 4523            .collect()
 4524    }
 4525
 4526    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4527        TextLayoutDetails {
 4528            text_system: window.text_system().clone(),
 4529            editor_style: self.style.clone().unwrap(),
 4530            rem_size: window.rem_size(),
 4531            scroll_anchor: self.scroll_manager.anchor(),
 4532            visible_rows: self.visible_line_count(),
 4533            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4534        }
 4535    }
 4536
 4537    pub fn splice_inlays(
 4538        &self,
 4539        to_remove: &[InlayId],
 4540        to_insert: Vec<Inlay>,
 4541        cx: &mut Context<Self>,
 4542    ) {
 4543        self.display_map.update(cx, |display_map, cx| {
 4544            display_map.splice_inlays(to_remove, to_insert, cx)
 4545        });
 4546        cx.notify();
 4547    }
 4548
 4549    fn trigger_on_type_formatting(
 4550        &self,
 4551        input: String,
 4552        window: &mut Window,
 4553        cx: &mut Context<Self>,
 4554    ) -> Option<Task<Result<()>>> {
 4555        if input.len() != 1 {
 4556            return None;
 4557        }
 4558
 4559        let project = self.project.as_ref()?;
 4560        let position = self.selections.newest_anchor().head();
 4561        let (buffer, buffer_position) = self
 4562            .buffer
 4563            .read(cx)
 4564            .text_anchor_for_position(position, cx)?;
 4565
 4566        let settings = language_settings::language_settings(
 4567            buffer
 4568                .read(cx)
 4569                .language_at(buffer_position)
 4570                .map(|l| l.name()),
 4571            buffer.read(cx).file(),
 4572            cx,
 4573        );
 4574        if !settings.use_on_type_format {
 4575            return None;
 4576        }
 4577
 4578        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4579        // hence we do LSP request & edit on host side only — add formats to host's history.
 4580        let push_to_lsp_host_history = true;
 4581        // If this is not the host, append its history with new edits.
 4582        let push_to_client_history = project.read(cx).is_via_collab();
 4583
 4584        let on_type_formatting = project.update(cx, |project, cx| {
 4585            project.on_type_format(
 4586                buffer.clone(),
 4587                buffer_position,
 4588                input,
 4589                push_to_lsp_host_history,
 4590                cx,
 4591            )
 4592        });
 4593        Some(cx.spawn_in(window, async move |editor, cx| {
 4594            if let Some(transaction) = on_type_formatting.await? {
 4595                if push_to_client_history {
 4596                    buffer
 4597                        .update(cx, |buffer, _| {
 4598                            buffer.push_transaction(transaction, Instant::now());
 4599                            buffer.finalize_last_transaction();
 4600                        })
 4601                        .ok();
 4602                }
 4603                editor.update(cx, |editor, cx| {
 4604                    editor.refresh_document_highlights(cx);
 4605                })?;
 4606            }
 4607            Ok(())
 4608        }))
 4609    }
 4610
 4611    pub fn show_word_completions(
 4612        &mut self,
 4613        _: &ShowWordCompletions,
 4614        window: &mut Window,
 4615        cx: &mut Context<Self>,
 4616    ) {
 4617        self.open_completions_menu(true, None, window, cx);
 4618    }
 4619
 4620    pub fn show_completions(
 4621        &mut self,
 4622        options: &ShowCompletions,
 4623        window: &mut Window,
 4624        cx: &mut Context<Self>,
 4625    ) {
 4626        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4627    }
 4628
 4629    fn open_completions_menu(
 4630        &mut self,
 4631        ignore_completion_provider: bool,
 4632        trigger: Option<&str>,
 4633        window: &mut Window,
 4634        cx: &mut Context<Self>,
 4635    ) {
 4636        if self.pending_rename.is_some() {
 4637            return;
 4638        }
 4639        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4640            return;
 4641        }
 4642
 4643        let position = self.selections.newest_anchor().head();
 4644        if position.diff_base_anchor.is_some() {
 4645            return;
 4646        }
 4647        let (buffer, buffer_position) =
 4648            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4649                output
 4650            } else {
 4651                return;
 4652            };
 4653        let buffer_snapshot = buffer.read(cx).snapshot();
 4654        let show_completion_documentation = buffer_snapshot
 4655            .settings_at(buffer_position, cx)
 4656            .show_completion_documentation;
 4657
 4658        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4659
 4660        let trigger_kind = match trigger {
 4661            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4662                CompletionTriggerKind::TRIGGER_CHARACTER
 4663            }
 4664            _ => CompletionTriggerKind::INVOKED,
 4665        };
 4666        let completion_context = CompletionContext {
 4667            trigger_character: trigger.and_then(|trigger| {
 4668                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4669                    Some(String::from(trigger))
 4670                } else {
 4671                    None
 4672                }
 4673            }),
 4674            trigger_kind,
 4675        };
 4676
 4677        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4678        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4679            let word_to_exclude = buffer_snapshot
 4680                .text_for_range(old_range.clone())
 4681                .collect::<String>();
 4682            (
 4683                buffer_snapshot.anchor_before(old_range.start)
 4684                    ..buffer_snapshot.anchor_after(old_range.end),
 4685                Some(word_to_exclude),
 4686            )
 4687        } else {
 4688            (buffer_position..buffer_position, None)
 4689        };
 4690
 4691        let completion_settings = language_settings(
 4692            buffer_snapshot
 4693                .language_at(buffer_position)
 4694                .map(|language| language.name()),
 4695            buffer_snapshot.file(),
 4696            cx,
 4697        )
 4698        .completions;
 4699
 4700        // The document can be large, so stay in reasonable bounds when searching for words,
 4701        // otherwise completion pop-up might be slow to appear.
 4702        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4703        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4704        let min_word_search = buffer_snapshot.clip_point(
 4705            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4706            Bias::Left,
 4707        );
 4708        let max_word_search = buffer_snapshot.clip_point(
 4709            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4710            Bias::Right,
 4711        );
 4712        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4713            ..buffer_snapshot.point_to_offset(max_word_search);
 4714
 4715        let provider = self
 4716            .completion_provider
 4717            .as_ref()
 4718            .filter(|_| !ignore_completion_provider);
 4719        let skip_digits = query
 4720            .as_ref()
 4721            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4722
 4723        let (mut words, provided_completions) = match provider {
 4724            Some(provider) => {
 4725                let completions = provider.completions(
 4726                    position.excerpt_id,
 4727                    &buffer,
 4728                    buffer_position,
 4729                    completion_context,
 4730                    window,
 4731                    cx,
 4732                );
 4733
 4734                let words = match completion_settings.words {
 4735                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4736                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4737                        .background_spawn(async move {
 4738                            buffer_snapshot.words_in_range(WordsQuery {
 4739                                fuzzy_contents: None,
 4740                                range: word_search_range,
 4741                                skip_digits,
 4742                            })
 4743                        }),
 4744                };
 4745
 4746                (words, completions)
 4747            }
 4748            None => (
 4749                cx.background_spawn(async move {
 4750                    buffer_snapshot.words_in_range(WordsQuery {
 4751                        fuzzy_contents: None,
 4752                        range: word_search_range,
 4753                        skip_digits,
 4754                    })
 4755                }),
 4756                Task::ready(Ok(None)),
 4757            ),
 4758        };
 4759
 4760        let sort_completions = provider
 4761            .as_ref()
 4762            .map_or(false, |provider| provider.sort_completions());
 4763
 4764        let filter_completions = provider
 4765            .as_ref()
 4766            .map_or(true, |provider| provider.filter_completions());
 4767
 4768        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4769
 4770        let id = post_inc(&mut self.next_completion_id);
 4771        let task = cx.spawn_in(window, async move |editor, cx| {
 4772            async move {
 4773                editor.update(cx, |this, _| {
 4774                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4775                })?;
 4776
 4777                let mut completions = Vec::new();
 4778                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4779                    completions.extend(provided_completions);
 4780                    if completion_settings.words == WordsCompletionMode::Fallback {
 4781                        words = Task::ready(BTreeMap::default());
 4782                    }
 4783                }
 4784
 4785                let mut words = words.await;
 4786                if let Some(word_to_exclude) = &word_to_exclude {
 4787                    words.remove(word_to_exclude);
 4788                }
 4789                for lsp_completion in &completions {
 4790                    words.remove(&lsp_completion.new_text);
 4791                }
 4792                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4793                    replace_range: old_range.clone(),
 4794                    new_text: word.clone(),
 4795                    label: CodeLabel::plain(word, None),
 4796                    icon_path: None,
 4797                    documentation: None,
 4798                    source: CompletionSource::BufferWord {
 4799                        word_range,
 4800                        resolved: false,
 4801                    },
 4802                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4803                    confirm: None,
 4804                }));
 4805
 4806                let menu = if completions.is_empty() {
 4807                    None
 4808                } else {
 4809                    let mut menu = CompletionsMenu::new(
 4810                        id,
 4811                        sort_completions,
 4812                        show_completion_documentation,
 4813                        ignore_completion_provider,
 4814                        position,
 4815                        buffer.clone(),
 4816                        completions.into(),
 4817                        snippet_sort_order,
 4818                    );
 4819
 4820                    menu.filter(
 4821                        if filter_completions {
 4822                            query.as_deref()
 4823                        } else {
 4824                            None
 4825                        },
 4826                        cx.background_executor().clone(),
 4827                    )
 4828                    .await;
 4829
 4830                    menu.visible().then_some(menu)
 4831                };
 4832
 4833                editor.update_in(cx, |editor, window, cx| {
 4834                    match editor.context_menu.borrow().as_ref() {
 4835                        None => {}
 4836                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4837                            if prev_menu.id > id {
 4838                                return;
 4839                            }
 4840                        }
 4841                        _ => return,
 4842                    }
 4843
 4844                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4845                        let mut menu = menu.unwrap();
 4846                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4847
 4848                        *editor.context_menu.borrow_mut() =
 4849                            Some(CodeContextMenu::Completions(menu));
 4850
 4851                        if editor.show_edit_predictions_in_menu() {
 4852                            editor.update_visible_inline_completion(window, cx);
 4853                        } else {
 4854                            editor.discard_inline_completion(false, cx);
 4855                        }
 4856
 4857                        cx.notify();
 4858                    } else if editor.completion_tasks.len() <= 1 {
 4859                        // If there are no more completion tasks and the last menu was
 4860                        // empty, we should hide it.
 4861                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4862                        // If it was already hidden and we don't show inline
 4863                        // completions in the menu, we should also show the
 4864                        // inline-completion when available.
 4865                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4866                            editor.update_visible_inline_completion(window, cx);
 4867                        }
 4868                    }
 4869                })?;
 4870
 4871                anyhow::Ok(())
 4872            }
 4873            .log_err()
 4874            .await
 4875        });
 4876
 4877        self.completion_tasks.push((id, task));
 4878    }
 4879
 4880    #[cfg(feature = "test-support")]
 4881    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4882        let menu = self.context_menu.borrow();
 4883        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4884            let completions = menu.completions.borrow();
 4885            Some(completions.to_vec())
 4886        } else {
 4887            None
 4888        }
 4889    }
 4890
 4891    pub fn confirm_completion(
 4892        &mut self,
 4893        action: &ConfirmCompletion,
 4894        window: &mut Window,
 4895        cx: &mut Context<Self>,
 4896    ) -> Option<Task<Result<()>>> {
 4897        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4898        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4899    }
 4900
 4901    pub fn confirm_completion_insert(
 4902        &mut self,
 4903        _: &ConfirmCompletionInsert,
 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::CompleteWithInsert, window, cx)
 4909    }
 4910
 4911    pub fn confirm_completion_replace(
 4912        &mut self,
 4913        _: &ConfirmCompletionReplace,
 4914        window: &mut Window,
 4915        cx: &mut Context<Self>,
 4916    ) -> Option<Task<Result<()>>> {
 4917        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4918        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4919    }
 4920
 4921    pub fn compose_completion(
 4922        &mut self,
 4923        action: &ComposeCompletion,
 4924        window: &mut Window,
 4925        cx: &mut Context<Self>,
 4926    ) -> Option<Task<Result<()>>> {
 4927        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4928        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4929    }
 4930
 4931    fn do_completion(
 4932        &mut self,
 4933        item_ix: Option<usize>,
 4934        intent: CompletionIntent,
 4935        window: &mut Window,
 4936        cx: &mut Context<Editor>,
 4937    ) -> Option<Task<Result<()>>> {
 4938        use language::ToOffset as _;
 4939
 4940        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4941        else {
 4942            return None;
 4943        };
 4944
 4945        let candidate_id = {
 4946            let entries = completions_menu.entries.borrow();
 4947            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4948            if self.show_edit_predictions_in_menu() {
 4949                self.discard_inline_completion(true, cx);
 4950            }
 4951            mat.candidate_id
 4952        };
 4953
 4954        let buffer_handle = completions_menu.buffer;
 4955        let completion = completions_menu
 4956            .completions
 4957            .borrow()
 4958            .get(candidate_id)?
 4959            .clone();
 4960        cx.stop_propagation();
 4961
 4962        let snippet;
 4963        let new_text;
 4964        if completion.is_snippet() {
 4965            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4966            new_text = snippet.as_ref().unwrap().text.clone();
 4967        } else {
 4968            snippet = None;
 4969            new_text = completion.new_text.clone();
 4970        };
 4971
 4972        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4973        let buffer = buffer_handle.read(cx);
 4974        let snapshot = self.buffer.read(cx).snapshot(cx);
 4975        let replace_range_multibuffer = {
 4976            let excerpt = snapshot
 4977                .excerpt_containing(self.selections.newest_anchor().range())
 4978                .unwrap();
 4979            let multibuffer_anchor = snapshot
 4980                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4981                .unwrap()
 4982                ..snapshot
 4983                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4984                    .unwrap();
 4985            multibuffer_anchor.start.to_offset(&snapshot)
 4986                ..multibuffer_anchor.end.to_offset(&snapshot)
 4987        };
 4988        let newest_anchor = self.selections.newest_anchor();
 4989        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4990            return None;
 4991        }
 4992
 4993        let old_text = buffer
 4994            .text_for_range(replace_range.clone())
 4995            .collect::<String>();
 4996        let lookbehind = newest_anchor
 4997            .start
 4998            .text_anchor
 4999            .to_offset(buffer)
 5000            .saturating_sub(replace_range.start);
 5001        let lookahead = replace_range
 5002            .end
 5003            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 5004        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 5005        let suffix = &old_text[lookbehind.min(old_text.len())..];
 5006
 5007        let selections = self.selections.all::<usize>(cx);
 5008        let mut ranges = Vec::new();
 5009        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 5010
 5011        for selection in &selections {
 5012            let range = if selection.id == newest_anchor.id {
 5013                replace_range_multibuffer.clone()
 5014            } else {
 5015                let mut range = selection.range();
 5016
 5017                // if prefix is present, don't duplicate it
 5018                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5019                    range.start = range.start.saturating_sub(lookbehind);
 5020
 5021                    // if suffix is also present, mimic the newest cursor and replace it
 5022                    if selection.id != newest_anchor.id
 5023                        && snapshot.contains_str_at(range.end, suffix)
 5024                    {
 5025                        range.end += lookahead;
 5026                    }
 5027                }
 5028                range
 5029            };
 5030
 5031            ranges.push(range.clone());
 5032
 5033            if !self.linked_edit_ranges.is_empty() {
 5034                let start_anchor = snapshot.anchor_before(range.start);
 5035                let end_anchor = snapshot.anchor_after(range.end);
 5036                if let Some(ranges) = self
 5037                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5038                {
 5039                    for (buffer, edits) in ranges {
 5040                        linked_edits
 5041                            .entry(buffer.clone())
 5042                            .or_default()
 5043                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5044                    }
 5045                }
 5046            }
 5047        }
 5048
 5049        cx.emit(EditorEvent::InputHandled {
 5050            utf16_range_to_replace: None,
 5051            text: new_text.clone().into(),
 5052        });
 5053
 5054        self.transact(window, cx, |this, window, cx| {
 5055            if let Some(mut snippet) = snippet {
 5056                snippet.text = new_text.to_string();
 5057                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5058            } else {
 5059                this.buffer.update(cx, |buffer, cx| {
 5060                    let auto_indent = match completion.insert_text_mode {
 5061                        Some(InsertTextMode::AS_IS) => None,
 5062                        _ => this.autoindent_mode.clone(),
 5063                    };
 5064                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5065                    buffer.edit(edits, auto_indent, cx);
 5066                });
 5067            }
 5068            for (buffer, edits) in linked_edits {
 5069                buffer.update(cx, |buffer, cx| {
 5070                    let snapshot = buffer.snapshot();
 5071                    let edits = edits
 5072                        .into_iter()
 5073                        .map(|(range, text)| {
 5074                            use text::ToPoint as TP;
 5075                            let end_point = TP::to_point(&range.end, &snapshot);
 5076                            let start_point = TP::to_point(&range.start, &snapshot);
 5077                            (start_point..end_point, text)
 5078                        })
 5079                        .sorted_by_key(|(range, _)| range.start);
 5080                    buffer.edit(edits, None, cx);
 5081                })
 5082            }
 5083
 5084            this.refresh_inline_completion(true, false, window, cx);
 5085        });
 5086
 5087        let show_new_completions_on_confirm = completion
 5088            .confirm
 5089            .as_ref()
 5090            .map_or(false, |confirm| confirm(intent, window, cx));
 5091        if show_new_completions_on_confirm {
 5092            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5093        }
 5094
 5095        let provider = self.completion_provider.as_ref()?;
 5096        drop(completion);
 5097        let apply_edits = provider.apply_additional_edits_for_completion(
 5098            buffer_handle,
 5099            completions_menu.completions.clone(),
 5100            candidate_id,
 5101            true,
 5102            cx,
 5103        );
 5104
 5105        let editor_settings = EditorSettings::get_global(cx);
 5106        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5107            // After the code completion is finished, users often want to know what signatures are needed.
 5108            // so we should automatically call signature_help
 5109            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5110        }
 5111
 5112        Some(cx.foreground_executor().spawn(async move {
 5113            apply_edits.await?;
 5114            Ok(())
 5115        }))
 5116    }
 5117
 5118    pub fn toggle_code_actions(
 5119        &mut self,
 5120        action: &ToggleCodeActions,
 5121        window: &mut Window,
 5122        cx: &mut Context<Self>,
 5123    ) {
 5124        let quick_launch = action.quick_launch;
 5125        let mut context_menu = self.context_menu.borrow_mut();
 5126        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5127            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5128                // Toggle if we're selecting the same one
 5129                *context_menu = None;
 5130                cx.notify();
 5131                return;
 5132            } else {
 5133                // Otherwise, clear it and start a new one
 5134                *context_menu = None;
 5135                cx.notify();
 5136            }
 5137        }
 5138        drop(context_menu);
 5139        let snapshot = self.snapshot(window, cx);
 5140        let deployed_from_indicator = action.deployed_from_indicator;
 5141        let mut task = self.code_actions_task.take();
 5142        let action = action.clone();
 5143        cx.spawn_in(window, async move |editor, cx| {
 5144            while let Some(prev_task) = task {
 5145                prev_task.await.log_err();
 5146                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5147            }
 5148
 5149            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5150                if editor.focus_handle.is_focused(window) {
 5151                    let multibuffer_point = action
 5152                        .deployed_from_indicator
 5153                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5154                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5155                    let (buffer, buffer_row) = snapshot
 5156                        .buffer_snapshot
 5157                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5158                        .and_then(|(buffer_snapshot, range)| {
 5159                            editor
 5160                                .buffer
 5161                                .read(cx)
 5162                                .buffer(buffer_snapshot.remote_id())
 5163                                .map(|buffer| (buffer, range.start.row))
 5164                        })?;
 5165                    let (_, code_actions) = editor
 5166                        .available_code_actions
 5167                        .clone()
 5168                        .and_then(|(location, code_actions)| {
 5169                            let snapshot = location.buffer.read(cx).snapshot();
 5170                            let point_range = location.range.to_point(&snapshot);
 5171                            let point_range = point_range.start.row..=point_range.end.row;
 5172                            if point_range.contains(&buffer_row) {
 5173                                Some((location, code_actions))
 5174                            } else {
 5175                                None
 5176                            }
 5177                        })
 5178                        .unzip();
 5179                    let buffer_id = buffer.read(cx).remote_id();
 5180                    let tasks = editor
 5181                        .tasks
 5182                        .get(&(buffer_id, buffer_row))
 5183                        .map(|t| Arc::new(t.to_owned()));
 5184                    if tasks.is_none() && code_actions.is_none() {
 5185                        return None;
 5186                    }
 5187
 5188                    editor.completion_tasks.clear();
 5189                    editor.discard_inline_completion(false, cx);
 5190                    let task_context =
 5191                        tasks
 5192                            .as_ref()
 5193                            .zip(editor.project.clone())
 5194                            .map(|(tasks, project)| {
 5195                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5196                            });
 5197
 5198                    Some(cx.spawn_in(window, async move |editor, cx| {
 5199                        let task_context = match task_context {
 5200                            Some(task_context) => task_context.await,
 5201                            None => None,
 5202                        };
 5203                        let resolved_tasks =
 5204                            tasks
 5205                                .zip(task_context.clone())
 5206                                .map(|(tasks, task_context)| ResolvedTasks {
 5207                                    templates: tasks.resolve(&task_context).collect(),
 5208                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5209                                        multibuffer_point.row,
 5210                                        tasks.column,
 5211                                    )),
 5212                                });
 5213                        let spawn_straight_away = quick_launch
 5214                            && resolved_tasks
 5215                                .as_ref()
 5216                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5217                            && code_actions
 5218                                .as_ref()
 5219                                .map_or(true, |actions| actions.is_empty());
 5220                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5221                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5222                                maybe!({
 5223                                    let project = editor.project.as_ref()?;
 5224                                    let dap_store = project.read(cx).dap_store();
 5225                                    let mut scenarios = vec![];
 5226                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5227                                    let buffer = buffer.read(cx);
 5228                                    let language = buffer.language()?;
 5229                                    let file = buffer.file();
 5230                                    let debug_adapter =
 5231                                        language_settings(language.name().into(), file, cx)
 5232                                            .debuggers
 5233                                            .first()
 5234                                            .map(SharedString::from)
 5235                                            .or_else(|| {
 5236                                                language
 5237                                                    .config()
 5238                                                    .debuggers
 5239                                                    .first()
 5240                                                    .map(SharedString::from)
 5241                                            })?;
 5242
 5243                                    dap_store.update(cx, |this, cx| {
 5244                                        for (_, task) in &resolved_tasks.templates {
 5245                                            if let Some(scenario) = this
 5246                                                .debug_scenario_for_build_task(
 5247                                                    task.original_task().clone(),
 5248                                                    debug_adapter.clone(),
 5249                                                    cx,
 5250                                                )
 5251                                            {
 5252                                                scenarios.push(scenario);
 5253                                            }
 5254                                        }
 5255                                    });
 5256                                    Some(scenarios)
 5257                                })
 5258                                .unwrap_or_default()
 5259                            } else {
 5260                                vec![]
 5261                            }
 5262                        })?;
 5263                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5264                            *editor.context_menu.borrow_mut() =
 5265                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5266                                    buffer,
 5267                                    actions: CodeActionContents::new(
 5268                                        resolved_tasks,
 5269                                        code_actions,
 5270                                        debug_scenarios,
 5271                                        task_context.unwrap_or_default(),
 5272                                    ),
 5273                                    selected_item: Default::default(),
 5274                                    scroll_handle: UniformListScrollHandle::default(),
 5275                                    deployed_from_indicator,
 5276                                }));
 5277                            if spawn_straight_away {
 5278                                if let Some(task) = editor.confirm_code_action(
 5279                                    &ConfirmCodeAction { item_ix: Some(0) },
 5280                                    window,
 5281                                    cx,
 5282                                ) {
 5283                                    cx.notify();
 5284                                    return task;
 5285                                }
 5286                            }
 5287                            cx.notify();
 5288                            Task::ready(Ok(()))
 5289                        }) {
 5290                            task.await
 5291                        } else {
 5292                            Ok(())
 5293                        }
 5294                    }))
 5295                } else {
 5296                    Some(Task::ready(Ok(())))
 5297                }
 5298            })?;
 5299            if let Some(task) = spawned_test_task {
 5300                task.await?;
 5301            }
 5302
 5303            Ok::<_, anyhow::Error>(())
 5304        })
 5305        .detach_and_log_err(cx);
 5306    }
 5307
 5308    pub fn confirm_code_action(
 5309        &mut self,
 5310        action: &ConfirmCodeAction,
 5311        window: &mut Window,
 5312        cx: &mut Context<Self>,
 5313    ) -> Option<Task<Result<()>>> {
 5314        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5315
 5316        let actions_menu =
 5317            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5318                menu
 5319            } else {
 5320                return None;
 5321            };
 5322
 5323        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5324        let action = actions_menu.actions.get(action_ix)?;
 5325        let title = action.label();
 5326        let buffer = actions_menu.buffer;
 5327        let workspace = self.workspace()?;
 5328
 5329        match action {
 5330            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5331                workspace.update(cx, |workspace, cx| {
 5332                    workspace.schedule_resolved_task(
 5333                        task_source_kind,
 5334                        resolved_task,
 5335                        false,
 5336                        window,
 5337                        cx,
 5338                    );
 5339
 5340                    Some(Task::ready(Ok(())))
 5341                })
 5342            }
 5343            CodeActionsItem::CodeAction {
 5344                excerpt_id,
 5345                action,
 5346                provider,
 5347            } => {
 5348                let apply_code_action =
 5349                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5350                let workspace = workspace.downgrade();
 5351                Some(cx.spawn_in(window, async move |editor, cx| {
 5352                    let project_transaction = apply_code_action.await?;
 5353                    Self::open_project_transaction(
 5354                        &editor,
 5355                        workspace,
 5356                        project_transaction,
 5357                        title,
 5358                        cx,
 5359                    )
 5360                    .await
 5361                }))
 5362            }
 5363            CodeActionsItem::DebugScenario(scenario) => {
 5364                let context = actions_menu.actions.context.clone();
 5365
 5366                workspace.update(cx, |workspace, cx| {
 5367                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5368                });
 5369                Some(Task::ready(Ok(())))
 5370            }
 5371        }
 5372    }
 5373
 5374    pub async fn open_project_transaction(
 5375        this: &WeakEntity<Editor>,
 5376        workspace: WeakEntity<Workspace>,
 5377        transaction: ProjectTransaction,
 5378        title: String,
 5379        cx: &mut AsyncWindowContext,
 5380    ) -> Result<()> {
 5381        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5382        cx.update(|_, cx| {
 5383            entries.sort_unstable_by_key(|(buffer, _)| {
 5384                buffer.read(cx).file().map(|f| f.path().clone())
 5385            });
 5386        })?;
 5387
 5388        // If the project transaction's edits are all contained within this editor, then
 5389        // avoid opening a new editor to display them.
 5390
 5391        if let Some((buffer, transaction)) = entries.first() {
 5392            if entries.len() == 1 {
 5393                let excerpt = this.update(cx, |editor, cx| {
 5394                    editor
 5395                        .buffer()
 5396                        .read(cx)
 5397                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5398                })?;
 5399                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5400                    if excerpted_buffer == *buffer {
 5401                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5402                            let excerpt_range = excerpt_range.to_offset(buffer);
 5403                            buffer
 5404                                .edited_ranges_for_transaction::<usize>(transaction)
 5405                                .all(|range| {
 5406                                    excerpt_range.start <= range.start
 5407                                        && excerpt_range.end >= range.end
 5408                                })
 5409                        })?;
 5410
 5411                        if all_edits_within_excerpt {
 5412                            return Ok(());
 5413                        }
 5414                    }
 5415                }
 5416            }
 5417        } else {
 5418            return Ok(());
 5419        }
 5420
 5421        let mut ranges_to_highlight = Vec::new();
 5422        let excerpt_buffer = cx.new(|cx| {
 5423            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5424            for (buffer_handle, transaction) in &entries {
 5425                let edited_ranges = buffer_handle
 5426                    .read(cx)
 5427                    .edited_ranges_for_transaction::<Point>(transaction)
 5428                    .collect::<Vec<_>>();
 5429                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5430                    PathKey::for_buffer(buffer_handle, cx),
 5431                    buffer_handle.clone(),
 5432                    edited_ranges,
 5433                    DEFAULT_MULTIBUFFER_CONTEXT,
 5434                    cx,
 5435                );
 5436
 5437                ranges_to_highlight.extend(ranges);
 5438            }
 5439            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5440            multibuffer
 5441        })?;
 5442
 5443        workspace.update_in(cx, |workspace, window, cx| {
 5444            let project = workspace.project().clone();
 5445            let editor =
 5446                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5447            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5448            editor.update(cx, |editor, cx| {
 5449                editor.highlight_background::<Self>(
 5450                    &ranges_to_highlight,
 5451                    |theme| theme.editor_highlighted_line_background,
 5452                    cx,
 5453                );
 5454            });
 5455        })?;
 5456
 5457        Ok(())
 5458    }
 5459
 5460    pub fn clear_code_action_providers(&mut self) {
 5461        self.code_action_providers.clear();
 5462        self.available_code_actions.take();
 5463    }
 5464
 5465    pub fn add_code_action_provider(
 5466        &mut self,
 5467        provider: Rc<dyn CodeActionProvider>,
 5468        window: &mut Window,
 5469        cx: &mut Context<Self>,
 5470    ) {
 5471        if self
 5472            .code_action_providers
 5473            .iter()
 5474            .any(|existing_provider| existing_provider.id() == provider.id())
 5475        {
 5476            return;
 5477        }
 5478
 5479        self.code_action_providers.push(provider);
 5480        self.refresh_code_actions(window, cx);
 5481    }
 5482
 5483    pub fn remove_code_action_provider(
 5484        &mut self,
 5485        id: Arc<str>,
 5486        window: &mut Window,
 5487        cx: &mut Context<Self>,
 5488    ) {
 5489        self.code_action_providers
 5490            .retain(|provider| provider.id() != id);
 5491        self.refresh_code_actions(window, cx);
 5492    }
 5493
 5494    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5495        let newest_selection = self.selections.newest_anchor().clone();
 5496        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5497        let buffer = self.buffer.read(cx);
 5498        if newest_selection.head().diff_base_anchor.is_some() {
 5499            return None;
 5500        }
 5501        let (start_buffer, start) =
 5502            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5503        let (end_buffer, end) =
 5504            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5505        if start_buffer != end_buffer {
 5506            return None;
 5507        }
 5508
 5509        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5510            cx.background_executor()
 5511                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5512                .await;
 5513
 5514            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5515                let providers = this.code_action_providers.clone();
 5516                let tasks = this
 5517                    .code_action_providers
 5518                    .iter()
 5519                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5520                    .collect::<Vec<_>>();
 5521                (providers, tasks)
 5522            })?;
 5523
 5524            let mut actions = Vec::new();
 5525            for (provider, provider_actions) in
 5526                providers.into_iter().zip(future::join_all(tasks).await)
 5527            {
 5528                if let Some(provider_actions) = provider_actions.log_err() {
 5529                    actions.extend(provider_actions.into_iter().map(|action| {
 5530                        AvailableCodeAction {
 5531                            excerpt_id: newest_selection.start.excerpt_id,
 5532                            action,
 5533                            provider: provider.clone(),
 5534                        }
 5535                    }));
 5536                }
 5537            }
 5538
 5539            this.update(cx, |this, cx| {
 5540                this.available_code_actions = if actions.is_empty() {
 5541                    None
 5542                } else {
 5543                    Some((
 5544                        Location {
 5545                            buffer: start_buffer,
 5546                            range: start..end,
 5547                        },
 5548                        actions.into(),
 5549                    ))
 5550                };
 5551                cx.notify();
 5552            })
 5553        }));
 5554        None
 5555    }
 5556
 5557    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5558        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5559            self.show_git_blame_inline = false;
 5560
 5561            self.show_git_blame_inline_delay_task =
 5562                Some(cx.spawn_in(window, async move |this, cx| {
 5563                    cx.background_executor().timer(delay).await;
 5564
 5565                    this.update(cx, |this, cx| {
 5566                        this.show_git_blame_inline = true;
 5567                        cx.notify();
 5568                    })
 5569                    .log_err();
 5570                }));
 5571        }
 5572    }
 5573
 5574    fn show_blame_popover(
 5575        &mut self,
 5576        blame_entry: &BlameEntry,
 5577        position: gpui::Point<Pixels>,
 5578        cx: &mut Context<Self>,
 5579    ) {
 5580        if let Some(state) = &mut self.inline_blame_popover {
 5581            state.hide_task.take();
 5582            cx.notify();
 5583        } else {
 5584            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5585            let show_task = cx.spawn(async move |editor, cx| {
 5586                cx.background_executor()
 5587                    .timer(std::time::Duration::from_millis(delay))
 5588                    .await;
 5589                editor
 5590                    .update(cx, |editor, cx| {
 5591                        if let Some(state) = &mut editor.inline_blame_popover {
 5592                            state.show_task = None;
 5593                            cx.notify();
 5594                        }
 5595                    })
 5596                    .ok();
 5597            });
 5598            let Some(blame) = self.blame.as_ref() else {
 5599                return;
 5600            };
 5601            let blame = blame.read(cx);
 5602            let details = blame.details_for_entry(&blame_entry);
 5603            let markdown = cx.new(|cx| {
 5604                Markdown::new(
 5605                    details
 5606                        .as_ref()
 5607                        .map(|message| message.message.clone())
 5608                        .unwrap_or_default(),
 5609                    None,
 5610                    None,
 5611                    cx,
 5612                )
 5613            });
 5614            self.inline_blame_popover = Some(InlineBlamePopover {
 5615                position,
 5616                show_task: Some(show_task),
 5617                hide_task: None,
 5618                popover_bounds: None,
 5619                popover_state: InlineBlamePopoverState {
 5620                    scroll_handle: ScrollHandle::new(),
 5621                    commit_message: details,
 5622                    markdown,
 5623                },
 5624            });
 5625        }
 5626    }
 5627
 5628    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5629        if let Some(state) = &mut self.inline_blame_popover {
 5630            if state.show_task.is_some() {
 5631                self.inline_blame_popover.take();
 5632                cx.notify();
 5633            } else {
 5634                let hide_task = cx.spawn(async move |editor, cx| {
 5635                    cx.background_executor()
 5636                        .timer(std::time::Duration::from_millis(100))
 5637                        .await;
 5638                    editor
 5639                        .update(cx, |editor, cx| {
 5640                            editor.inline_blame_popover.take();
 5641                            cx.notify();
 5642                        })
 5643                        .ok();
 5644                });
 5645                state.hide_task = Some(hide_task);
 5646            }
 5647        }
 5648    }
 5649
 5650    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5651        if self.pending_rename.is_some() {
 5652            return None;
 5653        }
 5654
 5655        let provider = self.semantics_provider.clone()?;
 5656        let buffer = self.buffer.read(cx);
 5657        let newest_selection = self.selections.newest_anchor().clone();
 5658        let cursor_position = newest_selection.head();
 5659        let (cursor_buffer, cursor_buffer_position) =
 5660            buffer.text_anchor_for_position(cursor_position, cx)?;
 5661        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5662        if cursor_buffer != tail_buffer {
 5663            return None;
 5664        }
 5665        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5666        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5667            cx.background_executor()
 5668                .timer(Duration::from_millis(debounce))
 5669                .await;
 5670
 5671            let highlights = if let Some(highlights) = cx
 5672                .update(|cx| {
 5673                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5674                })
 5675                .ok()
 5676                .flatten()
 5677            {
 5678                highlights.await.log_err()
 5679            } else {
 5680                None
 5681            };
 5682
 5683            if let Some(highlights) = highlights {
 5684                this.update(cx, |this, cx| {
 5685                    if this.pending_rename.is_some() {
 5686                        return;
 5687                    }
 5688
 5689                    let buffer_id = cursor_position.buffer_id;
 5690                    let buffer = this.buffer.read(cx);
 5691                    if !buffer
 5692                        .text_anchor_for_position(cursor_position, cx)
 5693                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5694                    {
 5695                        return;
 5696                    }
 5697
 5698                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5699                    let mut write_ranges = Vec::new();
 5700                    let mut read_ranges = Vec::new();
 5701                    for highlight in highlights {
 5702                        for (excerpt_id, excerpt_range) in
 5703                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5704                        {
 5705                            let start = highlight
 5706                                .range
 5707                                .start
 5708                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5709                            let end = highlight
 5710                                .range
 5711                                .end
 5712                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5713                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5714                                continue;
 5715                            }
 5716
 5717                            let range = Anchor {
 5718                                buffer_id,
 5719                                excerpt_id,
 5720                                text_anchor: start,
 5721                                diff_base_anchor: None,
 5722                            }..Anchor {
 5723                                buffer_id,
 5724                                excerpt_id,
 5725                                text_anchor: end,
 5726                                diff_base_anchor: None,
 5727                            };
 5728                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5729                                write_ranges.push(range);
 5730                            } else {
 5731                                read_ranges.push(range);
 5732                            }
 5733                        }
 5734                    }
 5735
 5736                    this.highlight_background::<DocumentHighlightRead>(
 5737                        &read_ranges,
 5738                        |theme| theme.editor_document_highlight_read_background,
 5739                        cx,
 5740                    );
 5741                    this.highlight_background::<DocumentHighlightWrite>(
 5742                        &write_ranges,
 5743                        |theme| theme.editor_document_highlight_write_background,
 5744                        cx,
 5745                    );
 5746                    cx.notify();
 5747                })
 5748                .log_err();
 5749            }
 5750        }));
 5751        None
 5752    }
 5753
 5754    fn prepare_highlight_query_from_selection(
 5755        &mut self,
 5756        cx: &mut Context<Editor>,
 5757    ) -> Option<(String, Range<Anchor>)> {
 5758        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5759            return None;
 5760        }
 5761        if !EditorSettings::get_global(cx).selection_highlight {
 5762            return None;
 5763        }
 5764        if self.selections.count() != 1 || self.selections.line_mode {
 5765            return None;
 5766        }
 5767        let selection = self.selections.newest::<Point>(cx);
 5768        if selection.is_empty() || selection.start.row != selection.end.row {
 5769            return None;
 5770        }
 5771        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5772        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5773        let query = multi_buffer_snapshot
 5774            .text_for_range(selection_anchor_range.clone())
 5775            .collect::<String>();
 5776        if query.trim().is_empty() {
 5777            return None;
 5778        }
 5779        Some((query, selection_anchor_range))
 5780    }
 5781
 5782    fn update_selection_occurrence_highlights(
 5783        &mut self,
 5784        query_text: String,
 5785        query_range: Range<Anchor>,
 5786        multi_buffer_range_to_query: Range<Point>,
 5787        use_debounce: bool,
 5788        window: &mut Window,
 5789        cx: &mut Context<Editor>,
 5790    ) -> Task<()> {
 5791        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5792        cx.spawn_in(window, async move |editor, cx| {
 5793            if use_debounce {
 5794                cx.background_executor()
 5795                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5796                    .await;
 5797            }
 5798            let match_task = cx.background_spawn(async move {
 5799                let buffer_ranges = multi_buffer_snapshot
 5800                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5801                    .into_iter()
 5802                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5803                let mut match_ranges = Vec::new();
 5804                let Ok(regex) = project::search::SearchQuery::text(
 5805                    query_text.clone(),
 5806                    false,
 5807                    false,
 5808                    false,
 5809                    Default::default(),
 5810                    Default::default(),
 5811                    false,
 5812                    None,
 5813                ) else {
 5814                    return Vec::default();
 5815                };
 5816                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5817                    match_ranges.extend(
 5818                        regex
 5819                            .search(&buffer_snapshot, Some(search_range.clone()))
 5820                            .await
 5821                            .into_iter()
 5822                            .filter_map(|match_range| {
 5823                                let match_start = buffer_snapshot
 5824                                    .anchor_after(search_range.start + match_range.start);
 5825                                let match_end = buffer_snapshot
 5826                                    .anchor_before(search_range.start + match_range.end);
 5827                                let match_anchor_range = Anchor::range_in_buffer(
 5828                                    excerpt_id,
 5829                                    buffer_snapshot.remote_id(),
 5830                                    match_start..match_end,
 5831                                );
 5832                                (match_anchor_range != query_range).then_some(match_anchor_range)
 5833                            }),
 5834                    );
 5835                }
 5836                match_ranges
 5837            });
 5838            let match_ranges = match_task.await;
 5839            editor
 5840                .update_in(cx, |editor, _, cx| {
 5841                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5842                    if !match_ranges.is_empty() {
 5843                        editor.highlight_background::<SelectedTextHighlight>(
 5844                            &match_ranges,
 5845                            |theme| theme.editor_document_highlight_bracket_background,
 5846                            cx,
 5847                        )
 5848                    }
 5849                })
 5850                .log_err();
 5851        })
 5852    }
 5853
 5854    fn refresh_selected_text_highlights(
 5855        &mut self,
 5856        on_buffer_edit: bool,
 5857        window: &mut Window,
 5858        cx: &mut Context<Editor>,
 5859    ) {
 5860        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5861        else {
 5862            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5863            self.quick_selection_highlight_task.take();
 5864            self.debounced_selection_highlight_task.take();
 5865            return;
 5866        };
 5867        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5868        if on_buffer_edit
 5869            || self
 5870                .quick_selection_highlight_task
 5871                .as_ref()
 5872                .map_or(true, |(prev_anchor_range, _)| {
 5873                    prev_anchor_range != &query_range
 5874                })
 5875        {
 5876            let multi_buffer_visible_start = self
 5877                .scroll_manager
 5878                .anchor()
 5879                .anchor
 5880                .to_point(&multi_buffer_snapshot);
 5881            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5882                multi_buffer_visible_start
 5883                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5884                Bias::Left,
 5885            );
 5886            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5887            self.quick_selection_highlight_task = Some((
 5888                query_range.clone(),
 5889                self.update_selection_occurrence_highlights(
 5890                    query_text.clone(),
 5891                    query_range.clone(),
 5892                    multi_buffer_visible_range,
 5893                    false,
 5894                    window,
 5895                    cx,
 5896                ),
 5897            ));
 5898        }
 5899        if on_buffer_edit
 5900            || self
 5901                .debounced_selection_highlight_task
 5902                .as_ref()
 5903                .map_or(true, |(prev_anchor_range, _)| {
 5904                    prev_anchor_range != &query_range
 5905                })
 5906        {
 5907            let multi_buffer_start = multi_buffer_snapshot
 5908                .anchor_before(0)
 5909                .to_point(&multi_buffer_snapshot);
 5910            let multi_buffer_end = multi_buffer_snapshot
 5911                .anchor_after(multi_buffer_snapshot.len())
 5912                .to_point(&multi_buffer_snapshot);
 5913            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5914            self.debounced_selection_highlight_task = Some((
 5915                query_range.clone(),
 5916                self.update_selection_occurrence_highlights(
 5917                    query_text,
 5918                    query_range,
 5919                    multi_buffer_full_range,
 5920                    true,
 5921                    window,
 5922                    cx,
 5923                ),
 5924            ));
 5925        }
 5926    }
 5927
 5928    pub fn refresh_inline_completion(
 5929        &mut self,
 5930        debounce: bool,
 5931        user_requested: bool,
 5932        window: &mut Window,
 5933        cx: &mut Context<Self>,
 5934    ) -> Option<()> {
 5935        let provider = self.edit_prediction_provider()?;
 5936        let cursor = self.selections.newest_anchor().head();
 5937        let (buffer, cursor_buffer_position) =
 5938            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5939
 5940        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5941            self.discard_inline_completion(false, cx);
 5942            return None;
 5943        }
 5944
 5945        if !user_requested
 5946            && (!self.should_show_edit_predictions()
 5947                || !self.is_focused(window)
 5948                || buffer.read(cx).is_empty())
 5949        {
 5950            self.discard_inline_completion(false, cx);
 5951            return None;
 5952        }
 5953
 5954        self.update_visible_inline_completion(window, cx);
 5955        provider.refresh(
 5956            self.project.clone(),
 5957            buffer,
 5958            cursor_buffer_position,
 5959            debounce,
 5960            cx,
 5961        );
 5962        Some(())
 5963    }
 5964
 5965    fn show_edit_predictions_in_menu(&self) -> bool {
 5966        match self.edit_prediction_settings {
 5967            EditPredictionSettings::Disabled => false,
 5968            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5969        }
 5970    }
 5971
 5972    pub fn edit_predictions_enabled(&self) -> bool {
 5973        match self.edit_prediction_settings {
 5974            EditPredictionSettings::Disabled => false,
 5975            EditPredictionSettings::Enabled { .. } => true,
 5976        }
 5977    }
 5978
 5979    fn edit_prediction_requires_modifier(&self) -> bool {
 5980        match self.edit_prediction_settings {
 5981            EditPredictionSettings::Disabled => false,
 5982            EditPredictionSettings::Enabled {
 5983                preview_requires_modifier,
 5984                ..
 5985            } => preview_requires_modifier,
 5986        }
 5987    }
 5988
 5989    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5990        if self.edit_prediction_provider.is_none() {
 5991            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5992        } else {
 5993            let selection = self.selections.newest_anchor();
 5994            let cursor = selection.head();
 5995
 5996            if let Some((buffer, cursor_buffer_position)) =
 5997                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5998            {
 5999                self.edit_prediction_settings =
 6000                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6001            }
 6002        }
 6003    }
 6004
 6005    fn edit_prediction_settings_at_position(
 6006        &self,
 6007        buffer: &Entity<Buffer>,
 6008        buffer_position: language::Anchor,
 6009        cx: &App,
 6010    ) -> EditPredictionSettings {
 6011        if !self.mode.is_full()
 6012            || !self.show_inline_completions_override.unwrap_or(true)
 6013            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 6014        {
 6015            return EditPredictionSettings::Disabled;
 6016        }
 6017
 6018        let buffer = buffer.read(cx);
 6019
 6020        let file = buffer.file();
 6021
 6022        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 6023            return EditPredictionSettings::Disabled;
 6024        };
 6025
 6026        let by_provider = matches!(
 6027            self.menu_inline_completions_policy,
 6028            MenuInlineCompletionsPolicy::ByProvider
 6029        );
 6030
 6031        let show_in_menu = by_provider
 6032            && self
 6033                .edit_prediction_provider
 6034                .as_ref()
 6035                .map_or(false, |provider| {
 6036                    provider.provider.show_completions_in_menu()
 6037                });
 6038
 6039        let preview_requires_modifier =
 6040            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6041
 6042        EditPredictionSettings::Enabled {
 6043            show_in_menu,
 6044            preview_requires_modifier,
 6045        }
 6046    }
 6047
 6048    fn should_show_edit_predictions(&self) -> bool {
 6049        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6050    }
 6051
 6052    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6053        matches!(
 6054            self.edit_prediction_preview,
 6055            EditPredictionPreview::Active { .. }
 6056        )
 6057    }
 6058
 6059    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6060        let cursor = self.selections.newest_anchor().head();
 6061        if let Some((buffer, cursor_position)) =
 6062            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6063        {
 6064            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6065        } else {
 6066            false
 6067        }
 6068    }
 6069
 6070    fn edit_predictions_enabled_in_buffer(
 6071        &self,
 6072        buffer: &Entity<Buffer>,
 6073        buffer_position: language::Anchor,
 6074        cx: &App,
 6075    ) -> bool {
 6076        maybe!({
 6077            if self.read_only(cx) {
 6078                return Some(false);
 6079            }
 6080            let provider = self.edit_prediction_provider()?;
 6081            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6082                return Some(false);
 6083            }
 6084            let buffer = buffer.read(cx);
 6085            let Some(file) = buffer.file() else {
 6086                return Some(true);
 6087            };
 6088            let settings = all_language_settings(Some(file), cx);
 6089            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6090        })
 6091        .unwrap_or(false)
 6092    }
 6093
 6094    fn cycle_inline_completion(
 6095        &mut self,
 6096        direction: Direction,
 6097        window: &mut Window,
 6098        cx: &mut Context<Self>,
 6099    ) -> Option<()> {
 6100        let provider = self.edit_prediction_provider()?;
 6101        let cursor = self.selections.newest_anchor().head();
 6102        let (buffer, cursor_buffer_position) =
 6103            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6104        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6105            return None;
 6106        }
 6107
 6108        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6109        self.update_visible_inline_completion(window, cx);
 6110
 6111        Some(())
 6112    }
 6113
 6114    pub fn show_inline_completion(
 6115        &mut self,
 6116        _: &ShowEditPrediction,
 6117        window: &mut Window,
 6118        cx: &mut Context<Self>,
 6119    ) {
 6120        if !self.has_active_inline_completion() {
 6121            self.refresh_inline_completion(false, true, window, cx);
 6122            return;
 6123        }
 6124
 6125        self.update_visible_inline_completion(window, cx);
 6126    }
 6127
 6128    pub fn display_cursor_names(
 6129        &mut self,
 6130        _: &DisplayCursorNames,
 6131        window: &mut Window,
 6132        cx: &mut Context<Self>,
 6133    ) {
 6134        self.show_cursor_names(window, cx);
 6135    }
 6136
 6137    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6138        self.show_cursor_names = true;
 6139        cx.notify();
 6140        cx.spawn_in(window, async move |this, cx| {
 6141            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6142            this.update(cx, |this, cx| {
 6143                this.show_cursor_names = false;
 6144                cx.notify()
 6145            })
 6146            .ok()
 6147        })
 6148        .detach();
 6149    }
 6150
 6151    pub fn next_edit_prediction(
 6152        &mut self,
 6153        _: &NextEditPrediction,
 6154        window: &mut Window,
 6155        cx: &mut Context<Self>,
 6156    ) {
 6157        if self.has_active_inline_completion() {
 6158            self.cycle_inline_completion(Direction::Next, window, cx);
 6159        } else {
 6160            let is_copilot_disabled = self
 6161                .refresh_inline_completion(false, true, window, cx)
 6162                .is_none();
 6163            if is_copilot_disabled {
 6164                cx.propagate();
 6165            }
 6166        }
 6167    }
 6168
 6169    pub fn previous_edit_prediction(
 6170        &mut self,
 6171        _: &PreviousEditPrediction,
 6172        window: &mut Window,
 6173        cx: &mut Context<Self>,
 6174    ) {
 6175        if self.has_active_inline_completion() {
 6176            self.cycle_inline_completion(Direction::Prev, window, cx);
 6177        } else {
 6178            let is_copilot_disabled = self
 6179                .refresh_inline_completion(false, true, window, cx)
 6180                .is_none();
 6181            if is_copilot_disabled {
 6182                cx.propagate();
 6183            }
 6184        }
 6185    }
 6186
 6187    pub fn accept_edit_prediction(
 6188        &mut self,
 6189        _: &AcceptEditPrediction,
 6190        window: &mut Window,
 6191        cx: &mut Context<Self>,
 6192    ) {
 6193        if self.show_edit_predictions_in_menu() {
 6194            self.hide_context_menu(window, cx);
 6195        }
 6196
 6197        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6198            return;
 6199        };
 6200
 6201        self.report_inline_completion_event(
 6202            active_inline_completion.completion_id.clone(),
 6203            true,
 6204            cx,
 6205        );
 6206
 6207        match &active_inline_completion.completion {
 6208            InlineCompletion::Move { target, .. } => {
 6209                let target = *target;
 6210
 6211                if let Some(position_map) = &self.last_position_map {
 6212                    if position_map
 6213                        .visible_row_range
 6214                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6215                        || !self.edit_prediction_requires_modifier()
 6216                    {
 6217                        self.unfold_ranges(&[target..target], true, false, cx);
 6218                        // Note that this is also done in vim's handler of the Tab action.
 6219                        self.change_selections(
 6220                            Some(Autoscroll::newest()),
 6221                            window,
 6222                            cx,
 6223                            |selections| {
 6224                                selections.select_anchor_ranges([target..target]);
 6225                            },
 6226                        );
 6227                        self.clear_row_highlights::<EditPredictionPreview>();
 6228
 6229                        self.edit_prediction_preview
 6230                            .set_previous_scroll_position(None);
 6231                    } else {
 6232                        self.edit_prediction_preview
 6233                            .set_previous_scroll_position(Some(
 6234                                position_map.snapshot.scroll_anchor,
 6235                            ));
 6236
 6237                        self.highlight_rows::<EditPredictionPreview>(
 6238                            target..target,
 6239                            cx.theme().colors().editor_highlighted_line_background,
 6240                            RowHighlightOptions {
 6241                                autoscroll: true,
 6242                                ..Default::default()
 6243                            },
 6244                            cx,
 6245                        );
 6246                        self.request_autoscroll(Autoscroll::fit(), cx);
 6247                    }
 6248                }
 6249            }
 6250            InlineCompletion::Edit { edits, .. } => {
 6251                if let Some(provider) = self.edit_prediction_provider() {
 6252                    provider.accept(cx);
 6253                }
 6254
 6255                let snapshot = self.buffer.read(cx).snapshot(cx);
 6256                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6257
 6258                self.buffer.update(cx, |buffer, cx| {
 6259                    buffer.edit(edits.iter().cloned(), None, cx)
 6260                });
 6261
 6262                self.change_selections(None, window, cx, |s| {
 6263                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6264                });
 6265
 6266                self.update_visible_inline_completion(window, cx);
 6267                if self.active_inline_completion.is_none() {
 6268                    self.refresh_inline_completion(true, true, window, cx);
 6269                }
 6270
 6271                cx.notify();
 6272            }
 6273        }
 6274
 6275        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6276    }
 6277
 6278    pub fn accept_partial_inline_completion(
 6279        &mut self,
 6280        _: &AcceptPartialEditPrediction,
 6281        window: &mut Window,
 6282        cx: &mut Context<Self>,
 6283    ) {
 6284        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6285            return;
 6286        };
 6287        if self.selections.count() != 1 {
 6288            return;
 6289        }
 6290
 6291        self.report_inline_completion_event(
 6292            active_inline_completion.completion_id.clone(),
 6293            true,
 6294            cx,
 6295        );
 6296
 6297        match &active_inline_completion.completion {
 6298            InlineCompletion::Move { target, .. } => {
 6299                let target = *target;
 6300                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6301                    selections.select_anchor_ranges([target..target]);
 6302                });
 6303            }
 6304            InlineCompletion::Edit { edits, .. } => {
 6305                // Find an insertion that starts at the cursor position.
 6306                let snapshot = self.buffer.read(cx).snapshot(cx);
 6307                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6308                let insertion = edits.iter().find_map(|(range, text)| {
 6309                    let range = range.to_offset(&snapshot);
 6310                    if range.is_empty() && range.start == cursor_offset {
 6311                        Some(text)
 6312                    } else {
 6313                        None
 6314                    }
 6315                });
 6316
 6317                if let Some(text) = insertion {
 6318                    let mut partial_completion = text
 6319                        .chars()
 6320                        .by_ref()
 6321                        .take_while(|c| c.is_alphabetic())
 6322                        .collect::<String>();
 6323                    if partial_completion.is_empty() {
 6324                        partial_completion = text
 6325                            .chars()
 6326                            .by_ref()
 6327                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6328                            .collect::<String>();
 6329                    }
 6330
 6331                    cx.emit(EditorEvent::InputHandled {
 6332                        utf16_range_to_replace: None,
 6333                        text: partial_completion.clone().into(),
 6334                    });
 6335
 6336                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6337
 6338                    self.refresh_inline_completion(true, true, window, cx);
 6339                    cx.notify();
 6340                } else {
 6341                    self.accept_edit_prediction(&Default::default(), window, cx);
 6342                }
 6343            }
 6344        }
 6345    }
 6346
 6347    fn discard_inline_completion(
 6348        &mut self,
 6349        should_report_inline_completion_event: bool,
 6350        cx: &mut Context<Self>,
 6351    ) -> bool {
 6352        if should_report_inline_completion_event {
 6353            let completion_id = self
 6354                .active_inline_completion
 6355                .as_ref()
 6356                .and_then(|active_completion| active_completion.completion_id.clone());
 6357
 6358            self.report_inline_completion_event(completion_id, false, cx);
 6359        }
 6360
 6361        if let Some(provider) = self.edit_prediction_provider() {
 6362            provider.discard(cx);
 6363        }
 6364
 6365        self.take_active_inline_completion(cx)
 6366    }
 6367
 6368    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6369        let Some(provider) = self.edit_prediction_provider() else {
 6370            return;
 6371        };
 6372
 6373        let Some((_, buffer, _)) = self
 6374            .buffer
 6375            .read(cx)
 6376            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6377        else {
 6378            return;
 6379        };
 6380
 6381        let extension = buffer
 6382            .read(cx)
 6383            .file()
 6384            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6385
 6386        let event_type = match accepted {
 6387            true => "Edit Prediction Accepted",
 6388            false => "Edit Prediction Discarded",
 6389        };
 6390        telemetry::event!(
 6391            event_type,
 6392            provider = provider.name(),
 6393            prediction_id = id,
 6394            suggestion_accepted = accepted,
 6395            file_extension = extension,
 6396        );
 6397    }
 6398
 6399    pub fn has_active_inline_completion(&self) -> bool {
 6400        self.active_inline_completion.is_some()
 6401    }
 6402
 6403    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6404        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6405            return false;
 6406        };
 6407
 6408        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6409        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6410        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6411        true
 6412    }
 6413
 6414    /// Returns true when we're displaying the edit prediction popover below the cursor
 6415    /// like we are not previewing and the LSP autocomplete menu is visible
 6416    /// or we are in `when_holding_modifier` mode.
 6417    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6418        if self.edit_prediction_preview_is_active()
 6419            || !self.show_edit_predictions_in_menu()
 6420            || !self.edit_predictions_enabled()
 6421        {
 6422            return false;
 6423        }
 6424
 6425        if self.has_visible_completions_menu() {
 6426            return true;
 6427        }
 6428
 6429        has_completion && self.edit_prediction_requires_modifier()
 6430    }
 6431
 6432    fn handle_modifiers_changed(
 6433        &mut self,
 6434        modifiers: Modifiers,
 6435        position_map: &PositionMap,
 6436        window: &mut Window,
 6437        cx: &mut Context<Self>,
 6438    ) {
 6439        if self.show_edit_predictions_in_menu() {
 6440            self.update_edit_prediction_preview(&modifiers, window, cx);
 6441        }
 6442
 6443        self.update_selection_mode(&modifiers, position_map, window, cx);
 6444
 6445        let mouse_position = window.mouse_position();
 6446        if !position_map.text_hitbox.is_hovered(window) {
 6447            return;
 6448        }
 6449
 6450        self.update_hovered_link(
 6451            position_map.point_for_position(mouse_position),
 6452            &position_map.snapshot,
 6453            modifiers,
 6454            window,
 6455            cx,
 6456        )
 6457    }
 6458
 6459    fn update_selection_mode(
 6460        &mut self,
 6461        modifiers: &Modifiers,
 6462        position_map: &PositionMap,
 6463        window: &mut Window,
 6464        cx: &mut Context<Self>,
 6465    ) {
 6466        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6467            return;
 6468        }
 6469
 6470        let mouse_position = window.mouse_position();
 6471        let point_for_position = position_map.point_for_position(mouse_position);
 6472        let position = point_for_position.previous_valid;
 6473
 6474        self.select(
 6475            SelectPhase::BeginColumnar {
 6476                position,
 6477                reset: false,
 6478                goal_column: point_for_position.exact_unclipped.column(),
 6479            },
 6480            window,
 6481            cx,
 6482        );
 6483    }
 6484
 6485    fn update_edit_prediction_preview(
 6486        &mut self,
 6487        modifiers: &Modifiers,
 6488        window: &mut Window,
 6489        cx: &mut Context<Self>,
 6490    ) {
 6491        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6492        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6493            return;
 6494        };
 6495
 6496        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6497            if matches!(
 6498                self.edit_prediction_preview,
 6499                EditPredictionPreview::Inactive { .. }
 6500            ) {
 6501                self.edit_prediction_preview = EditPredictionPreview::Active {
 6502                    previous_scroll_position: None,
 6503                    since: Instant::now(),
 6504                };
 6505
 6506                self.update_visible_inline_completion(window, cx);
 6507                cx.notify();
 6508            }
 6509        } else if let EditPredictionPreview::Active {
 6510            previous_scroll_position,
 6511            since,
 6512        } = self.edit_prediction_preview
 6513        {
 6514            if let (Some(previous_scroll_position), Some(position_map)) =
 6515                (previous_scroll_position, self.last_position_map.as_ref())
 6516            {
 6517                self.set_scroll_position(
 6518                    previous_scroll_position
 6519                        .scroll_position(&position_map.snapshot.display_snapshot),
 6520                    window,
 6521                    cx,
 6522                );
 6523            }
 6524
 6525            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6526                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6527            };
 6528            self.clear_row_highlights::<EditPredictionPreview>();
 6529            self.update_visible_inline_completion(window, cx);
 6530            cx.notify();
 6531        }
 6532    }
 6533
 6534    fn update_visible_inline_completion(
 6535        &mut self,
 6536        _window: &mut Window,
 6537        cx: &mut Context<Self>,
 6538    ) -> Option<()> {
 6539        let selection = self.selections.newest_anchor();
 6540        let cursor = selection.head();
 6541        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6542        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6543        let excerpt_id = cursor.excerpt_id;
 6544
 6545        let show_in_menu = self.show_edit_predictions_in_menu();
 6546        let completions_menu_has_precedence = !show_in_menu
 6547            && (self.context_menu.borrow().is_some()
 6548                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6549
 6550        if completions_menu_has_precedence
 6551            || !offset_selection.is_empty()
 6552            || self
 6553                .active_inline_completion
 6554                .as_ref()
 6555                .map_or(false, |completion| {
 6556                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6557                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6558                    !invalidation_range.contains(&offset_selection.head())
 6559                })
 6560        {
 6561            self.discard_inline_completion(false, cx);
 6562            return None;
 6563        }
 6564
 6565        self.take_active_inline_completion(cx);
 6566        let Some(provider) = self.edit_prediction_provider() else {
 6567            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6568            return None;
 6569        };
 6570
 6571        let (buffer, cursor_buffer_position) =
 6572            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6573
 6574        self.edit_prediction_settings =
 6575            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6576
 6577        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6578
 6579        if self.edit_prediction_indent_conflict {
 6580            let cursor_point = cursor.to_point(&multibuffer);
 6581
 6582            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6583
 6584            if let Some((_, indent)) = indents.iter().next() {
 6585                if indent.len == cursor_point.column {
 6586                    self.edit_prediction_indent_conflict = false;
 6587                }
 6588            }
 6589        }
 6590
 6591        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6592        let edits = inline_completion
 6593            .edits
 6594            .into_iter()
 6595            .flat_map(|(range, new_text)| {
 6596                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6597                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6598                Some((start..end, new_text))
 6599            })
 6600            .collect::<Vec<_>>();
 6601        if edits.is_empty() {
 6602            return None;
 6603        }
 6604
 6605        let first_edit_start = edits.first().unwrap().0.start;
 6606        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6607        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6608
 6609        let last_edit_end = edits.last().unwrap().0.end;
 6610        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6611        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6612
 6613        let cursor_row = cursor.to_point(&multibuffer).row;
 6614
 6615        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6616
 6617        let mut inlay_ids = Vec::new();
 6618        let invalidation_row_range;
 6619        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6620            Some(cursor_row..edit_end_row)
 6621        } else if cursor_row > edit_end_row {
 6622            Some(edit_start_row..cursor_row)
 6623        } else {
 6624            None
 6625        };
 6626        let is_move =
 6627            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6628        let completion = if is_move {
 6629            invalidation_row_range =
 6630                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6631            let target = first_edit_start;
 6632            InlineCompletion::Move { target, snapshot }
 6633        } else {
 6634            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6635                && !self.inline_completions_hidden_for_vim_mode;
 6636
 6637            if show_completions_in_buffer {
 6638                if edits
 6639                    .iter()
 6640                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6641                {
 6642                    let mut inlays = Vec::new();
 6643                    for (range, new_text) in &edits {
 6644                        let inlay = Inlay::inline_completion(
 6645                            post_inc(&mut self.next_inlay_id),
 6646                            range.start,
 6647                            new_text.as_str(),
 6648                        );
 6649                        inlay_ids.push(inlay.id);
 6650                        inlays.push(inlay);
 6651                    }
 6652
 6653                    self.splice_inlays(&[], inlays, cx);
 6654                } else {
 6655                    let background_color = cx.theme().status().deleted_background;
 6656                    self.highlight_text::<InlineCompletionHighlight>(
 6657                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6658                        HighlightStyle {
 6659                            background_color: Some(background_color),
 6660                            ..Default::default()
 6661                        },
 6662                        cx,
 6663                    );
 6664                }
 6665            }
 6666
 6667            invalidation_row_range = edit_start_row..edit_end_row;
 6668
 6669            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6670                if provider.show_tab_accept_marker() {
 6671                    EditDisplayMode::TabAccept
 6672                } else {
 6673                    EditDisplayMode::Inline
 6674                }
 6675            } else {
 6676                EditDisplayMode::DiffPopover
 6677            };
 6678
 6679            InlineCompletion::Edit {
 6680                edits,
 6681                edit_preview: inline_completion.edit_preview,
 6682                display_mode,
 6683                snapshot,
 6684            }
 6685        };
 6686
 6687        let invalidation_range = multibuffer
 6688            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6689            ..multibuffer.anchor_after(Point::new(
 6690                invalidation_row_range.end,
 6691                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6692            ));
 6693
 6694        self.stale_inline_completion_in_menu = None;
 6695        self.active_inline_completion = Some(InlineCompletionState {
 6696            inlay_ids,
 6697            completion,
 6698            completion_id: inline_completion.id,
 6699            invalidation_range,
 6700        });
 6701
 6702        cx.notify();
 6703
 6704        Some(())
 6705    }
 6706
 6707    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6708        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6709    }
 6710
 6711    fn clear_tasks(&mut self) {
 6712        self.tasks.clear()
 6713    }
 6714
 6715    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6716        if self.tasks.insert(key, value).is_some() {
 6717            // This case should hopefully be rare, but just in case...
 6718            log::error!(
 6719                "multiple different run targets found on a single line, only the last target will be rendered"
 6720            )
 6721        }
 6722    }
 6723
 6724    /// Get all display points of breakpoints that will be rendered within editor
 6725    ///
 6726    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6727    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6728    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6729    fn active_breakpoints(
 6730        &self,
 6731        range: Range<DisplayRow>,
 6732        window: &mut Window,
 6733        cx: &mut Context<Self>,
 6734    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6735        let mut breakpoint_display_points = HashMap::default();
 6736
 6737        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6738            return breakpoint_display_points;
 6739        };
 6740
 6741        let snapshot = self.snapshot(window, cx);
 6742
 6743        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6744        let Some(project) = self.project.as_ref() else {
 6745            return breakpoint_display_points;
 6746        };
 6747
 6748        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6749            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6750
 6751        for (buffer_snapshot, range, excerpt_id) in
 6752            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6753        {
 6754            let Some(buffer) = project.read_with(cx, |this, cx| {
 6755                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6756            }) else {
 6757                continue;
 6758            };
 6759            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6760                &buffer,
 6761                Some(
 6762                    buffer_snapshot.anchor_before(range.start)
 6763                        ..buffer_snapshot.anchor_after(range.end),
 6764                ),
 6765                buffer_snapshot,
 6766                cx,
 6767            );
 6768            for (anchor, breakpoint) in breakpoints {
 6769                let multi_buffer_anchor =
 6770                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6771                let position = multi_buffer_anchor
 6772                    .to_point(&multi_buffer_snapshot)
 6773                    .to_display_point(&snapshot);
 6774
 6775                breakpoint_display_points
 6776                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6777            }
 6778        }
 6779
 6780        breakpoint_display_points
 6781    }
 6782
 6783    fn breakpoint_context_menu(
 6784        &self,
 6785        anchor: Anchor,
 6786        window: &mut Window,
 6787        cx: &mut Context<Self>,
 6788    ) -> Entity<ui::ContextMenu> {
 6789        let weak_editor = cx.weak_entity();
 6790        let focus_handle = self.focus_handle(cx);
 6791
 6792        let row = self
 6793            .buffer
 6794            .read(cx)
 6795            .snapshot(cx)
 6796            .summary_for_anchor::<Point>(&anchor)
 6797            .row;
 6798
 6799        let breakpoint = self
 6800            .breakpoint_at_row(row, window, cx)
 6801            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6802
 6803        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6804            "Edit Log Breakpoint"
 6805        } else {
 6806            "Set Log Breakpoint"
 6807        };
 6808
 6809        let condition_breakpoint_msg = if breakpoint
 6810            .as_ref()
 6811            .is_some_and(|bp| bp.1.condition.is_some())
 6812        {
 6813            "Edit Condition Breakpoint"
 6814        } else {
 6815            "Set Condition Breakpoint"
 6816        };
 6817
 6818        let hit_condition_breakpoint_msg = if breakpoint
 6819            .as_ref()
 6820            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6821        {
 6822            "Edit Hit Condition Breakpoint"
 6823        } else {
 6824            "Set Hit Condition Breakpoint"
 6825        };
 6826
 6827        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6828            "Unset Breakpoint"
 6829        } else {
 6830            "Set Breakpoint"
 6831        };
 6832
 6833        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6834            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6835
 6836        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6837            BreakpointState::Enabled => Some("Disable"),
 6838            BreakpointState::Disabled => Some("Enable"),
 6839        });
 6840
 6841        let (anchor, breakpoint) =
 6842            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6843
 6844        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6845            menu.on_blur_subscription(Subscription::new(|| {}))
 6846                .context(focus_handle)
 6847                .when(run_to_cursor, |this| {
 6848                    let weak_editor = weak_editor.clone();
 6849                    this.entry("Run to cursor", None, move |window, cx| {
 6850                        weak_editor
 6851                            .update(cx, |editor, cx| {
 6852                                editor.change_selections(None, window, cx, |s| {
 6853                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6854                                });
 6855                            })
 6856                            .ok();
 6857
 6858                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6859                    })
 6860                    .separator()
 6861                })
 6862                .when_some(toggle_state_msg, |this, msg| {
 6863                    this.entry(msg, None, {
 6864                        let weak_editor = weak_editor.clone();
 6865                        let breakpoint = breakpoint.clone();
 6866                        move |_window, cx| {
 6867                            weak_editor
 6868                                .update(cx, |this, cx| {
 6869                                    this.edit_breakpoint_at_anchor(
 6870                                        anchor,
 6871                                        breakpoint.as_ref().clone(),
 6872                                        BreakpointEditAction::InvertState,
 6873                                        cx,
 6874                                    );
 6875                                })
 6876                                .log_err();
 6877                        }
 6878                    })
 6879                })
 6880                .entry(set_breakpoint_msg, None, {
 6881                    let weak_editor = weak_editor.clone();
 6882                    let breakpoint = breakpoint.clone();
 6883                    move |_window, cx| {
 6884                        weak_editor
 6885                            .update(cx, |this, cx| {
 6886                                this.edit_breakpoint_at_anchor(
 6887                                    anchor,
 6888                                    breakpoint.as_ref().clone(),
 6889                                    BreakpointEditAction::Toggle,
 6890                                    cx,
 6891                                );
 6892                            })
 6893                            .log_err();
 6894                    }
 6895                })
 6896                .entry(log_breakpoint_msg, None, {
 6897                    let breakpoint = breakpoint.clone();
 6898                    let weak_editor = weak_editor.clone();
 6899                    move |window, cx| {
 6900                        weak_editor
 6901                            .update(cx, |this, cx| {
 6902                                this.add_edit_breakpoint_block(
 6903                                    anchor,
 6904                                    breakpoint.as_ref(),
 6905                                    BreakpointPromptEditAction::Log,
 6906                                    window,
 6907                                    cx,
 6908                                );
 6909                            })
 6910                            .log_err();
 6911                    }
 6912                })
 6913                .entry(condition_breakpoint_msg, None, {
 6914                    let breakpoint = breakpoint.clone();
 6915                    let weak_editor = weak_editor.clone();
 6916                    move |window, cx| {
 6917                        weak_editor
 6918                            .update(cx, |this, cx| {
 6919                                this.add_edit_breakpoint_block(
 6920                                    anchor,
 6921                                    breakpoint.as_ref(),
 6922                                    BreakpointPromptEditAction::Condition,
 6923                                    window,
 6924                                    cx,
 6925                                );
 6926                            })
 6927                            .log_err();
 6928                    }
 6929                })
 6930                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6931                    weak_editor
 6932                        .update(cx, |this, cx| {
 6933                            this.add_edit_breakpoint_block(
 6934                                anchor,
 6935                                breakpoint.as_ref(),
 6936                                BreakpointPromptEditAction::HitCondition,
 6937                                window,
 6938                                cx,
 6939                            );
 6940                        })
 6941                        .log_err();
 6942                })
 6943        })
 6944    }
 6945
 6946    fn render_breakpoint(
 6947        &self,
 6948        position: Anchor,
 6949        row: DisplayRow,
 6950        breakpoint: &Breakpoint,
 6951        cx: &mut Context<Self>,
 6952    ) -> IconButton {
 6953        // Is it a breakpoint that shows up when hovering over gutter?
 6954        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 6955            (false, false),
 6956            |PhantomBreakpointIndicator {
 6957                 is_active,
 6958                 display_row,
 6959                 collides_with_existing_breakpoint,
 6960             }| {
 6961                (
 6962                    is_active && display_row == row,
 6963                    collides_with_existing_breakpoint,
 6964                )
 6965            },
 6966        );
 6967
 6968        let (color, icon) = {
 6969            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6970                (false, false) => ui::IconName::DebugBreakpoint,
 6971                (true, false) => ui::IconName::DebugLogBreakpoint,
 6972                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6973                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6974            };
 6975
 6976            let color = if is_phantom {
 6977                Color::Hint
 6978            } else {
 6979                Color::Debugger
 6980            };
 6981
 6982            (color, icon)
 6983        };
 6984
 6985        let breakpoint = Arc::from(breakpoint.clone());
 6986
 6987        let alt_as_text = gpui::Keystroke {
 6988            modifiers: Modifiers::secondary_key(),
 6989            ..Default::default()
 6990        };
 6991        let primary_action_text = if breakpoint.is_disabled() {
 6992            "enable"
 6993        } else if is_phantom && !collides_with_existing {
 6994            "set"
 6995        } else {
 6996            "unset"
 6997        };
 6998        let mut primary_text = format!("Click to {primary_action_text}");
 6999        if collides_with_existing && !breakpoint.is_disabled() {
 7000            use std::fmt::Write;
 7001            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7002        }
 7003        let primary_text = SharedString::from(primary_text);
 7004        let focus_handle = self.focus_handle.clone();
 7005        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7006            .icon_size(IconSize::XSmall)
 7007            .size(ui::ButtonSize::None)
 7008            .icon_color(color)
 7009            .style(ButtonStyle::Transparent)
 7010            .on_click(cx.listener({
 7011                let breakpoint = breakpoint.clone();
 7012
 7013                move |editor, event: &ClickEvent, window, cx| {
 7014                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7015                        BreakpointEditAction::InvertState
 7016                    } else {
 7017                        BreakpointEditAction::Toggle
 7018                    };
 7019
 7020                    window.focus(&editor.focus_handle(cx));
 7021                    editor.edit_breakpoint_at_anchor(
 7022                        position,
 7023                        breakpoint.as_ref().clone(),
 7024                        edit_action,
 7025                        cx,
 7026                    );
 7027                }
 7028            }))
 7029            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7030                editor.set_breakpoint_context_menu(
 7031                    row,
 7032                    Some(position),
 7033                    event.down.position,
 7034                    window,
 7035                    cx,
 7036                );
 7037            }))
 7038            .tooltip(move |window, cx| {
 7039                Tooltip::with_meta_in(
 7040                    primary_text.clone(),
 7041                    None,
 7042                    "Right-click for more options",
 7043                    &focus_handle,
 7044                    window,
 7045                    cx,
 7046                )
 7047            })
 7048    }
 7049
 7050    fn build_tasks_context(
 7051        project: &Entity<Project>,
 7052        buffer: &Entity<Buffer>,
 7053        buffer_row: u32,
 7054        tasks: &Arc<RunnableTasks>,
 7055        cx: &mut Context<Self>,
 7056    ) -> Task<Option<task::TaskContext>> {
 7057        let position = Point::new(buffer_row, tasks.column);
 7058        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7059        let location = Location {
 7060            buffer: buffer.clone(),
 7061            range: range_start..range_start,
 7062        };
 7063        // Fill in the environmental variables from the tree-sitter captures
 7064        let mut captured_task_variables = TaskVariables::default();
 7065        for (capture_name, value) in tasks.extra_variables.clone() {
 7066            captured_task_variables.insert(
 7067                task::VariableName::Custom(capture_name.into()),
 7068                value.clone(),
 7069            );
 7070        }
 7071        project.update(cx, |project, cx| {
 7072            project.task_store().update(cx, |task_store, cx| {
 7073                task_store.task_context_for_location(captured_task_variables, location, cx)
 7074            })
 7075        })
 7076    }
 7077
 7078    pub fn spawn_nearest_task(
 7079        &mut self,
 7080        action: &SpawnNearestTask,
 7081        window: &mut Window,
 7082        cx: &mut Context<Self>,
 7083    ) {
 7084        let Some((workspace, _)) = self.workspace.clone() else {
 7085            return;
 7086        };
 7087        let Some(project) = self.project.clone() else {
 7088            return;
 7089        };
 7090
 7091        // Try to find a closest, enclosing node using tree-sitter that has a
 7092        // task
 7093        let Some((buffer, buffer_row, tasks)) = self
 7094            .find_enclosing_node_task(cx)
 7095            // Or find the task that's closest in row-distance.
 7096            .or_else(|| self.find_closest_task(cx))
 7097        else {
 7098            return;
 7099        };
 7100
 7101        let reveal_strategy = action.reveal;
 7102        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7103        cx.spawn_in(window, async move |_, cx| {
 7104            let context = task_context.await?;
 7105            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7106
 7107            let resolved = &mut resolved_task.resolved;
 7108            resolved.reveal = reveal_strategy;
 7109
 7110            workspace
 7111                .update_in(cx, |workspace, window, cx| {
 7112                    workspace.schedule_resolved_task(
 7113                        task_source_kind,
 7114                        resolved_task,
 7115                        false,
 7116                        window,
 7117                        cx,
 7118                    );
 7119                })
 7120                .ok()
 7121        })
 7122        .detach();
 7123    }
 7124
 7125    fn find_closest_task(
 7126        &mut self,
 7127        cx: &mut Context<Self>,
 7128    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7129        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7130
 7131        let ((buffer_id, row), tasks) = self
 7132            .tasks
 7133            .iter()
 7134            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7135
 7136        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7137        let tasks = Arc::new(tasks.to_owned());
 7138        Some((buffer, *row, tasks))
 7139    }
 7140
 7141    fn find_enclosing_node_task(
 7142        &mut self,
 7143        cx: &mut Context<Self>,
 7144    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7145        let snapshot = self.buffer.read(cx).snapshot(cx);
 7146        let offset = self.selections.newest::<usize>(cx).head();
 7147        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7148        let buffer_id = excerpt.buffer().remote_id();
 7149
 7150        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7151        let mut cursor = layer.node().walk();
 7152
 7153        while cursor.goto_first_child_for_byte(offset).is_some() {
 7154            if cursor.node().end_byte() == offset {
 7155                cursor.goto_next_sibling();
 7156            }
 7157        }
 7158
 7159        // Ascend to the smallest ancestor that contains the range and has a task.
 7160        loop {
 7161            let node = cursor.node();
 7162            let node_range = node.byte_range();
 7163            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7164
 7165            // Check if this node contains our offset
 7166            if node_range.start <= offset && node_range.end >= offset {
 7167                // If it contains offset, check for task
 7168                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7169                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7170                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7171                }
 7172            }
 7173
 7174            if !cursor.goto_parent() {
 7175                break;
 7176            }
 7177        }
 7178        None
 7179    }
 7180
 7181    fn render_run_indicator(
 7182        &self,
 7183        _style: &EditorStyle,
 7184        is_active: bool,
 7185        row: DisplayRow,
 7186        breakpoint: Option<(Anchor, Breakpoint)>,
 7187        cx: &mut Context<Self>,
 7188    ) -> IconButton {
 7189        let color = Color::Muted;
 7190        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7191
 7192        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7193            .shape(ui::IconButtonShape::Square)
 7194            .icon_size(IconSize::XSmall)
 7195            .icon_color(color)
 7196            .toggle_state(is_active)
 7197            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7198                let quick_launch = e.down.button == MouseButton::Left;
 7199                window.focus(&editor.focus_handle(cx));
 7200                editor.toggle_code_actions(
 7201                    &ToggleCodeActions {
 7202                        deployed_from_indicator: Some(row),
 7203                        quick_launch,
 7204                    },
 7205                    window,
 7206                    cx,
 7207                );
 7208            }))
 7209            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7210                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7211            }))
 7212    }
 7213
 7214    pub fn context_menu_visible(&self) -> bool {
 7215        !self.edit_prediction_preview_is_active()
 7216            && self
 7217                .context_menu
 7218                .borrow()
 7219                .as_ref()
 7220                .map_or(false, |menu| menu.visible())
 7221    }
 7222
 7223    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7224        self.context_menu
 7225            .borrow()
 7226            .as_ref()
 7227            .map(|menu| menu.origin())
 7228    }
 7229
 7230    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7231        self.context_menu_options = Some(options);
 7232    }
 7233
 7234    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7235    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7236
 7237    fn render_edit_prediction_popover(
 7238        &mut self,
 7239        text_bounds: &Bounds<Pixels>,
 7240        content_origin: gpui::Point<Pixels>,
 7241        editor_snapshot: &EditorSnapshot,
 7242        visible_row_range: Range<DisplayRow>,
 7243        scroll_top: f32,
 7244        scroll_bottom: f32,
 7245        line_layouts: &[LineWithInvisibles],
 7246        line_height: Pixels,
 7247        scroll_pixel_position: gpui::Point<Pixels>,
 7248        newest_selection_head: Option<DisplayPoint>,
 7249        editor_width: Pixels,
 7250        style: &EditorStyle,
 7251        window: &mut Window,
 7252        cx: &mut App,
 7253    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7254        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7255
 7256        if self.edit_prediction_visible_in_cursor_popover(true) {
 7257            return None;
 7258        }
 7259
 7260        match &active_inline_completion.completion {
 7261            InlineCompletion::Move { target, .. } => {
 7262                let target_display_point = target.to_display_point(editor_snapshot);
 7263
 7264                if self.edit_prediction_requires_modifier() {
 7265                    if !self.edit_prediction_preview_is_active() {
 7266                        return None;
 7267                    }
 7268
 7269                    self.render_edit_prediction_modifier_jump_popover(
 7270                        text_bounds,
 7271                        content_origin,
 7272                        visible_row_range,
 7273                        line_layouts,
 7274                        line_height,
 7275                        scroll_pixel_position,
 7276                        newest_selection_head,
 7277                        target_display_point,
 7278                        window,
 7279                        cx,
 7280                    )
 7281                } else {
 7282                    self.render_edit_prediction_eager_jump_popover(
 7283                        text_bounds,
 7284                        content_origin,
 7285                        editor_snapshot,
 7286                        visible_row_range,
 7287                        scroll_top,
 7288                        scroll_bottom,
 7289                        line_height,
 7290                        scroll_pixel_position,
 7291                        target_display_point,
 7292                        editor_width,
 7293                        window,
 7294                        cx,
 7295                    )
 7296                }
 7297            }
 7298            InlineCompletion::Edit {
 7299                display_mode: EditDisplayMode::Inline,
 7300                ..
 7301            } => None,
 7302            InlineCompletion::Edit {
 7303                display_mode: EditDisplayMode::TabAccept,
 7304                edits,
 7305                ..
 7306            } => {
 7307                let range = &edits.first()?.0;
 7308                let target_display_point = range.end.to_display_point(editor_snapshot);
 7309
 7310                self.render_edit_prediction_end_of_line_popover(
 7311                    "Accept",
 7312                    editor_snapshot,
 7313                    visible_row_range,
 7314                    target_display_point,
 7315                    line_height,
 7316                    scroll_pixel_position,
 7317                    content_origin,
 7318                    editor_width,
 7319                    window,
 7320                    cx,
 7321                )
 7322            }
 7323            InlineCompletion::Edit {
 7324                edits,
 7325                edit_preview,
 7326                display_mode: EditDisplayMode::DiffPopover,
 7327                snapshot,
 7328            } => self.render_edit_prediction_diff_popover(
 7329                text_bounds,
 7330                content_origin,
 7331                editor_snapshot,
 7332                visible_row_range,
 7333                line_layouts,
 7334                line_height,
 7335                scroll_pixel_position,
 7336                newest_selection_head,
 7337                editor_width,
 7338                style,
 7339                edits,
 7340                edit_preview,
 7341                snapshot,
 7342                window,
 7343                cx,
 7344            ),
 7345        }
 7346    }
 7347
 7348    fn render_edit_prediction_modifier_jump_popover(
 7349        &mut self,
 7350        text_bounds: &Bounds<Pixels>,
 7351        content_origin: gpui::Point<Pixels>,
 7352        visible_row_range: Range<DisplayRow>,
 7353        line_layouts: &[LineWithInvisibles],
 7354        line_height: Pixels,
 7355        scroll_pixel_position: gpui::Point<Pixels>,
 7356        newest_selection_head: Option<DisplayPoint>,
 7357        target_display_point: DisplayPoint,
 7358        window: &mut Window,
 7359        cx: &mut App,
 7360    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7361        let scrolled_content_origin =
 7362            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7363
 7364        const SCROLL_PADDING_Y: Pixels = px(12.);
 7365
 7366        if target_display_point.row() < visible_row_range.start {
 7367            return self.render_edit_prediction_scroll_popover(
 7368                |_| SCROLL_PADDING_Y,
 7369                IconName::ArrowUp,
 7370                visible_row_range,
 7371                line_layouts,
 7372                newest_selection_head,
 7373                scrolled_content_origin,
 7374                window,
 7375                cx,
 7376            );
 7377        } else if target_display_point.row() >= visible_row_range.end {
 7378            return self.render_edit_prediction_scroll_popover(
 7379                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7380                IconName::ArrowDown,
 7381                visible_row_range,
 7382                line_layouts,
 7383                newest_selection_head,
 7384                scrolled_content_origin,
 7385                window,
 7386                cx,
 7387            );
 7388        }
 7389
 7390        const POLE_WIDTH: Pixels = px(2.);
 7391
 7392        let line_layout =
 7393            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7394        let target_column = target_display_point.column() as usize;
 7395
 7396        let target_x = line_layout.x_for_index(target_column);
 7397        let target_y =
 7398            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7399
 7400        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7401
 7402        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7403        border_color.l += 0.001;
 7404
 7405        let mut element = v_flex()
 7406            .items_end()
 7407            .when(flag_on_right, |el| el.items_start())
 7408            .child(if flag_on_right {
 7409                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7410                    .rounded_bl(px(0.))
 7411                    .rounded_tl(px(0.))
 7412                    .border_l_2()
 7413                    .border_color(border_color)
 7414            } else {
 7415                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7416                    .rounded_br(px(0.))
 7417                    .rounded_tr(px(0.))
 7418                    .border_r_2()
 7419                    .border_color(border_color)
 7420            })
 7421            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7422            .into_any();
 7423
 7424        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7425
 7426        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7427            - point(
 7428                if flag_on_right {
 7429                    POLE_WIDTH
 7430                } else {
 7431                    size.width - POLE_WIDTH
 7432                },
 7433                size.height - line_height,
 7434            );
 7435
 7436        origin.x = origin.x.max(content_origin.x);
 7437
 7438        element.prepaint_at(origin, window, cx);
 7439
 7440        Some((element, origin))
 7441    }
 7442
 7443    fn render_edit_prediction_scroll_popover(
 7444        &mut self,
 7445        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7446        scroll_icon: IconName,
 7447        visible_row_range: Range<DisplayRow>,
 7448        line_layouts: &[LineWithInvisibles],
 7449        newest_selection_head: Option<DisplayPoint>,
 7450        scrolled_content_origin: gpui::Point<Pixels>,
 7451        window: &mut Window,
 7452        cx: &mut App,
 7453    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7454        let mut element = self
 7455            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7456            .into_any();
 7457
 7458        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7459
 7460        let cursor = newest_selection_head?;
 7461        let cursor_row_layout =
 7462            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7463        let cursor_column = cursor.column() as usize;
 7464
 7465        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7466
 7467        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7468
 7469        element.prepaint_at(origin, window, cx);
 7470        Some((element, origin))
 7471    }
 7472
 7473    fn render_edit_prediction_eager_jump_popover(
 7474        &mut self,
 7475        text_bounds: &Bounds<Pixels>,
 7476        content_origin: gpui::Point<Pixels>,
 7477        editor_snapshot: &EditorSnapshot,
 7478        visible_row_range: Range<DisplayRow>,
 7479        scroll_top: f32,
 7480        scroll_bottom: f32,
 7481        line_height: Pixels,
 7482        scroll_pixel_position: gpui::Point<Pixels>,
 7483        target_display_point: DisplayPoint,
 7484        editor_width: Pixels,
 7485        window: &mut Window,
 7486        cx: &mut App,
 7487    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7488        if target_display_point.row().as_f32() < scroll_top {
 7489            let mut element = self
 7490                .render_edit_prediction_line_popover(
 7491                    "Jump to Edit",
 7492                    Some(IconName::ArrowUp),
 7493                    window,
 7494                    cx,
 7495                )?
 7496                .into_any();
 7497
 7498            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7499            let offset = point(
 7500                (text_bounds.size.width - size.width) / 2.,
 7501                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7502            );
 7503
 7504            let origin = text_bounds.origin + offset;
 7505            element.prepaint_at(origin, window, cx);
 7506            Some((element, origin))
 7507        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7508            let mut element = self
 7509                .render_edit_prediction_line_popover(
 7510                    "Jump to Edit",
 7511                    Some(IconName::ArrowDown),
 7512                    window,
 7513                    cx,
 7514                )?
 7515                .into_any();
 7516
 7517            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7518            let offset = point(
 7519                (text_bounds.size.width - size.width) / 2.,
 7520                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7521            );
 7522
 7523            let origin = text_bounds.origin + offset;
 7524            element.prepaint_at(origin, window, cx);
 7525            Some((element, origin))
 7526        } else {
 7527            self.render_edit_prediction_end_of_line_popover(
 7528                "Jump to Edit",
 7529                editor_snapshot,
 7530                visible_row_range,
 7531                target_display_point,
 7532                line_height,
 7533                scroll_pixel_position,
 7534                content_origin,
 7535                editor_width,
 7536                window,
 7537                cx,
 7538            )
 7539        }
 7540    }
 7541
 7542    fn render_edit_prediction_end_of_line_popover(
 7543        self: &mut Editor,
 7544        label: &'static str,
 7545        editor_snapshot: &EditorSnapshot,
 7546        visible_row_range: Range<DisplayRow>,
 7547        target_display_point: DisplayPoint,
 7548        line_height: Pixels,
 7549        scroll_pixel_position: gpui::Point<Pixels>,
 7550        content_origin: gpui::Point<Pixels>,
 7551        editor_width: Pixels,
 7552        window: &mut Window,
 7553        cx: &mut App,
 7554    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7555        let target_line_end = DisplayPoint::new(
 7556            target_display_point.row(),
 7557            editor_snapshot.line_len(target_display_point.row()),
 7558        );
 7559
 7560        let mut element = self
 7561            .render_edit_prediction_line_popover(label, None, window, cx)?
 7562            .into_any();
 7563
 7564        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7565
 7566        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7567
 7568        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7569        let mut origin = start_point
 7570            + line_origin
 7571            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7572        origin.x = origin.x.max(content_origin.x);
 7573
 7574        let max_x = content_origin.x + editor_width - size.width;
 7575
 7576        if origin.x > max_x {
 7577            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7578
 7579            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7580                origin.y += offset;
 7581                IconName::ArrowUp
 7582            } else {
 7583                origin.y -= offset;
 7584                IconName::ArrowDown
 7585            };
 7586
 7587            element = self
 7588                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7589                .into_any();
 7590
 7591            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7592
 7593            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7594        }
 7595
 7596        element.prepaint_at(origin, window, cx);
 7597        Some((element, origin))
 7598    }
 7599
 7600    fn render_edit_prediction_diff_popover(
 7601        self: &Editor,
 7602        text_bounds: &Bounds<Pixels>,
 7603        content_origin: gpui::Point<Pixels>,
 7604        editor_snapshot: &EditorSnapshot,
 7605        visible_row_range: Range<DisplayRow>,
 7606        line_layouts: &[LineWithInvisibles],
 7607        line_height: Pixels,
 7608        scroll_pixel_position: gpui::Point<Pixels>,
 7609        newest_selection_head: Option<DisplayPoint>,
 7610        editor_width: Pixels,
 7611        style: &EditorStyle,
 7612        edits: &Vec<(Range<Anchor>, String)>,
 7613        edit_preview: &Option<language::EditPreview>,
 7614        snapshot: &language::BufferSnapshot,
 7615        window: &mut Window,
 7616        cx: &mut App,
 7617    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7618        let edit_start = edits
 7619            .first()
 7620            .unwrap()
 7621            .0
 7622            .start
 7623            .to_display_point(editor_snapshot);
 7624        let edit_end = edits
 7625            .last()
 7626            .unwrap()
 7627            .0
 7628            .end
 7629            .to_display_point(editor_snapshot);
 7630
 7631        let is_visible = visible_row_range.contains(&edit_start.row())
 7632            || visible_row_range.contains(&edit_end.row());
 7633        if !is_visible {
 7634            return None;
 7635        }
 7636
 7637        let highlighted_edits =
 7638            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7639
 7640        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7641        let line_count = highlighted_edits.text.lines().count();
 7642
 7643        const BORDER_WIDTH: Pixels = px(1.);
 7644
 7645        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7646        let has_keybind = keybind.is_some();
 7647
 7648        let mut element = h_flex()
 7649            .items_start()
 7650            .child(
 7651                h_flex()
 7652                    .bg(cx.theme().colors().editor_background)
 7653                    .border(BORDER_WIDTH)
 7654                    .shadow_sm()
 7655                    .border_color(cx.theme().colors().border)
 7656                    .rounded_l_lg()
 7657                    .when(line_count > 1, |el| el.rounded_br_lg())
 7658                    .pr_1()
 7659                    .child(styled_text),
 7660            )
 7661            .child(
 7662                h_flex()
 7663                    .h(line_height + BORDER_WIDTH * 2.)
 7664                    .px_1p5()
 7665                    .gap_1()
 7666                    // Workaround: For some reason, there's a gap if we don't do this
 7667                    .ml(-BORDER_WIDTH)
 7668                    .shadow(smallvec![gpui::BoxShadow {
 7669                        color: gpui::black().opacity(0.05),
 7670                        offset: point(px(1.), px(1.)),
 7671                        blur_radius: px(2.),
 7672                        spread_radius: px(0.),
 7673                    }])
 7674                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7675                    .border(BORDER_WIDTH)
 7676                    .border_color(cx.theme().colors().border)
 7677                    .rounded_r_lg()
 7678                    .id("edit_prediction_diff_popover_keybind")
 7679                    .when(!has_keybind, |el| {
 7680                        let status_colors = cx.theme().status();
 7681
 7682                        el.bg(status_colors.error_background)
 7683                            .border_color(status_colors.error.opacity(0.6))
 7684                            .child(Icon::new(IconName::Info).color(Color::Error))
 7685                            .cursor_default()
 7686                            .hoverable_tooltip(move |_window, cx| {
 7687                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7688                            })
 7689                    })
 7690                    .children(keybind),
 7691            )
 7692            .into_any();
 7693
 7694        let longest_row =
 7695            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7696        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7697            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7698        } else {
 7699            layout_line(
 7700                longest_row,
 7701                editor_snapshot,
 7702                style,
 7703                editor_width,
 7704                |_| false,
 7705                window,
 7706                cx,
 7707            )
 7708            .width
 7709        };
 7710
 7711        let viewport_bounds =
 7712            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7713                right: -EditorElement::SCROLLBAR_WIDTH,
 7714                ..Default::default()
 7715            });
 7716
 7717        let x_after_longest =
 7718            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7719                - scroll_pixel_position.x;
 7720
 7721        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7722
 7723        // Fully visible if it can be displayed within the window (allow overlapping other
 7724        // panes). However, this is only allowed if the popover starts within text_bounds.
 7725        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7726            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7727
 7728        let mut origin = if can_position_to_the_right {
 7729            point(
 7730                x_after_longest,
 7731                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7732                    - scroll_pixel_position.y,
 7733            )
 7734        } else {
 7735            let cursor_row = newest_selection_head.map(|head| head.row());
 7736            let above_edit = edit_start
 7737                .row()
 7738                .0
 7739                .checked_sub(line_count as u32)
 7740                .map(DisplayRow);
 7741            let below_edit = Some(edit_end.row() + 1);
 7742            let above_cursor =
 7743                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7744            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7745
 7746            // Place the edit popover adjacent to the edit if there is a location
 7747            // available that is onscreen and does not obscure the cursor. Otherwise,
 7748            // place it adjacent to the cursor.
 7749            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7750                .into_iter()
 7751                .flatten()
 7752                .find(|&start_row| {
 7753                    let end_row = start_row + line_count as u32;
 7754                    visible_row_range.contains(&start_row)
 7755                        && visible_row_range.contains(&end_row)
 7756                        && cursor_row.map_or(true, |cursor_row| {
 7757                            !((start_row..end_row).contains(&cursor_row))
 7758                        })
 7759                })?;
 7760
 7761            content_origin
 7762                + point(
 7763                    -scroll_pixel_position.x,
 7764                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7765                )
 7766        };
 7767
 7768        origin.x -= BORDER_WIDTH;
 7769
 7770        window.defer_draw(element, origin, 1);
 7771
 7772        // Do not return an element, since it will already be drawn due to defer_draw.
 7773        None
 7774    }
 7775
 7776    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7777        px(30.)
 7778    }
 7779
 7780    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7781        if self.read_only(cx) {
 7782            cx.theme().players().read_only()
 7783        } else {
 7784            self.style.as_ref().unwrap().local_player
 7785        }
 7786    }
 7787
 7788    fn render_edit_prediction_accept_keybind(
 7789        &self,
 7790        window: &mut Window,
 7791        cx: &App,
 7792    ) -> Option<AnyElement> {
 7793        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7794        let accept_keystroke = accept_binding.keystroke()?;
 7795
 7796        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7797
 7798        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7799            Color::Accent
 7800        } else {
 7801            Color::Muted
 7802        };
 7803
 7804        h_flex()
 7805            .px_0p5()
 7806            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7807            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7808            .text_size(TextSize::XSmall.rems(cx))
 7809            .child(h_flex().children(ui::render_modifiers(
 7810                &accept_keystroke.modifiers,
 7811                PlatformStyle::platform(),
 7812                Some(modifiers_color),
 7813                Some(IconSize::XSmall.rems().into()),
 7814                true,
 7815            )))
 7816            .when(is_platform_style_mac, |parent| {
 7817                parent.child(accept_keystroke.key.clone())
 7818            })
 7819            .when(!is_platform_style_mac, |parent| {
 7820                parent.child(
 7821                    Key::new(
 7822                        util::capitalize(&accept_keystroke.key),
 7823                        Some(Color::Default),
 7824                    )
 7825                    .size(Some(IconSize::XSmall.rems().into())),
 7826                )
 7827            })
 7828            .into_any()
 7829            .into()
 7830    }
 7831
 7832    fn render_edit_prediction_line_popover(
 7833        &self,
 7834        label: impl Into<SharedString>,
 7835        icon: Option<IconName>,
 7836        window: &mut Window,
 7837        cx: &App,
 7838    ) -> Option<Stateful<Div>> {
 7839        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7840
 7841        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7842        let has_keybind = keybind.is_some();
 7843
 7844        let result = h_flex()
 7845            .id("ep-line-popover")
 7846            .py_0p5()
 7847            .pl_1()
 7848            .pr(padding_right)
 7849            .gap_1()
 7850            .rounded_md()
 7851            .border_1()
 7852            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7853            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7854            .shadow_sm()
 7855            .when(!has_keybind, |el| {
 7856                let status_colors = cx.theme().status();
 7857
 7858                el.bg(status_colors.error_background)
 7859                    .border_color(status_colors.error.opacity(0.6))
 7860                    .pl_2()
 7861                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7862                    .cursor_default()
 7863                    .hoverable_tooltip(move |_window, cx| {
 7864                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7865                    })
 7866            })
 7867            .children(keybind)
 7868            .child(
 7869                Label::new(label)
 7870                    .size(LabelSize::Small)
 7871                    .when(!has_keybind, |el| {
 7872                        el.color(cx.theme().status().error.into()).strikethrough()
 7873                    }),
 7874            )
 7875            .when(!has_keybind, |el| {
 7876                el.child(
 7877                    h_flex().ml_1().child(
 7878                        Icon::new(IconName::Info)
 7879                            .size(IconSize::Small)
 7880                            .color(cx.theme().status().error.into()),
 7881                    ),
 7882                )
 7883            })
 7884            .when_some(icon, |element, icon| {
 7885                element.child(
 7886                    div()
 7887                        .mt(px(1.5))
 7888                        .child(Icon::new(icon).size(IconSize::Small)),
 7889                )
 7890            });
 7891
 7892        Some(result)
 7893    }
 7894
 7895    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7896        let accent_color = cx.theme().colors().text_accent;
 7897        let editor_bg_color = cx.theme().colors().editor_background;
 7898        editor_bg_color.blend(accent_color.opacity(0.1))
 7899    }
 7900
 7901    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7902        let accent_color = cx.theme().colors().text_accent;
 7903        let editor_bg_color = cx.theme().colors().editor_background;
 7904        editor_bg_color.blend(accent_color.opacity(0.6))
 7905    }
 7906
 7907    fn render_edit_prediction_cursor_popover(
 7908        &self,
 7909        min_width: Pixels,
 7910        max_width: Pixels,
 7911        cursor_point: Point,
 7912        style: &EditorStyle,
 7913        accept_keystroke: Option<&gpui::Keystroke>,
 7914        _window: &Window,
 7915        cx: &mut Context<Editor>,
 7916    ) -> Option<AnyElement> {
 7917        let provider = self.edit_prediction_provider.as_ref()?;
 7918
 7919        if provider.provider.needs_terms_acceptance(cx) {
 7920            return Some(
 7921                h_flex()
 7922                    .min_w(min_width)
 7923                    .flex_1()
 7924                    .px_2()
 7925                    .py_1()
 7926                    .gap_3()
 7927                    .elevation_2(cx)
 7928                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7929                    .id("accept-terms")
 7930                    .cursor_pointer()
 7931                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7932                    .on_click(cx.listener(|this, _event, window, cx| {
 7933                        cx.stop_propagation();
 7934                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7935                        window.dispatch_action(
 7936                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7937                            cx,
 7938                        );
 7939                    }))
 7940                    .child(
 7941                        h_flex()
 7942                            .flex_1()
 7943                            .gap_2()
 7944                            .child(Icon::new(IconName::ZedPredict))
 7945                            .child(Label::new("Accept Terms of Service"))
 7946                            .child(div().w_full())
 7947                            .child(
 7948                                Icon::new(IconName::ArrowUpRight)
 7949                                    .color(Color::Muted)
 7950                                    .size(IconSize::Small),
 7951                            )
 7952                            .into_any_element(),
 7953                    )
 7954                    .into_any(),
 7955            );
 7956        }
 7957
 7958        let is_refreshing = provider.provider.is_refreshing(cx);
 7959
 7960        fn pending_completion_container() -> Div {
 7961            h_flex()
 7962                .h_full()
 7963                .flex_1()
 7964                .gap_2()
 7965                .child(Icon::new(IconName::ZedPredict))
 7966        }
 7967
 7968        let completion = match &self.active_inline_completion {
 7969            Some(prediction) => {
 7970                if !self.has_visible_completions_menu() {
 7971                    const RADIUS: Pixels = px(6.);
 7972                    const BORDER_WIDTH: Pixels = px(1.);
 7973
 7974                    return Some(
 7975                        h_flex()
 7976                            .elevation_2(cx)
 7977                            .border(BORDER_WIDTH)
 7978                            .border_color(cx.theme().colors().border)
 7979                            .when(accept_keystroke.is_none(), |el| {
 7980                                el.border_color(cx.theme().status().error)
 7981                            })
 7982                            .rounded(RADIUS)
 7983                            .rounded_tl(px(0.))
 7984                            .overflow_hidden()
 7985                            .child(div().px_1p5().child(match &prediction.completion {
 7986                                InlineCompletion::Move { target, snapshot } => {
 7987                                    use text::ToPoint as _;
 7988                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7989                                    {
 7990                                        Icon::new(IconName::ZedPredictDown)
 7991                                    } else {
 7992                                        Icon::new(IconName::ZedPredictUp)
 7993                                    }
 7994                                }
 7995                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7996                            }))
 7997                            .child(
 7998                                h_flex()
 7999                                    .gap_1()
 8000                                    .py_1()
 8001                                    .px_2()
 8002                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8003                                    .border_l_1()
 8004                                    .border_color(cx.theme().colors().border)
 8005                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8006                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8007                                        el.child(
 8008                                            Label::new("Hold")
 8009                                                .size(LabelSize::Small)
 8010                                                .when(accept_keystroke.is_none(), |el| {
 8011                                                    el.strikethrough()
 8012                                                })
 8013                                                .line_height_style(LineHeightStyle::UiLabel),
 8014                                        )
 8015                                    })
 8016                                    .id("edit_prediction_cursor_popover_keybind")
 8017                                    .when(accept_keystroke.is_none(), |el| {
 8018                                        let status_colors = cx.theme().status();
 8019
 8020                                        el.bg(status_colors.error_background)
 8021                                            .border_color(status_colors.error.opacity(0.6))
 8022                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8023                                            .cursor_default()
 8024                                            .hoverable_tooltip(move |_window, cx| {
 8025                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8026                                                    .into()
 8027                                            })
 8028                                    })
 8029                                    .when_some(
 8030                                        accept_keystroke.as_ref(),
 8031                                        |el, accept_keystroke| {
 8032                                            el.child(h_flex().children(ui::render_modifiers(
 8033                                                &accept_keystroke.modifiers,
 8034                                                PlatformStyle::platform(),
 8035                                                Some(Color::Default),
 8036                                                Some(IconSize::XSmall.rems().into()),
 8037                                                false,
 8038                                            )))
 8039                                        },
 8040                                    ),
 8041                            )
 8042                            .into_any(),
 8043                    );
 8044                }
 8045
 8046                self.render_edit_prediction_cursor_popover_preview(
 8047                    prediction,
 8048                    cursor_point,
 8049                    style,
 8050                    cx,
 8051                )?
 8052            }
 8053
 8054            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8055                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8056                    stale_completion,
 8057                    cursor_point,
 8058                    style,
 8059                    cx,
 8060                )?,
 8061
 8062                None => {
 8063                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8064                }
 8065            },
 8066
 8067            None => pending_completion_container().child(Label::new("No Prediction")),
 8068        };
 8069
 8070        let completion = if is_refreshing {
 8071            completion
 8072                .with_animation(
 8073                    "loading-completion",
 8074                    Animation::new(Duration::from_secs(2))
 8075                        .repeat()
 8076                        .with_easing(pulsating_between(0.4, 0.8)),
 8077                    |label, delta| label.opacity(delta),
 8078                )
 8079                .into_any_element()
 8080        } else {
 8081            completion.into_any_element()
 8082        };
 8083
 8084        let has_completion = self.active_inline_completion.is_some();
 8085
 8086        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8087        Some(
 8088            h_flex()
 8089                .min_w(min_width)
 8090                .max_w(max_width)
 8091                .flex_1()
 8092                .elevation_2(cx)
 8093                .border_color(cx.theme().colors().border)
 8094                .child(
 8095                    div()
 8096                        .flex_1()
 8097                        .py_1()
 8098                        .px_2()
 8099                        .overflow_hidden()
 8100                        .child(completion),
 8101                )
 8102                .when_some(accept_keystroke, |el, accept_keystroke| {
 8103                    if !accept_keystroke.modifiers.modified() {
 8104                        return el;
 8105                    }
 8106
 8107                    el.child(
 8108                        h_flex()
 8109                            .h_full()
 8110                            .border_l_1()
 8111                            .rounded_r_lg()
 8112                            .border_color(cx.theme().colors().border)
 8113                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8114                            .gap_1()
 8115                            .py_1()
 8116                            .px_2()
 8117                            .child(
 8118                                h_flex()
 8119                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8120                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8121                                    .child(h_flex().children(ui::render_modifiers(
 8122                                        &accept_keystroke.modifiers,
 8123                                        PlatformStyle::platform(),
 8124                                        Some(if !has_completion {
 8125                                            Color::Muted
 8126                                        } else {
 8127                                            Color::Default
 8128                                        }),
 8129                                        None,
 8130                                        false,
 8131                                    ))),
 8132                            )
 8133                            .child(Label::new("Preview").into_any_element())
 8134                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8135                    )
 8136                })
 8137                .into_any(),
 8138        )
 8139    }
 8140
 8141    fn render_edit_prediction_cursor_popover_preview(
 8142        &self,
 8143        completion: &InlineCompletionState,
 8144        cursor_point: Point,
 8145        style: &EditorStyle,
 8146        cx: &mut Context<Editor>,
 8147    ) -> Option<Div> {
 8148        use text::ToPoint as _;
 8149
 8150        fn render_relative_row_jump(
 8151            prefix: impl Into<String>,
 8152            current_row: u32,
 8153            target_row: u32,
 8154        ) -> Div {
 8155            let (row_diff, arrow) = if target_row < current_row {
 8156                (current_row - target_row, IconName::ArrowUp)
 8157            } else {
 8158                (target_row - current_row, IconName::ArrowDown)
 8159            };
 8160
 8161            h_flex()
 8162                .child(
 8163                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8164                        .color(Color::Muted)
 8165                        .size(LabelSize::Small),
 8166                )
 8167                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8168        }
 8169
 8170        match &completion.completion {
 8171            InlineCompletion::Move {
 8172                target, snapshot, ..
 8173            } => Some(
 8174                h_flex()
 8175                    .px_2()
 8176                    .gap_2()
 8177                    .flex_1()
 8178                    .child(
 8179                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8180                            Icon::new(IconName::ZedPredictDown)
 8181                        } else {
 8182                            Icon::new(IconName::ZedPredictUp)
 8183                        },
 8184                    )
 8185                    .child(Label::new("Jump to Edit")),
 8186            ),
 8187
 8188            InlineCompletion::Edit {
 8189                edits,
 8190                edit_preview,
 8191                snapshot,
 8192                display_mode: _,
 8193            } => {
 8194                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8195
 8196                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8197                    &snapshot,
 8198                    &edits,
 8199                    edit_preview.as_ref()?,
 8200                    true,
 8201                    cx,
 8202                )
 8203                .first_line_preview();
 8204
 8205                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8206                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8207
 8208                let preview = h_flex()
 8209                    .gap_1()
 8210                    .min_w_16()
 8211                    .child(styled_text)
 8212                    .when(has_more_lines, |parent| parent.child(""));
 8213
 8214                let left = if first_edit_row != cursor_point.row {
 8215                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8216                        .into_any_element()
 8217                } else {
 8218                    Icon::new(IconName::ZedPredict).into_any_element()
 8219                };
 8220
 8221                Some(
 8222                    h_flex()
 8223                        .h_full()
 8224                        .flex_1()
 8225                        .gap_2()
 8226                        .pr_1()
 8227                        .overflow_x_hidden()
 8228                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8229                        .child(left)
 8230                        .child(preview),
 8231                )
 8232            }
 8233        }
 8234    }
 8235
 8236    fn render_context_menu(
 8237        &self,
 8238        style: &EditorStyle,
 8239        max_height_in_lines: u32,
 8240        window: &mut Window,
 8241        cx: &mut Context<Editor>,
 8242    ) -> Option<AnyElement> {
 8243        let menu = self.context_menu.borrow();
 8244        let menu = menu.as_ref()?;
 8245        if !menu.visible() {
 8246            return None;
 8247        };
 8248        Some(menu.render(style, max_height_in_lines, window, cx))
 8249    }
 8250
 8251    fn render_context_menu_aside(
 8252        &mut self,
 8253        max_size: Size<Pixels>,
 8254        window: &mut Window,
 8255        cx: &mut Context<Editor>,
 8256    ) -> Option<AnyElement> {
 8257        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8258            if menu.visible() {
 8259                menu.render_aside(self, max_size, window, cx)
 8260            } else {
 8261                None
 8262            }
 8263        })
 8264    }
 8265
 8266    fn hide_context_menu(
 8267        &mut self,
 8268        window: &mut Window,
 8269        cx: &mut Context<Self>,
 8270    ) -> Option<CodeContextMenu> {
 8271        cx.notify();
 8272        self.completion_tasks.clear();
 8273        let context_menu = self.context_menu.borrow_mut().take();
 8274        self.stale_inline_completion_in_menu.take();
 8275        self.update_visible_inline_completion(window, cx);
 8276        context_menu
 8277    }
 8278
 8279    fn show_snippet_choices(
 8280        &mut self,
 8281        choices: &Vec<String>,
 8282        selection: Range<Anchor>,
 8283        cx: &mut Context<Self>,
 8284    ) {
 8285        if selection.start.buffer_id.is_none() {
 8286            return;
 8287        }
 8288        let buffer_id = selection.start.buffer_id.unwrap();
 8289        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8290        let id = post_inc(&mut self.next_completion_id);
 8291        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8292
 8293        if let Some(buffer) = buffer {
 8294            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8295                CompletionsMenu::new_snippet_choices(
 8296                    id,
 8297                    true,
 8298                    choices,
 8299                    selection,
 8300                    buffer,
 8301                    snippet_sort_order,
 8302                ),
 8303            ));
 8304        }
 8305    }
 8306
 8307    pub fn insert_snippet(
 8308        &mut self,
 8309        insertion_ranges: &[Range<usize>],
 8310        snippet: Snippet,
 8311        window: &mut Window,
 8312        cx: &mut Context<Self>,
 8313    ) -> Result<()> {
 8314        struct Tabstop<T> {
 8315            is_end_tabstop: bool,
 8316            ranges: Vec<Range<T>>,
 8317            choices: Option<Vec<String>>,
 8318        }
 8319
 8320        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8321            let snippet_text: Arc<str> = snippet.text.clone().into();
 8322            let edits = insertion_ranges
 8323                .iter()
 8324                .cloned()
 8325                .map(|range| (range, snippet_text.clone()));
 8326            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8327
 8328            let snapshot = &*buffer.read(cx);
 8329            let snippet = &snippet;
 8330            snippet
 8331                .tabstops
 8332                .iter()
 8333                .map(|tabstop| {
 8334                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8335                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8336                    });
 8337                    let mut tabstop_ranges = tabstop
 8338                        .ranges
 8339                        .iter()
 8340                        .flat_map(|tabstop_range| {
 8341                            let mut delta = 0_isize;
 8342                            insertion_ranges.iter().map(move |insertion_range| {
 8343                                let insertion_start = insertion_range.start as isize + delta;
 8344                                delta +=
 8345                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8346
 8347                                let start = ((insertion_start + tabstop_range.start) as usize)
 8348                                    .min(snapshot.len());
 8349                                let end = ((insertion_start + tabstop_range.end) as usize)
 8350                                    .min(snapshot.len());
 8351                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8352                            })
 8353                        })
 8354                        .collect::<Vec<_>>();
 8355                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8356
 8357                    Tabstop {
 8358                        is_end_tabstop,
 8359                        ranges: tabstop_ranges,
 8360                        choices: tabstop.choices.clone(),
 8361                    }
 8362                })
 8363                .collect::<Vec<_>>()
 8364        });
 8365        if let Some(tabstop) = tabstops.first() {
 8366            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8367                s.select_ranges(tabstop.ranges.iter().cloned());
 8368            });
 8369
 8370            if let Some(choices) = &tabstop.choices {
 8371                if let Some(selection) = tabstop.ranges.first() {
 8372                    self.show_snippet_choices(choices, selection.clone(), cx)
 8373                }
 8374            }
 8375
 8376            // If we're already at the last tabstop and it's at the end of the snippet,
 8377            // we're done, we don't need to keep the state around.
 8378            if !tabstop.is_end_tabstop {
 8379                let choices = tabstops
 8380                    .iter()
 8381                    .map(|tabstop| tabstop.choices.clone())
 8382                    .collect();
 8383
 8384                let ranges = tabstops
 8385                    .into_iter()
 8386                    .map(|tabstop| tabstop.ranges)
 8387                    .collect::<Vec<_>>();
 8388
 8389                self.snippet_stack.push(SnippetState {
 8390                    active_index: 0,
 8391                    ranges,
 8392                    choices,
 8393                });
 8394            }
 8395
 8396            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8397            if self.autoclose_regions.is_empty() {
 8398                let snapshot = self.buffer.read(cx).snapshot(cx);
 8399                for selection in &mut self.selections.all::<Point>(cx) {
 8400                    let selection_head = selection.head();
 8401                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8402                        continue;
 8403                    };
 8404
 8405                    let mut bracket_pair = None;
 8406                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8407                    let prev_chars = snapshot
 8408                        .reversed_chars_at(selection_head)
 8409                        .collect::<String>();
 8410                    for (pair, enabled) in scope.brackets() {
 8411                        if enabled
 8412                            && pair.close
 8413                            && prev_chars.starts_with(pair.start.as_str())
 8414                            && next_chars.starts_with(pair.end.as_str())
 8415                        {
 8416                            bracket_pair = Some(pair.clone());
 8417                            break;
 8418                        }
 8419                    }
 8420                    if let Some(pair) = bracket_pair {
 8421                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8422                        let autoclose_enabled =
 8423                            self.use_autoclose && snapshot_settings.use_autoclose;
 8424                        if autoclose_enabled {
 8425                            let start = snapshot.anchor_after(selection_head);
 8426                            let end = snapshot.anchor_after(selection_head);
 8427                            self.autoclose_regions.push(AutocloseRegion {
 8428                                selection_id: selection.id,
 8429                                range: start..end,
 8430                                pair,
 8431                            });
 8432                        }
 8433                    }
 8434                }
 8435            }
 8436        }
 8437        Ok(())
 8438    }
 8439
 8440    pub fn move_to_next_snippet_tabstop(
 8441        &mut self,
 8442        window: &mut Window,
 8443        cx: &mut Context<Self>,
 8444    ) -> bool {
 8445        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8446    }
 8447
 8448    pub fn move_to_prev_snippet_tabstop(
 8449        &mut self,
 8450        window: &mut Window,
 8451        cx: &mut Context<Self>,
 8452    ) -> bool {
 8453        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8454    }
 8455
 8456    pub fn move_to_snippet_tabstop(
 8457        &mut self,
 8458        bias: Bias,
 8459        window: &mut Window,
 8460        cx: &mut Context<Self>,
 8461    ) -> bool {
 8462        if let Some(mut snippet) = self.snippet_stack.pop() {
 8463            match bias {
 8464                Bias::Left => {
 8465                    if snippet.active_index > 0 {
 8466                        snippet.active_index -= 1;
 8467                    } else {
 8468                        self.snippet_stack.push(snippet);
 8469                        return false;
 8470                    }
 8471                }
 8472                Bias::Right => {
 8473                    if snippet.active_index + 1 < snippet.ranges.len() {
 8474                        snippet.active_index += 1;
 8475                    } else {
 8476                        self.snippet_stack.push(snippet);
 8477                        return false;
 8478                    }
 8479                }
 8480            }
 8481            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8482                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8483                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8484                });
 8485
 8486                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8487                    if let Some(selection) = current_ranges.first() {
 8488                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8489                    }
 8490                }
 8491
 8492                // If snippet state is not at the last tabstop, push it back on the stack
 8493                if snippet.active_index + 1 < snippet.ranges.len() {
 8494                    self.snippet_stack.push(snippet);
 8495                }
 8496                return true;
 8497            }
 8498        }
 8499
 8500        false
 8501    }
 8502
 8503    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8504        self.transact(window, cx, |this, window, cx| {
 8505            this.select_all(&SelectAll, window, cx);
 8506            this.insert("", window, cx);
 8507        });
 8508    }
 8509
 8510    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8511        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8512        self.transact(window, cx, |this, window, cx| {
 8513            this.select_autoclose_pair(window, cx);
 8514            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8515            if !this.linked_edit_ranges.is_empty() {
 8516                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8517                let snapshot = this.buffer.read(cx).snapshot(cx);
 8518
 8519                for selection in selections.iter() {
 8520                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8521                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8522                    if selection_start.buffer_id != selection_end.buffer_id {
 8523                        continue;
 8524                    }
 8525                    if let Some(ranges) =
 8526                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8527                    {
 8528                        for (buffer, entries) in ranges {
 8529                            linked_ranges.entry(buffer).or_default().extend(entries);
 8530                        }
 8531                    }
 8532                }
 8533            }
 8534
 8535            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8536            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8537            for selection in &mut selections {
 8538                if selection.is_empty() {
 8539                    let old_head = selection.head();
 8540                    let mut new_head =
 8541                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8542                            .to_point(&display_map);
 8543                    if let Some((buffer, line_buffer_range)) = display_map
 8544                        .buffer_snapshot
 8545                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8546                    {
 8547                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8548                        let indent_len = match indent_size.kind {
 8549                            IndentKind::Space => {
 8550                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8551                            }
 8552                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8553                        };
 8554                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8555                            let indent_len = indent_len.get();
 8556                            new_head = cmp::min(
 8557                                new_head,
 8558                                MultiBufferPoint::new(
 8559                                    old_head.row,
 8560                                    ((old_head.column - 1) / indent_len) * indent_len,
 8561                                ),
 8562                            );
 8563                        }
 8564                    }
 8565
 8566                    selection.set_head(new_head, SelectionGoal::None);
 8567                }
 8568            }
 8569
 8570            this.signature_help_state.set_backspace_pressed(true);
 8571            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8572                s.select(selections)
 8573            });
 8574            this.insert("", window, cx);
 8575            let empty_str: Arc<str> = Arc::from("");
 8576            for (buffer, edits) in linked_ranges {
 8577                let snapshot = buffer.read(cx).snapshot();
 8578                use text::ToPoint as TP;
 8579
 8580                let edits = edits
 8581                    .into_iter()
 8582                    .map(|range| {
 8583                        let end_point = TP::to_point(&range.end, &snapshot);
 8584                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8585
 8586                        if end_point == start_point {
 8587                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8588                                .saturating_sub(1);
 8589                            start_point =
 8590                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8591                        };
 8592
 8593                        (start_point..end_point, empty_str.clone())
 8594                    })
 8595                    .sorted_by_key(|(range, _)| range.start)
 8596                    .collect::<Vec<_>>();
 8597                buffer.update(cx, |this, cx| {
 8598                    this.edit(edits, None, cx);
 8599                })
 8600            }
 8601            this.refresh_inline_completion(true, false, window, cx);
 8602            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8603        });
 8604    }
 8605
 8606    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8607        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8608        self.transact(window, cx, |this, window, cx| {
 8609            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8610                s.move_with(|map, selection| {
 8611                    if selection.is_empty() {
 8612                        let cursor = movement::right(map, selection.head());
 8613                        selection.end = cursor;
 8614                        selection.reversed = true;
 8615                        selection.goal = SelectionGoal::None;
 8616                    }
 8617                })
 8618            });
 8619            this.insert("", window, cx);
 8620            this.refresh_inline_completion(true, false, window, cx);
 8621        });
 8622    }
 8623
 8624    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8625        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8626        if self.move_to_prev_snippet_tabstop(window, cx) {
 8627            return;
 8628        }
 8629        self.outdent(&Outdent, window, cx);
 8630    }
 8631
 8632    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8633        if self.move_to_next_snippet_tabstop(window, cx) {
 8634            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8635            return;
 8636        }
 8637        if self.read_only(cx) {
 8638            return;
 8639        }
 8640        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8641        let mut selections = self.selections.all_adjusted(cx);
 8642        let buffer = self.buffer.read(cx);
 8643        let snapshot = buffer.snapshot(cx);
 8644        let rows_iter = selections.iter().map(|s| s.head().row);
 8645        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8646
 8647        let has_some_cursor_in_whitespace = selections
 8648            .iter()
 8649            .filter(|selection| selection.is_empty())
 8650            .any(|selection| {
 8651                let cursor = selection.head();
 8652                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8653                cursor.column < current_indent.len
 8654            });
 8655
 8656        let mut edits = Vec::new();
 8657        let mut prev_edited_row = 0;
 8658        let mut row_delta = 0;
 8659        for selection in &mut selections {
 8660            if selection.start.row != prev_edited_row {
 8661                row_delta = 0;
 8662            }
 8663            prev_edited_row = selection.end.row;
 8664
 8665            // If the selection is non-empty, then increase the indentation of the selected lines.
 8666            if !selection.is_empty() {
 8667                row_delta =
 8668                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8669                continue;
 8670            }
 8671
 8672            // If the selection is empty and the cursor is in the leading whitespace before the
 8673            // suggested indentation, then auto-indent the line.
 8674            let cursor = selection.head();
 8675            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8676            if let Some(suggested_indent) =
 8677                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8678            {
 8679                // If there exist any empty selection in the leading whitespace, then skip
 8680                // indent for selections at the boundary.
 8681                if has_some_cursor_in_whitespace
 8682                    && cursor.column == current_indent.len
 8683                    && current_indent.len == suggested_indent.len
 8684                {
 8685                    continue;
 8686                }
 8687
 8688                if cursor.column < suggested_indent.len
 8689                    && cursor.column <= current_indent.len
 8690                    && current_indent.len <= suggested_indent.len
 8691                {
 8692                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8693                    selection.end = selection.start;
 8694                    if row_delta == 0 {
 8695                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8696                            cursor.row,
 8697                            current_indent,
 8698                            suggested_indent,
 8699                        ));
 8700                        row_delta = suggested_indent.len - current_indent.len;
 8701                    }
 8702                    continue;
 8703                }
 8704            }
 8705
 8706            // Otherwise, insert a hard or soft tab.
 8707            let settings = buffer.language_settings_at(cursor, cx);
 8708            let tab_size = if settings.hard_tabs {
 8709                IndentSize::tab()
 8710            } else {
 8711                let tab_size = settings.tab_size.get();
 8712                let indent_remainder = snapshot
 8713                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8714                    .flat_map(str::chars)
 8715                    .fold(row_delta % tab_size, |counter: u32, c| {
 8716                        if c == '\t' {
 8717                            0
 8718                        } else {
 8719                            (counter + 1) % tab_size
 8720                        }
 8721                    });
 8722
 8723                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8724                IndentSize::spaces(chars_to_next_tab_stop)
 8725            };
 8726            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8727            selection.end = selection.start;
 8728            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8729            row_delta += tab_size.len;
 8730        }
 8731
 8732        self.transact(window, cx, |this, window, cx| {
 8733            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8734            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8735                s.select(selections)
 8736            });
 8737            this.refresh_inline_completion(true, false, window, cx);
 8738        });
 8739    }
 8740
 8741    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8742        if self.read_only(cx) {
 8743            return;
 8744        }
 8745        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8746        let mut selections = self.selections.all::<Point>(cx);
 8747        let mut prev_edited_row = 0;
 8748        let mut row_delta = 0;
 8749        let mut edits = Vec::new();
 8750        let buffer = self.buffer.read(cx);
 8751        let snapshot = buffer.snapshot(cx);
 8752        for selection in &mut selections {
 8753            if selection.start.row != prev_edited_row {
 8754                row_delta = 0;
 8755            }
 8756            prev_edited_row = selection.end.row;
 8757
 8758            row_delta =
 8759                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8760        }
 8761
 8762        self.transact(window, cx, |this, window, cx| {
 8763            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8764            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8765                s.select(selections)
 8766            });
 8767        });
 8768    }
 8769
 8770    fn indent_selection(
 8771        buffer: &MultiBuffer,
 8772        snapshot: &MultiBufferSnapshot,
 8773        selection: &mut Selection<Point>,
 8774        edits: &mut Vec<(Range<Point>, String)>,
 8775        delta_for_start_row: u32,
 8776        cx: &App,
 8777    ) -> u32 {
 8778        let settings = buffer.language_settings_at(selection.start, cx);
 8779        let tab_size = settings.tab_size.get();
 8780        let indent_kind = if settings.hard_tabs {
 8781            IndentKind::Tab
 8782        } else {
 8783            IndentKind::Space
 8784        };
 8785        let mut start_row = selection.start.row;
 8786        let mut end_row = selection.end.row + 1;
 8787
 8788        // If a selection ends at the beginning of a line, don't indent
 8789        // that last line.
 8790        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8791            end_row -= 1;
 8792        }
 8793
 8794        // Avoid re-indenting a row that has already been indented by a
 8795        // previous selection, but still update this selection's column
 8796        // to reflect that indentation.
 8797        if delta_for_start_row > 0 {
 8798            start_row += 1;
 8799            selection.start.column += delta_for_start_row;
 8800            if selection.end.row == selection.start.row {
 8801                selection.end.column += delta_for_start_row;
 8802            }
 8803        }
 8804
 8805        let mut delta_for_end_row = 0;
 8806        let has_multiple_rows = start_row + 1 != end_row;
 8807        for row in start_row..end_row {
 8808            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8809            let indent_delta = match (current_indent.kind, indent_kind) {
 8810                (IndentKind::Space, IndentKind::Space) => {
 8811                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8812                    IndentSize::spaces(columns_to_next_tab_stop)
 8813                }
 8814                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8815                (_, IndentKind::Tab) => IndentSize::tab(),
 8816            };
 8817
 8818            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8819                0
 8820            } else {
 8821                selection.start.column
 8822            };
 8823            let row_start = Point::new(row, start);
 8824            edits.push((
 8825                row_start..row_start,
 8826                indent_delta.chars().collect::<String>(),
 8827            ));
 8828
 8829            // Update this selection's endpoints to reflect the indentation.
 8830            if row == selection.start.row {
 8831                selection.start.column += indent_delta.len;
 8832            }
 8833            if row == selection.end.row {
 8834                selection.end.column += indent_delta.len;
 8835                delta_for_end_row = indent_delta.len;
 8836            }
 8837        }
 8838
 8839        if selection.start.row == selection.end.row {
 8840            delta_for_start_row + delta_for_end_row
 8841        } else {
 8842            delta_for_end_row
 8843        }
 8844    }
 8845
 8846    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8847        if self.read_only(cx) {
 8848            return;
 8849        }
 8850        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8851        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8852        let selections = self.selections.all::<Point>(cx);
 8853        let mut deletion_ranges = Vec::new();
 8854        let mut last_outdent = None;
 8855        {
 8856            let buffer = self.buffer.read(cx);
 8857            let snapshot = buffer.snapshot(cx);
 8858            for selection in &selections {
 8859                let settings = buffer.language_settings_at(selection.start, cx);
 8860                let tab_size = settings.tab_size.get();
 8861                let mut rows = selection.spanned_rows(false, &display_map);
 8862
 8863                // Avoid re-outdenting a row that has already been outdented by a
 8864                // previous selection.
 8865                if let Some(last_row) = last_outdent {
 8866                    if last_row == rows.start {
 8867                        rows.start = rows.start.next_row();
 8868                    }
 8869                }
 8870                let has_multiple_rows = rows.len() > 1;
 8871                for row in rows.iter_rows() {
 8872                    let indent_size = snapshot.indent_size_for_line(row);
 8873                    if indent_size.len > 0 {
 8874                        let deletion_len = match indent_size.kind {
 8875                            IndentKind::Space => {
 8876                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8877                                if columns_to_prev_tab_stop == 0 {
 8878                                    tab_size
 8879                                } else {
 8880                                    columns_to_prev_tab_stop
 8881                                }
 8882                            }
 8883                            IndentKind::Tab => 1,
 8884                        };
 8885                        let start = if has_multiple_rows
 8886                            || deletion_len > selection.start.column
 8887                            || indent_size.len < selection.start.column
 8888                        {
 8889                            0
 8890                        } else {
 8891                            selection.start.column - deletion_len
 8892                        };
 8893                        deletion_ranges.push(
 8894                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8895                        );
 8896                        last_outdent = Some(row);
 8897                    }
 8898                }
 8899            }
 8900        }
 8901
 8902        self.transact(window, cx, |this, window, cx| {
 8903            this.buffer.update(cx, |buffer, cx| {
 8904                let empty_str: Arc<str> = Arc::default();
 8905                buffer.edit(
 8906                    deletion_ranges
 8907                        .into_iter()
 8908                        .map(|range| (range, empty_str.clone())),
 8909                    None,
 8910                    cx,
 8911                );
 8912            });
 8913            let selections = this.selections.all::<usize>(cx);
 8914            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8915                s.select(selections)
 8916            });
 8917        });
 8918    }
 8919
 8920    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8921        if self.read_only(cx) {
 8922            return;
 8923        }
 8924        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8925        let selections = self
 8926            .selections
 8927            .all::<usize>(cx)
 8928            .into_iter()
 8929            .map(|s| s.range());
 8930
 8931        self.transact(window, cx, |this, window, cx| {
 8932            this.buffer.update(cx, |buffer, cx| {
 8933                buffer.autoindent_ranges(selections, cx);
 8934            });
 8935            let selections = this.selections.all::<usize>(cx);
 8936            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8937                s.select(selections)
 8938            });
 8939        });
 8940    }
 8941
 8942    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8943        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8944        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8945        let selections = self.selections.all::<Point>(cx);
 8946
 8947        let mut new_cursors = Vec::new();
 8948        let mut edit_ranges = Vec::new();
 8949        let mut selections = selections.iter().peekable();
 8950        while let Some(selection) = selections.next() {
 8951            let mut rows = selection.spanned_rows(false, &display_map);
 8952            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8953
 8954            // Accumulate contiguous regions of rows that we want to delete.
 8955            while let Some(next_selection) = selections.peek() {
 8956                let next_rows = next_selection.spanned_rows(false, &display_map);
 8957                if next_rows.start <= rows.end {
 8958                    rows.end = next_rows.end;
 8959                    selections.next().unwrap();
 8960                } else {
 8961                    break;
 8962                }
 8963            }
 8964
 8965            let buffer = &display_map.buffer_snapshot;
 8966            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8967            let edit_end;
 8968            let cursor_buffer_row;
 8969            if buffer.max_point().row >= rows.end.0 {
 8970                // If there's a line after the range, delete the \n from the end of the row range
 8971                // and position the cursor on the next line.
 8972                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8973                cursor_buffer_row = rows.end;
 8974            } else {
 8975                // If there isn't a line after the range, delete the \n from the line before the
 8976                // start of the row range and position the cursor there.
 8977                edit_start = edit_start.saturating_sub(1);
 8978                edit_end = buffer.len();
 8979                cursor_buffer_row = rows.start.previous_row();
 8980            }
 8981
 8982            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8983            *cursor.column_mut() =
 8984                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8985
 8986            new_cursors.push((
 8987                selection.id,
 8988                buffer.anchor_after(cursor.to_point(&display_map)),
 8989            ));
 8990            edit_ranges.push(edit_start..edit_end);
 8991        }
 8992
 8993        self.transact(window, cx, |this, window, cx| {
 8994            let buffer = this.buffer.update(cx, |buffer, cx| {
 8995                let empty_str: Arc<str> = Arc::default();
 8996                buffer.edit(
 8997                    edit_ranges
 8998                        .into_iter()
 8999                        .map(|range| (range, empty_str.clone())),
 9000                    None,
 9001                    cx,
 9002                );
 9003                buffer.snapshot(cx)
 9004            });
 9005            let new_selections = new_cursors
 9006                .into_iter()
 9007                .map(|(id, cursor)| {
 9008                    let cursor = cursor.to_point(&buffer);
 9009                    Selection {
 9010                        id,
 9011                        start: cursor,
 9012                        end: cursor,
 9013                        reversed: false,
 9014                        goal: SelectionGoal::None,
 9015                    }
 9016                })
 9017                .collect();
 9018
 9019            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9020                s.select(new_selections);
 9021            });
 9022        });
 9023    }
 9024
 9025    pub fn join_lines_impl(
 9026        &mut self,
 9027        insert_whitespace: bool,
 9028        window: &mut Window,
 9029        cx: &mut Context<Self>,
 9030    ) {
 9031        if self.read_only(cx) {
 9032            return;
 9033        }
 9034        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9035        for selection in self.selections.all::<Point>(cx) {
 9036            let start = MultiBufferRow(selection.start.row);
 9037            // Treat single line selections as if they include the next line. Otherwise this action
 9038            // would do nothing for single line selections individual cursors.
 9039            let end = if selection.start.row == selection.end.row {
 9040                MultiBufferRow(selection.start.row + 1)
 9041            } else {
 9042                MultiBufferRow(selection.end.row)
 9043            };
 9044
 9045            if let Some(last_row_range) = row_ranges.last_mut() {
 9046                if start <= last_row_range.end {
 9047                    last_row_range.end = end;
 9048                    continue;
 9049                }
 9050            }
 9051            row_ranges.push(start..end);
 9052        }
 9053
 9054        let snapshot = self.buffer.read(cx).snapshot(cx);
 9055        let mut cursor_positions = Vec::new();
 9056        for row_range in &row_ranges {
 9057            let anchor = snapshot.anchor_before(Point::new(
 9058                row_range.end.previous_row().0,
 9059                snapshot.line_len(row_range.end.previous_row()),
 9060            ));
 9061            cursor_positions.push(anchor..anchor);
 9062        }
 9063
 9064        self.transact(window, cx, |this, window, cx| {
 9065            for row_range in row_ranges.into_iter().rev() {
 9066                for row in row_range.iter_rows().rev() {
 9067                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9068                    let next_line_row = row.next_row();
 9069                    let indent = snapshot.indent_size_for_line(next_line_row);
 9070                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9071
 9072                    let replace =
 9073                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9074                            " "
 9075                        } else {
 9076                            ""
 9077                        };
 9078
 9079                    this.buffer.update(cx, |buffer, cx| {
 9080                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9081                    });
 9082                }
 9083            }
 9084
 9085            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9086                s.select_anchor_ranges(cursor_positions)
 9087            });
 9088        });
 9089    }
 9090
 9091    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9092        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9093        self.join_lines_impl(true, window, cx);
 9094    }
 9095
 9096    pub fn sort_lines_case_sensitive(
 9097        &mut self,
 9098        _: &SortLinesCaseSensitive,
 9099        window: &mut Window,
 9100        cx: &mut Context<Self>,
 9101    ) {
 9102        self.manipulate_lines(window, cx, |lines| lines.sort())
 9103    }
 9104
 9105    pub fn sort_lines_case_insensitive(
 9106        &mut self,
 9107        _: &SortLinesCaseInsensitive,
 9108        window: &mut Window,
 9109        cx: &mut Context<Self>,
 9110    ) {
 9111        self.manipulate_lines(window, cx, |lines| {
 9112            lines.sort_by_key(|line| line.to_lowercase())
 9113        })
 9114    }
 9115
 9116    pub fn unique_lines_case_insensitive(
 9117        &mut self,
 9118        _: &UniqueLinesCaseInsensitive,
 9119        window: &mut Window,
 9120        cx: &mut Context<Self>,
 9121    ) {
 9122        self.manipulate_lines(window, cx, |lines| {
 9123            let mut seen = HashSet::default();
 9124            lines.retain(|line| seen.insert(line.to_lowercase()));
 9125        })
 9126    }
 9127
 9128    pub fn unique_lines_case_sensitive(
 9129        &mut self,
 9130        _: &UniqueLinesCaseSensitive,
 9131        window: &mut Window,
 9132        cx: &mut Context<Self>,
 9133    ) {
 9134        self.manipulate_lines(window, cx, |lines| {
 9135            let mut seen = HashSet::default();
 9136            lines.retain(|line| seen.insert(*line));
 9137        })
 9138    }
 9139
 9140    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9141        let Some(project) = self.project.clone() else {
 9142            return;
 9143        };
 9144        self.reload(project, window, cx)
 9145            .detach_and_notify_err(window, cx);
 9146    }
 9147
 9148    pub fn restore_file(
 9149        &mut self,
 9150        _: &::git::RestoreFile,
 9151        window: &mut Window,
 9152        cx: &mut Context<Self>,
 9153    ) {
 9154        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9155        let mut buffer_ids = HashSet::default();
 9156        let snapshot = self.buffer().read(cx).snapshot(cx);
 9157        for selection in self.selections.all::<usize>(cx) {
 9158            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9159        }
 9160
 9161        let buffer = self.buffer().read(cx);
 9162        let ranges = buffer_ids
 9163            .into_iter()
 9164            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9165            .collect::<Vec<_>>();
 9166
 9167        self.restore_hunks_in_ranges(ranges, window, cx);
 9168    }
 9169
 9170    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9171        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9172        let selections = self
 9173            .selections
 9174            .all(cx)
 9175            .into_iter()
 9176            .map(|s| s.range())
 9177            .collect();
 9178        self.restore_hunks_in_ranges(selections, window, cx);
 9179    }
 9180
 9181    pub fn restore_hunks_in_ranges(
 9182        &mut self,
 9183        ranges: Vec<Range<Point>>,
 9184        window: &mut Window,
 9185        cx: &mut Context<Editor>,
 9186    ) {
 9187        let mut revert_changes = HashMap::default();
 9188        let chunk_by = self
 9189            .snapshot(window, cx)
 9190            .hunks_for_ranges(ranges)
 9191            .into_iter()
 9192            .chunk_by(|hunk| hunk.buffer_id);
 9193        for (buffer_id, hunks) in &chunk_by {
 9194            let hunks = hunks.collect::<Vec<_>>();
 9195            for hunk in &hunks {
 9196                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9197            }
 9198            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9199        }
 9200        drop(chunk_by);
 9201        if !revert_changes.is_empty() {
 9202            self.transact(window, cx, |editor, window, cx| {
 9203                editor.restore(revert_changes, window, cx);
 9204            });
 9205        }
 9206    }
 9207
 9208    pub fn open_active_item_in_terminal(
 9209        &mut self,
 9210        _: &OpenInTerminal,
 9211        window: &mut Window,
 9212        cx: &mut Context<Self>,
 9213    ) {
 9214        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9215            let project_path = buffer.read(cx).project_path(cx)?;
 9216            let project = self.project.as_ref()?.read(cx);
 9217            let entry = project.entry_for_path(&project_path, cx)?;
 9218            let parent = match &entry.canonical_path {
 9219                Some(canonical_path) => canonical_path.to_path_buf(),
 9220                None => project.absolute_path(&project_path, cx)?,
 9221            }
 9222            .parent()?
 9223            .to_path_buf();
 9224            Some(parent)
 9225        }) {
 9226            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9227        }
 9228    }
 9229
 9230    fn set_breakpoint_context_menu(
 9231        &mut self,
 9232        display_row: DisplayRow,
 9233        position: Option<Anchor>,
 9234        clicked_point: gpui::Point<Pixels>,
 9235        window: &mut Window,
 9236        cx: &mut Context<Self>,
 9237    ) {
 9238        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9239            return;
 9240        }
 9241        let source = self
 9242            .buffer
 9243            .read(cx)
 9244            .snapshot(cx)
 9245            .anchor_before(Point::new(display_row.0, 0u32));
 9246
 9247        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9248
 9249        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9250            self,
 9251            source,
 9252            clicked_point,
 9253            context_menu,
 9254            window,
 9255            cx,
 9256        );
 9257    }
 9258
 9259    fn add_edit_breakpoint_block(
 9260        &mut self,
 9261        anchor: Anchor,
 9262        breakpoint: &Breakpoint,
 9263        edit_action: BreakpointPromptEditAction,
 9264        window: &mut Window,
 9265        cx: &mut Context<Self>,
 9266    ) {
 9267        let weak_editor = cx.weak_entity();
 9268        let bp_prompt = cx.new(|cx| {
 9269            BreakpointPromptEditor::new(
 9270                weak_editor,
 9271                anchor,
 9272                breakpoint.clone(),
 9273                edit_action,
 9274                window,
 9275                cx,
 9276            )
 9277        });
 9278
 9279        let height = bp_prompt.update(cx, |this, cx| {
 9280            this.prompt
 9281                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9282        });
 9283        let cloned_prompt = bp_prompt.clone();
 9284        let blocks = vec![BlockProperties {
 9285            style: BlockStyle::Sticky,
 9286            placement: BlockPlacement::Above(anchor),
 9287            height: Some(height),
 9288            render: Arc::new(move |cx| {
 9289                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9290                cloned_prompt.clone().into_any_element()
 9291            }),
 9292            priority: 0,
 9293        }];
 9294
 9295        let focus_handle = bp_prompt.focus_handle(cx);
 9296        window.focus(&focus_handle);
 9297
 9298        let block_ids = self.insert_blocks(blocks, None, cx);
 9299        bp_prompt.update(cx, |prompt, _| {
 9300            prompt.add_block_ids(block_ids);
 9301        });
 9302    }
 9303
 9304    pub(crate) fn breakpoint_at_row(
 9305        &self,
 9306        row: u32,
 9307        window: &mut Window,
 9308        cx: &mut Context<Self>,
 9309    ) -> Option<(Anchor, Breakpoint)> {
 9310        let snapshot = self.snapshot(window, cx);
 9311        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9312
 9313        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9314    }
 9315
 9316    pub(crate) fn breakpoint_at_anchor(
 9317        &self,
 9318        breakpoint_position: Anchor,
 9319        snapshot: &EditorSnapshot,
 9320        cx: &mut Context<Self>,
 9321    ) -> Option<(Anchor, Breakpoint)> {
 9322        let project = self.project.clone()?;
 9323
 9324        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9325            snapshot
 9326                .buffer_snapshot
 9327                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9328        })?;
 9329
 9330        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9331        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9332        let buffer_snapshot = buffer.read(cx).snapshot();
 9333
 9334        let row = buffer_snapshot
 9335            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9336            .row;
 9337
 9338        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9339        let anchor_end = snapshot
 9340            .buffer_snapshot
 9341            .anchor_after(Point::new(row, line_len));
 9342
 9343        let bp = self
 9344            .breakpoint_store
 9345            .as_ref()?
 9346            .read_with(cx, |breakpoint_store, cx| {
 9347                breakpoint_store
 9348                    .breakpoints(
 9349                        &buffer,
 9350                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9351                        &buffer_snapshot,
 9352                        cx,
 9353                    )
 9354                    .next()
 9355                    .and_then(|(anchor, bp)| {
 9356                        let breakpoint_row = buffer_snapshot
 9357                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9358                            .row;
 9359
 9360                        if breakpoint_row == row {
 9361                            snapshot
 9362                                .buffer_snapshot
 9363                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9364                                .map(|anchor| (anchor, bp.clone()))
 9365                        } else {
 9366                            None
 9367                        }
 9368                    })
 9369            });
 9370        bp
 9371    }
 9372
 9373    pub fn edit_log_breakpoint(
 9374        &mut self,
 9375        _: &EditLogBreakpoint,
 9376        window: &mut Window,
 9377        cx: &mut Context<Self>,
 9378    ) {
 9379        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9380            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9381                message: None,
 9382                state: BreakpointState::Enabled,
 9383                condition: None,
 9384                hit_condition: None,
 9385            });
 9386
 9387            self.add_edit_breakpoint_block(
 9388                anchor,
 9389                &breakpoint,
 9390                BreakpointPromptEditAction::Log,
 9391                window,
 9392                cx,
 9393            );
 9394        }
 9395    }
 9396
 9397    fn breakpoints_at_cursors(
 9398        &self,
 9399        window: &mut Window,
 9400        cx: &mut Context<Self>,
 9401    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9402        let snapshot = self.snapshot(window, cx);
 9403        let cursors = self
 9404            .selections
 9405            .disjoint_anchors()
 9406            .into_iter()
 9407            .map(|selection| {
 9408                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9409
 9410                let breakpoint_position = self
 9411                    .breakpoint_at_row(cursor_position.row, window, cx)
 9412                    .map(|bp| bp.0)
 9413                    .unwrap_or_else(|| {
 9414                        snapshot
 9415                            .display_snapshot
 9416                            .buffer_snapshot
 9417                            .anchor_after(Point::new(cursor_position.row, 0))
 9418                    });
 9419
 9420                let breakpoint = self
 9421                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9422                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9423
 9424                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9425            })
 9426            // 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.
 9427            .collect::<HashMap<Anchor, _>>();
 9428
 9429        cursors.into_iter().collect()
 9430    }
 9431
 9432    pub fn enable_breakpoint(
 9433        &mut self,
 9434        _: &crate::actions::EnableBreakpoint,
 9435        window: &mut Window,
 9436        cx: &mut Context<Self>,
 9437    ) {
 9438        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9439            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9440                continue;
 9441            };
 9442            self.edit_breakpoint_at_anchor(
 9443                anchor,
 9444                breakpoint,
 9445                BreakpointEditAction::InvertState,
 9446                cx,
 9447            );
 9448        }
 9449    }
 9450
 9451    pub fn disable_breakpoint(
 9452        &mut self,
 9453        _: &crate::actions::DisableBreakpoint,
 9454        window: &mut Window,
 9455        cx: &mut Context<Self>,
 9456    ) {
 9457        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9458            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9459                continue;
 9460            };
 9461            self.edit_breakpoint_at_anchor(
 9462                anchor,
 9463                breakpoint,
 9464                BreakpointEditAction::InvertState,
 9465                cx,
 9466            );
 9467        }
 9468    }
 9469
 9470    pub fn toggle_breakpoint(
 9471        &mut self,
 9472        _: &crate::actions::ToggleBreakpoint,
 9473        window: &mut Window,
 9474        cx: &mut Context<Self>,
 9475    ) {
 9476        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9477            if let Some(breakpoint) = breakpoint {
 9478                self.edit_breakpoint_at_anchor(
 9479                    anchor,
 9480                    breakpoint,
 9481                    BreakpointEditAction::Toggle,
 9482                    cx,
 9483                );
 9484            } else {
 9485                self.edit_breakpoint_at_anchor(
 9486                    anchor,
 9487                    Breakpoint::new_standard(),
 9488                    BreakpointEditAction::Toggle,
 9489                    cx,
 9490                );
 9491            }
 9492        }
 9493    }
 9494
 9495    pub fn edit_breakpoint_at_anchor(
 9496        &mut self,
 9497        breakpoint_position: Anchor,
 9498        breakpoint: Breakpoint,
 9499        edit_action: BreakpointEditAction,
 9500        cx: &mut Context<Self>,
 9501    ) {
 9502        let Some(breakpoint_store) = &self.breakpoint_store else {
 9503            return;
 9504        };
 9505
 9506        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9507            if breakpoint_position == Anchor::min() {
 9508                self.buffer()
 9509                    .read(cx)
 9510                    .excerpt_buffer_ids()
 9511                    .into_iter()
 9512                    .next()
 9513            } else {
 9514                None
 9515            }
 9516        }) else {
 9517            return;
 9518        };
 9519
 9520        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9521            return;
 9522        };
 9523
 9524        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9525            breakpoint_store.toggle_breakpoint(
 9526                buffer,
 9527                (breakpoint_position.text_anchor, breakpoint),
 9528                edit_action,
 9529                cx,
 9530            );
 9531        });
 9532
 9533        cx.notify();
 9534    }
 9535
 9536    #[cfg(any(test, feature = "test-support"))]
 9537    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9538        self.breakpoint_store.clone()
 9539    }
 9540
 9541    pub fn prepare_restore_change(
 9542        &self,
 9543        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9544        hunk: &MultiBufferDiffHunk,
 9545        cx: &mut App,
 9546    ) -> Option<()> {
 9547        if hunk.is_created_file() {
 9548            return None;
 9549        }
 9550        let buffer = self.buffer.read(cx);
 9551        let diff = buffer.diff_for(hunk.buffer_id)?;
 9552        let buffer = buffer.buffer(hunk.buffer_id)?;
 9553        let buffer = buffer.read(cx);
 9554        let original_text = diff
 9555            .read(cx)
 9556            .base_text()
 9557            .as_rope()
 9558            .slice(hunk.diff_base_byte_range.clone());
 9559        let buffer_snapshot = buffer.snapshot();
 9560        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9561        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9562            probe
 9563                .0
 9564                .start
 9565                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9566                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9567        }) {
 9568            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9569            Some(())
 9570        } else {
 9571            None
 9572        }
 9573    }
 9574
 9575    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9576        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9577    }
 9578
 9579    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9580        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9581    }
 9582
 9583    fn manipulate_lines<Fn>(
 9584        &mut self,
 9585        window: &mut Window,
 9586        cx: &mut Context<Self>,
 9587        mut callback: Fn,
 9588    ) where
 9589        Fn: FnMut(&mut Vec<&str>),
 9590    {
 9591        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9592
 9593        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9594        let buffer = self.buffer.read(cx).snapshot(cx);
 9595
 9596        let mut edits = Vec::new();
 9597
 9598        let selections = self.selections.all::<Point>(cx);
 9599        let mut selections = selections.iter().peekable();
 9600        let mut contiguous_row_selections = Vec::new();
 9601        let mut new_selections = Vec::new();
 9602        let mut added_lines = 0;
 9603        let mut removed_lines = 0;
 9604
 9605        while let Some(selection) = selections.next() {
 9606            let (start_row, end_row) = consume_contiguous_rows(
 9607                &mut contiguous_row_selections,
 9608                selection,
 9609                &display_map,
 9610                &mut selections,
 9611            );
 9612
 9613            let start_point = Point::new(start_row.0, 0);
 9614            let end_point = Point::new(
 9615                end_row.previous_row().0,
 9616                buffer.line_len(end_row.previous_row()),
 9617            );
 9618            let text = buffer
 9619                .text_for_range(start_point..end_point)
 9620                .collect::<String>();
 9621
 9622            let mut lines = text.split('\n').collect_vec();
 9623
 9624            let lines_before = lines.len();
 9625            callback(&mut lines);
 9626            let lines_after = lines.len();
 9627
 9628            edits.push((start_point..end_point, lines.join("\n")));
 9629
 9630            // Selections must change based on added and removed line count
 9631            let start_row =
 9632                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9633            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9634            new_selections.push(Selection {
 9635                id: selection.id,
 9636                start: start_row,
 9637                end: end_row,
 9638                goal: SelectionGoal::None,
 9639                reversed: selection.reversed,
 9640            });
 9641
 9642            if lines_after > lines_before {
 9643                added_lines += lines_after - lines_before;
 9644            } else if lines_before > lines_after {
 9645                removed_lines += lines_before - lines_after;
 9646            }
 9647        }
 9648
 9649        self.transact(window, cx, |this, window, cx| {
 9650            let buffer = this.buffer.update(cx, |buffer, cx| {
 9651                buffer.edit(edits, None, cx);
 9652                buffer.snapshot(cx)
 9653            });
 9654
 9655            // Recalculate offsets on newly edited buffer
 9656            let new_selections = new_selections
 9657                .iter()
 9658                .map(|s| {
 9659                    let start_point = Point::new(s.start.0, 0);
 9660                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9661                    Selection {
 9662                        id: s.id,
 9663                        start: buffer.point_to_offset(start_point),
 9664                        end: buffer.point_to_offset(end_point),
 9665                        goal: s.goal,
 9666                        reversed: s.reversed,
 9667                    }
 9668                })
 9669                .collect();
 9670
 9671            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9672                s.select(new_selections);
 9673            });
 9674
 9675            this.request_autoscroll(Autoscroll::fit(), cx);
 9676        });
 9677    }
 9678
 9679    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9680        self.manipulate_text(window, cx, |text| {
 9681            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9682            if has_upper_case_characters {
 9683                text.to_lowercase()
 9684            } else {
 9685                text.to_uppercase()
 9686            }
 9687        })
 9688    }
 9689
 9690    pub fn convert_to_upper_case(
 9691        &mut self,
 9692        _: &ConvertToUpperCase,
 9693        window: &mut Window,
 9694        cx: &mut Context<Self>,
 9695    ) {
 9696        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9697    }
 9698
 9699    pub fn convert_to_lower_case(
 9700        &mut self,
 9701        _: &ConvertToLowerCase,
 9702        window: &mut Window,
 9703        cx: &mut Context<Self>,
 9704    ) {
 9705        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9706    }
 9707
 9708    pub fn convert_to_title_case(
 9709        &mut self,
 9710        _: &ConvertToTitleCase,
 9711        window: &mut Window,
 9712        cx: &mut Context<Self>,
 9713    ) {
 9714        self.manipulate_text(window, cx, |text| {
 9715            text.split('\n')
 9716                .map(|line| line.to_case(Case::Title))
 9717                .join("\n")
 9718        })
 9719    }
 9720
 9721    pub fn convert_to_snake_case(
 9722        &mut self,
 9723        _: &ConvertToSnakeCase,
 9724        window: &mut Window,
 9725        cx: &mut Context<Self>,
 9726    ) {
 9727        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9728    }
 9729
 9730    pub fn convert_to_kebab_case(
 9731        &mut self,
 9732        _: &ConvertToKebabCase,
 9733        window: &mut Window,
 9734        cx: &mut Context<Self>,
 9735    ) {
 9736        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9737    }
 9738
 9739    pub fn convert_to_upper_camel_case(
 9740        &mut self,
 9741        _: &ConvertToUpperCamelCase,
 9742        window: &mut Window,
 9743        cx: &mut Context<Self>,
 9744    ) {
 9745        self.manipulate_text(window, cx, |text| {
 9746            text.split('\n')
 9747                .map(|line| line.to_case(Case::UpperCamel))
 9748                .join("\n")
 9749        })
 9750    }
 9751
 9752    pub fn convert_to_lower_camel_case(
 9753        &mut self,
 9754        _: &ConvertToLowerCamelCase,
 9755        window: &mut Window,
 9756        cx: &mut Context<Self>,
 9757    ) {
 9758        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9759    }
 9760
 9761    pub fn convert_to_opposite_case(
 9762        &mut self,
 9763        _: &ConvertToOppositeCase,
 9764        window: &mut Window,
 9765        cx: &mut Context<Self>,
 9766    ) {
 9767        self.manipulate_text(window, cx, |text| {
 9768            text.chars()
 9769                .fold(String::with_capacity(text.len()), |mut t, c| {
 9770                    if c.is_uppercase() {
 9771                        t.extend(c.to_lowercase());
 9772                    } else {
 9773                        t.extend(c.to_uppercase());
 9774                    }
 9775                    t
 9776                })
 9777        })
 9778    }
 9779
 9780    pub fn convert_to_rot13(
 9781        &mut self,
 9782        _: &ConvertToRot13,
 9783        window: &mut Window,
 9784        cx: &mut Context<Self>,
 9785    ) {
 9786        self.manipulate_text(window, cx, |text| {
 9787            text.chars()
 9788                .map(|c| match c {
 9789                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9790                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9791                    _ => c,
 9792                })
 9793                .collect()
 9794        })
 9795    }
 9796
 9797    pub fn convert_to_rot47(
 9798        &mut self,
 9799        _: &ConvertToRot47,
 9800        window: &mut Window,
 9801        cx: &mut Context<Self>,
 9802    ) {
 9803        self.manipulate_text(window, cx, |text| {
 9804            text.chars()
 9805                .map(|c| {
 9806                    let code_point = c as u32;
 9807                    if code_point >= 33 && code_point <= 126 {
 9808                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9809                    }
 9810                    c
 9811                })
 9812                .collect()
 9813        })
 9814    }
 9815
 9816    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9817    where
 9818        Fn: FnMut(&str) -> String,
 9819    {
 9820        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9821        let buffer = self.buffer.read(cx).snapshot(cx);
 9822
 9823        let mut new_selections = Vec::new();
 9824        let mut edits = Vec::new();
 9825        let mut selection_adjustment = 0i32;
 9826
 9827        for selection in self.selections.all::<usize>(cx) {
 9828            let selection_is_empty = selection.is_empty();
 9829
 9830            let (start, end) = if selection_is_empty {
 9831                let word_range = movement::surrounding_word(
 9832                    &display_map,
 9833                    selection.start.to_display_point(&display_map),
 9834                );
 9835                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9836                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9837                (start, end)
 9838            } else {
 9839                (selection.start, selection.end)
 9840            };
 9841
 9842            let text = buffer.text_for_range(start..end).collect::<String>();
 9843            let old_length = text.len() as i32;
 9844            let text = callback(&text);
 9845
 9846            new_selections.push(Selection {
 9847                start: (start as i32 - selection_adjustment) as usize,
 9848                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9849                goal: SelectionGoal::None,
 9850                ..selection
 9851            });
 9852
 9853            selection_adjustment += old_length - text.len() as i32;
 9854
 9855            edits.push((start..end, text));
 9856        }
 9857
 9858        self.transact(window, cx, |this, window, cx| {
 9859            this.buffer.update(cx, |buffer, cx| {
 9860                buffer.edit(edits, None, cx);
 9861            });
 9862
 9863            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9864                s.select(new_selections);
 9865            });
 9866
 9867            this.request_autoscroll(Autoscroll::fit(), cx);
 9868        });
 9869    }
 9870
 9871    pub fn duplicate(
 9872        &mut self,
 9873        upwards: bool,
 9874        whole_lines: bool,
 9875        window: &mut Window,
 9876        cx: &mut Context<Self>,
 9877    ) {
 9878        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9879
 9880        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9881        let buffer = &display_map.buffer_snapshot;
 9882        let selections = self.selections.all::<Point>(cx);
 9883
 9884        let mut edits = Vec::new();
 9885        let mut selections_iter = selections.iter().peekable();
 9886        while let Some(selection) = selections_iter.next() {
 9887            let mut rows = selection.spanned_rows(false, &display_map);
 9888            // duplicate line-wise
 9889            if whole_lines || selection.start == selection.end {
 9890                // Avoid duplicating the same lines twice.
 9891                while let Some(next_selection) = selections_iter.peek() {
 9892                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9893                    if next_rows.start < rows.end {
 9894                        rows.end = next_rows.end;
 9895                        selections_iter.next().unwrap();
 9896                    } else {
 9897                        break;
 9898                    }
 9899                }
 9900
 9901                // Copy the text from the selected row region and splice it either at the start
 9902                // or end of the region.
 9903                let start = Point::new(rows.start.0, 0);
 9904                let end = Point::new(
 9905                    rows.end.previous_row().0,
 9906                    buffer.line_len(rows.end.previous_row()),
 9907                );
 9908                let text = buffer
 9909                    .text_for_range(start..end)
 9910                    .chain(Some("\n"))
 9911                    .collect::<String>();
 9912                let insert_location = if upwards {
 9913                    Point::new(rows.end.0, 0)
 9914                } else {
 9915                    start
 9916                };
 9917                edits.push((insert_location..insert_location, text));
 9918            } else {
 9919                // duplicate character-wise
 9920                let start = selection.start;
 9921                let end = selection.end;
 9922                let text = buffer.text_for_range(start..end).collect::<String>();
 9923                edits.push((selection.end..selection.end, text));
 9924            }
 9925        }
 9926
 9927        self.transact(window, cx, |this, _, cx| {
 9928            this.buffer.update(cx, |buffer, cx| {
 9929                buffer.edit(edits, None, cx);
 9930            });
 9931
 9932            this.request_autoscroll(Autoscroll::fit(), cx);
 9933        });
 9934    }
 9935
 9936    pub fn duplicate_line_up(
 9937        &mut self,
 9938        _: &DuplicateLineUp,
 9939        window: &mut Window,
 9940        cx: &mut Context<Self>,
 9941    ) {
 9942        self.duplicate(true, true, window, cx);
 9943    }
 9944
 9945    pub fn duplicate_line_down(
 9946        &mut self,
 9947        _: &DuplicateLineDown,
 9948        window: &mut Window,
 9949        cx: &mut Context<Self>,
 9950    ) {
 9951        self.duplicate(false, true, window, cx);
 9952    }
 9953
 9954    pub fn duplicate_selection(
 9955        &mut self,
 9956        _: &DuplicateSelection,
 9957        window: &mut Window,
 9958        cx: &mut Context<Self>,
 9959    ) {
 9960        self.duplicate(false, false, window, cx);
 9961    }
 9962
 9963    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9964        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9965
 9966        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9967        let buffer = self.buffer.read(cx).snapshot(cx);
 9968
 9969        let mut edits = Vec::new();
 9970        let mut unfold_ranges = Vec::new();
 9971        let mut refold_creases = Vec::new();
 9972
 9973        let selections = self.selections.all::<Point>(cx);
 9974        let mut selections = selections.iter().peekable();
 9975        let mut contiguous_row_selections = Vec::new();
 9976        let mut new_selections = Vec::new();
 9977
 9978        while let Some(selection) = selections.next() {
 9979            // Find all the selections that span a contiguous row range
 9980            let (start_row, end_row) = consume_contiguous_rows(
 9981                &mut contiguous_row_selections,
 9982                selection,
 9983                &display_map,
 9984                &mut selections,
 9985            );
 9986
 9987            // Move the text spanned by the row range to be before the line preceding the row range
 9988            if start_row.0 > 0 {
 9989                let range_to_move = Point::new(
 9990                    start_row.previous_row().0,
 9991                    buffer.line_len(start_row.previous_row()),
 9992                )
 9993                    ..Point::new(
 9994                        end_row.previous_row().0,
 9995                        buffer.line_len(end_row.previous_row()),
 9996                    );
 9997                let insertion_point = display_map
 9998                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9999                    .0;
10000
10001                // Don't move lines across excerpts
10002                if buffer
10003                    .excerpt_containing(insertion_point..range_to_move.end)
10004                    .is_some()
10005                {
10006                    let text = buffer
10007                        .text_for_range(range_to_move.clone())
10008                        .flat_map(|s| s.chars())
10009                        .skip(1)
10010                        .chain(['\n'])
10011                        .collect::<String>();
10012
10013                    edits.push((
10014                        buffer.anchor_after(range_to_move.start)
10015                            ..buffer.anchor_before(range_to_move.end),
10016                        String::new(),
10017                    ));
10018                    let insertion_anchor = buffer.anchor_after(insertion_point);
10019                    edits.push((insertion_anchor..insertion_anchor, text));
10020
10021                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10022
10023                    // Move selections up
10024                    new_selections.extend(contiguous_row_selections.drain(..).map(
10025                        |mut selection| {
10026                            selection.start.row -= row_delta;
10027                            selection.end.row -= row_delta;
10028                            selection
10029                        },
10030                    ));
10031
10032                    // Move folds up
10033                    unfold_ranges.push(range_to_move.clone());
10034                    for fold in display_map.folds_in_range(
10035                        buffer.anchor_before(range_to_move.start)
10036                            ..buffer.anchor_after(range_to_move.end),
10037                    ) {
10038                        let mut start = fold.range.start.to_point(&buffer);
10039                        let mut end = fold.range.end.to_point(&buffer);
10040                        start.row -= row_delta;
10041                        end.row -= row_delta;
10042                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10043                    }
10044                }
10045            }
10046
10047            // If we didn't move line(s), preserve the existing selections
10048            new_selections.append(&mut contiguous_row_selections);
10049        }
10050
10051        self.transact(window, cx, |this, window, cx| {
10052            this.unfold_ranges(&unfold_ranges, true, true, cx);
10053            this.buffer.update(cx, |buffer, cx| {
10054                for (range, text) in edits {
10055                    buffer.edit([(range, text)], None, cx);
10056                }
10057            });
10058            this.fold_creases(refold_creases, true, window, cx);
10059            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10060                s.select(new_selections);
10061            })
10062        });
10063    }
10064
10065    pub fn move_line_down(
10066        &mut self,
10067        _: &MoveLineDown,
10068        window: &mut Window,
10069        cx: &mut Context<Self>,
10070    ) {
10071        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10072
10073        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10074        let buffer = self.buffer.read(cx).snapshot(cx);
10075
10076        let mut edits = Vec::new();
10077        let mut unfold_ranges = Vec::new();
10078        let mut refold_creases = Vec::new();
10079
10080        let selections = self.selections.all::<Point>(cx);
10081        let mut selections = selections.iter().peekable();
10082        let mut contiguous_row_selections = Vec::new();
10083        let mut new_selections = Vec::new();
10084
10085        while let Some(selection) = selections.next() {
10086            // Find all the selections that span a contiguous row range
10087            let (start_row, end_row) = consume_contiguous_rows(
10088                &mut contiguous_row_selections,
10089                selection,
10090                &display_map,
10091                &mut selections,
10092            );
10093
10094            // Move the text spanned by the row range to be after the last line of the row range
10095            if end_row.0 <= buffer.max_point().row {
10096                let range_to_move =
10097                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10098                let insertion_point = display_map
10099                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10100                    .0;
10101
10102                // Don't move lines across excerpt boundaries
10103                if buffer
10104                    .excerpt_containing(range_to_move.start..insertion_point)
10105                    .is_some()
10106                {
10107                    let mut text = String::from("\n");
10108                    text.extend(buffer.text_for_range(range_to_move.clone()));
10109                    text.pop(); // Drop trailing newline
10110                    edits.push((
10111                        buffer.anchor_after(range_to_move.start)
10112                            ..buffer.anchor_before(range_to_move.end),
10113                        String::new(),
10114                    ));
10115                    let insertion_anchor = buffer.anchor_after(insertion_point);
10116                    edits.push((insertion_anchor..insertion_anchor, text));
10117
10118                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10119
10120                    // Move selections down
10121                    new_selections.extend(contiguous_row_selections.drain(..).map(
10122                        |mut selection| {
10123                            selection.start.row += row_delta;
10124                            selection.end.row += row_delta;
10125                            selection
10126                        },
10127                    ));
10128
10129                    // Move folds down
10130                    unfold_ranges.push(range_to_move.clone());
10131                    for fold in display_map.folds_in_range(
10132                        buffer.anchor_before(range_to_move.start)
10133                            ..buffer.anchor_after(range_to_move.end),
10134                    ) {
10135                        let mut start = fold.range.start.to_point(&buffer);
10136                        let mut end = fold.range.end.to_point(&buffer);
10137                        start.row += row_delta;
10138                        end.row += row_delta;
10139                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10140                    }
10141                }
10142            }
10143
10144            // If we didn't move line(s), preserve the existing selections
10145            new_selections.append(&mut contiguous_row_selections);
10146        }
10147
10148        self.transact(window, cx, |this, window, cx| {
10149            this.unfold_ranges(&unfold_ranges, true, true, cx);
10150            this.buffer.update(cx, |buffer, cx| {
10151                for (range, text) in edits {
10152                    buffer.edit([(range, text)], None, cx);
10153                }
10154            });
10155            this.fold_creases(refold_creases, true, window, cx);
10156            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10157                s.select(new_selections)
10158            });
10159        });
10160    }
10161
10162    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10163        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10164        let text_layout_details = &self.text_layout_details(window);
10165        self.transact(window, cx, |this, window, cx| {
10166            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10167                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10168                s.move_with(|display_map, selection| {
10169                    if !selection.is_empty() {
10170                        return;
10171                    }
10172
10173                    let mut head = selection.head();
10174                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10175                    if head.column() == display_map.line_len(head.row()) {
10176                        transpose_offset = display_map
10177                            .buffer_snapshot
10178                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10179                    }
10180
10181                    if transpose_offset == 0 {
10182                        return;
10183                    }
10184
10185                    *head.column_mut() += 1;
10186                    head = display_map.clip_point(head, Bias::Right);
10187                    let goal = SelectionGoal::HorizontalPosition(
10188                        display_map
10189                            .x_for_display_point(head, text_layout_details)
10190                            .into(),
10191                    );
10192                    selection.collapse_to(head, goal);
10193
10194                    let transpose_start = display_map
10195                        .buffer_snapshot
10196                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10197                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10198                        let transpose_end = display_map
10199                            .buffer_snapshot
10200                            .clip_offset(transpose_offset + 1, Bias::Right);
10201                        if let Some(ch) =
10202                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10203                        {
10204                            edits.push((transpose_start..transpose_offset, String::new()));
10205                            edits.push((transpose_end..transpose_end, ch.to_string()));
10206                        }
10207                    }
10208                });
10209                edits
10210            });
10211            this.buffer
10212                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10213            let selections = this.selections.all::<usize>(cx);
10214            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10215                s.select(selections);
10216            });
10217        });
10218    }
10219
10220    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10221        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10222        self.rewrap_impl(RewrapOptions::default(), cx)
10223    }
10224
10225    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10226        let buffer = self.buffer.read(cx).snapshot(cx);
10227        let selections = self.selections.all::<Point>(cx);
10228        let mut selections = selections.iter().peekable();
10229
10230        let mut edits = Vec::new();
10231        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10232
10233        while let Some(selection) = selections.next() {
10234            let mut start_row = selection.start.row;
10235            let mut end_row = selection.end.row;
10236
10237            // Skip selections that overlap with a range that has already been rewrapped.
10238            let selection_range = start_row..end_row;
10239            if rewrapped_row_ranges
10240                .iter()
10241                .any(|range| range.overlaps(&selection_range))
10242            {
10243                continue;
10244            }
10245
10246            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10247
10248            // Since not all lines in the selection may be at the same indent
10249            // level, choose the indent size that is the most common between all
10250            // of the lines.
10251            //
10252            // If there is a tie, we use the deepest indent.
10253            let (indent_size, indent_end) = {
10254                let mut indent_size_occurrences = HashMap::default();
10255                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10256
10257                for row in start_row..=end_row {
10258                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10259                    rows_by_indent_size.entry(indent).or_default().push(row);
10260                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10261                }
10262
10263                let indent_size = indent_size_occurrences
10264                    .into_iter()
10265                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10266                    .map(|(indent, _)| indent)
10267                    .unwrap_or_default();
10268                let row = rows_by_indent_size[&indent_size][0];
10269                let indent_end = Point::new(row, indent_size.len);
10270
10271                (indent_size, indent_end)
10272            };
10273
10274            let mut line_prefix = indent_size.chars().collect::<String>();
10275
10276            let mut inside_comment = false;
10277            if let Some(comment_prefix) =
10278                buffer
10279                    .language_scope_at(selection.head())
10280                    .and_then(|language| {
10281                        language
10282                            .line_comment_prefixes()
10283                            .iter()
10284                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10285                            .cloned()
10286                    })
10287            {
10288                line_prefix.push_str(&comment_prefix);
10289                inside_comment = true;
10290            }
10291
10292            let language_settings = buffer.language_settings_at(selection.head(), cx);
10293            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10294                RewrapBehavior::InComments => inside_comment,
10295                RewrapBehavior::InSelections => !selection.is_empty(),
10296                RewrapBehavior::Anywhere => true,
10297            };
10298
10299            let should_rewrap = options.override_language_settings
10300                || allow_rewrap_based_on_language
10301                || self.hard_wrap.is_some();
10302            if !should_rewrap {
10303                continue;
10304            }
10305
10306            if selection.is_empty() {
10307                'expand_upwards: while start_row > 0 {
10308                    let prev_row = start_row - 1;
10309                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10310                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10311                    {
10312                        start_row = prev_row;
10313                    } else {
10314                        break 'expand_upwards;
10315                    }
10316                }
10317
10318                'expand_downwards: while end_row < buffer.max_point().row {
10319                    let next_row = end_row + 1;
10320                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10321                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10322                    {
10323                        end_row = next_row;
10324                    } else {
10325                        break 'expand_downwards;
10326                    }
10327                }
10328            }
10329
10330            let start = Point::new(start_row, 0);
10331            let start_offset = start.to_offset(&buffer);
10332            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10333            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10334            let Some(lines_without_prefixes) = selection_text
10335                .lines()
10336                .map(|line| {
10337                    line.strip_prefix(&line_prefix)
10338                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10339                        .ok_or_else(|| {
10340                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10341                        })
10342                })
10343                .collect::<Result<Vec<_>, _>>()
10344                .log_err()
10345            else {
10346                continue;
10347            };
10348
10349            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10350                buffer
10351                    .language_settings_at(Point::new(start_row, 0), cx)
10352                    .preferred_line_length as usize
10353            });
10354            let wrapped_text = wrap_with_prefix(
10355                line_prefix,
10356                lines_without_prefixes.join("\n"),
10357                wrap_column,
10358                tab_size,
10359                options.preserve_existing_whitespace,
10360            );
10361
10362            // TODO: should always use char-based diff while still supporting cursor behavior that
10363            // matches vim.
10364            let mut diff_options = DiffOptions::default();
10365            if options.override_language_settings {
10366                diff_options.max_word_diff_len = 0;
10367                diff_options.max_word_diff_line_count = 0;
10368            } else {
10369                diff_options.max_word_diff_len = usize::MAX;
10370                diff_options.max_word_diff_line_count = usize::MAX;
10371            }
10372
10373            for (old_range, new_text) in
10374                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10375            {
10376                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10377                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10378                edits.push((edit_start..edit_end, new_text));
10379            }
10380
10381            rewrapped_row_ranges.push(start_row..=end_row);
10382        }
10383
10384        self.buffer
10385            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10386    }
10387
10388    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10389        let mut text = String::new();
10390        let buffer = self.buffer.read(cx).snapshot(cx);
10391        let mut selections = self.selections.all::<Point>(cx);
10392        let mut clipboard_selections = Vec::with_capacity(selections.len());
10393        {
10394            let max_point = buffer.max_point();
10395            let mut is_first = true;
10396            for selection in &mut selections {
10397                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10398                if is_entire_line {
10399                    selection.start = Point::new(selection.start.row, 0);
10400                    if !selection.is_empty() && selection.end.column == 0 {
10401                        selection.end = cmp::min(max_point, selection.end);
10402                    } else {
10403                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10404                    }
10405                    selection.goal = SelectionGoal::None;
10406                }
10407                if is_first {
10408                    is_first = false;
10409                } else {
10410                    text += "\n";
10411                }
10412                let mut len = 0;
10413                for chunk in buffer.text_for_range(selection.start..selection.end) {
10414                    text.push_str(chunk);
10415                    len += chunk.len();
10416                }
10417                clipboard_selections.push(ClipboardSelection {
10418                    len,
10419                    is_entire_line,
10420                    first_line_indent: buffer
10421                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10422                        .len,
10423                });
10424            }
10425        }
10426
10427        self.transact(window, cx, |this, window, cx| {
10428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10429                s.select(selections);
10430            });
10431            this.insert("", window, cx);
10432        });
10433        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10434    }
10435
10436    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10437        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10438        let item = self.cut_common(window, cx);
10439        cx.write_to_clipboard(item);
10440    }
10441
10442    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10443        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10444        self.change_selections(None, window, cx, |s| {
10445            s.move_with(|snapshot, sel| {
10446                if sel.is_empty() {
10447                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10448                }
10449            });
10450        });
10451        let item = self.cut_common(window, cx);
10452        cx.set_global(KillRing(item))
10453    }
10454
10455    pub fn kill_ring_yank(
10456        &mut self,
10457        _: &KillRingYank,
10458        window: &mut Window,
10459        cx: &mut Context<Self>,
10460    ) {
10461        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10462        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10463            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10464                (kill_ring.text().to_string(), kill_ring.metadata_json())
10465            } else {
10466                return;
10467            }
10468        } else {
10469            return;
10470        };
10471        self.do_paste(&text, metadata, false, window, cx);
10472    }
10473
10474    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10475        self.do_copy(true, cx);
10476    }
10477
10478    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10479        self.do_copy(false, cx);
10480    }
10481
10482    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10483        let selections = self.selections.all::<Point>(cx);
10484        let buffer = self.buffer.read(cx).read(cx);
10485        let mut text = String::new();
10486
10487        let mut clipboard_selections = Vec::with_capacity(selections.len());
10488        {
10489            let max_point = buffer.max_point();
10490            let mut is_first = true;
10491            for selection in &selections {
10492                let mut start = selection.start;
10493                let mut end = selection.end;
10494                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10495                if is_entire_line {
10496                    start = Point::new(start.row, 0);
10497                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10498                }
10499
10500                let mut trimmed_selections = Vec::new();
10501                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10502                    let row = MultiBufferRow(start.row);
10503                    let first_indent = buffer.indent_size_for_line(row);
10504                    if first_indent.len == 0 || start.column > first_indent.len {
10505                        trimmed_selections.push(start..end);
10506                    } else {
10507                        trimmed_selections.push(
10508                            Point::new(row.0, first_indent.len)
10509                                ..Point::new(row.0, buffer.line_len(row)),
10510                        );
10511                        for row in start.row + 1..=end.row {
10512                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10513                            if row == end.row {
10514                                line_len = end.column;
10515                            }
10516                            if line_len == 0 {
10517                                trimmed_selections
10518                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10519                                continue;
10520                            }
10521                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10522                            if row_indent_size.len >= first_indent.len {
10523                                trimmed_selections.push(
10524                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10525                                );
10526                            } else {
10527                                trimmed_selections.clear();
10528                                trimmed_selections.push(start..end);
10529                                break;
10530                            }
10531                        }
10532                    }
10533                } else {
10534                    trimmed_selections.push(start..end);
10535                }
10536
10537                for trimmed_range in trimmed_selections {
10538                    if is_first {
10539                        is_first = false;
10540                    } else {
10541                        text += "\n";
10542                    }
10543                    let mut len = 0;
10544                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10545                        text.push_str(chunk);
10546                        len += chunk.len();
10547                    }
10548                    clipboard_selections.push(ClipboardSelection {
10549                        len,
10550                        is_entire_line,
10551                        first_line_indent: buffer
10552                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10553                            .len,
10554                    });
10555                }
10556            }
10557        }
10558
10559        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10560            text,
10561            clipboard_selections,
10562        ));
10563    }
10564
10565    pub fn do_paste(
10566        &mut self,
10567        text: &String,
10568        clipboard_selections: Option<Vec<ClipboardSelection>>,
10569        handle_entire_lines: bool,
10570        window: &mut Window,
10571        cx: &mut Context<Self>,
10572    ) {
10573        if self.read_only(cx) {
10574            return;
10575        }
10576
10577        let clipboard_text = Cow::Borrowed(text);
10578
10579        self.transact(window, cx, |this, window, cx| {
10580            if let Some(mut clipboard_selections) = clipboard_selections {
10581                let old_selections = this.selections.all::<usize>(cx);
10582                let all_selections_were_entire_line =
10583                    clipboard_selections.iter().all(|s| s.is_entire_line);
10584                let first_selection_indent_column =
10585                    clipboard_selections.first().map(|s| s.first_line_indent);
10586                if clipboard_selections.len() != old_selections.len() {
10587                    clipboard_selections.drain(..);
10588                }
10589                let cursor_offset = this.selections.last::<usize>(cx).head();
10590                let mut auto_indent_on_paste = true;
10591
10592                this.buffer.update(cx, |buffer, cx| {
10593                    let snapshot = buffer.read(cx);
10594                    auto_indent_on_paste = snapshot
10595                        .language_settings_at(cursor_offset, cx)
10596                        .auto_indent_on_paste;
10597
10598                    let mut start_offset = 0;
10599                    let mut edits = Vec::new();
10600                    let mut original_indent_columns = Vec::new();
10601                    for (ix, selection) in old_selections.iter().enumerate() {
10602                        let to_insert;
10603                        let entire_line;
10604                        let original_indent_column;
10605                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10606                            let end_offset = start_offset + clipboard_selection.len;
10607                            to_insert = &clipboard_text[start_offset..end_offset];
10608                            entire_line = clipboard_selection.is_entire_line;
10609                            start_offset = end_offset + 1;
10610                            original_indent_column = Some(clipboard_selection.first_line_indent);
10611                        } else {
10612                            to_insert = clipboard_text.as_str();
10613                            entire_line = all_selections_were_entire_line;
10614                            original_indent_column = first_selection_indent_column
10615                        }
10616
10617                        // If the corresponding selection was empty when this slice of the
10618                        // clipboard text was written, then the entire line containing the
10619                        // selection was copied. If this selection is also currently empty,
10620                        // then paste the line before the current line of the buffer.
10621                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10622                            let column = selection.start.to_point(&snapshot).column as usize;
10623                            let line_start = selection.start - column;
10624                            line_start..line_start
10625                        } else {
10626                            selection.range()
10627                        };
10628
10629                        edits.push((range, to_insert));
10630                        original_indent_columns.push(original_indent_column);
10631                    }
10632                    drop(snapshot);
10633
10634                    buffer.edit(
10635                        edits,
10636                        if auto_indent_on_paste {
10637                            Some(AutoindentMode::Block {
10638                                original_indent_columns,
10639                            })
10640                        } else {
10641                            None
10642                        },
10643                        cx,
10644                    );
10645                });
10646
10647                let selections = this.selections.all::<usize>(cx);
10648                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10649                    s.select(selections)
10650                });
10651            } else {
10652                this.insert(&clipboard_text, window, cx);
10653            }
10654        });
10655    }
10656
10657    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10658        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10659        if let Some(item) = cx.read_from_clipboard() {
10660            let entries = item.entries();
10661
10662            match entries.first() {
10663                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10664                // of all the pasted entries.
10665                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10666                    .do_paste(
10667                        clipboard_string.text(),
10668                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10669                        true,
10670                        window,
10671                        cx,
10672                    ),
10673                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10674            }
10675        }
10676    }
10677
10678    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10679        if self.read_only(cx) {
10680            return;
10681        }
10682
10683        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10684
10685        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10686            if let Some((selections, _)) =
10687                self.selection_history.transaction(transaction_id).cloned()
10688            {
10689                self.change_selections(None, window, cx, |s| {
10690                    s.select_anchors(selections.to_vec());
10691                });
10692            } else {
10693                log::error!(
10694                    "No entry in selection_history found for undo. \
10695                     This may correspond to a bug where undo does not update the selection. \
10696                     If this is occurring, please add details to \
10697                     https://github.com/zed-industries/zed/issues/22692"
10698                );
10699            }
10700            self.request_autoscroll(Autoscroll::fit(), cx);
10701            self.unmark_text(window, cx);
10702            self.refresh_inline_completion(true, false, window, cx);
10703            cx.emit(EditorEvent::Edited { transaction_id });
10704            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10705        }
10706    }
10707
10708    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10709        if self.read_only(cx) {
10710            return;
10711        }
10712
10713        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10714
10715        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10716            if let Some((_, Some(selections))) =
10717                self.selection_history.transaction(transaction_id).cloned()
10718            {
10719                self.change_selections(None, window, cx, |s| {
10720                    s.select_anchors(selections.to_vec());
10721                });
10722            } else {
10723                log::error!(
10724                    "No entry in selection_history found for redo. \
10725                     This may correspond to a bug where undo does not update the selection. \
10726                     If this is occurring, please add details to \
10727                     https://github.com/zed-industries/zed/issues/22692"
10728                );
10729            }
10730            self.request_autoscroll(Autoscroll::fit(), cx);
10731            self.unmark_text(window, cx);
10732            self.refresh_inline_completion(true, false, window, cx);
10733            cx.emit(EditorEvent::Edited { transaction_id });
10734        }
10735    }
10736
10737    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10738        self.buffer
10739            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10740    }
10741
10742    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10743        self.buffer
10744            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10745    }
10746
10747    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10748        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10750            s.move_with(|map, selection| {
10751                let cursor = if selection.is_empty() {
10752                    movement::left(map, selection.start)
10753                } else {
10754                    selection.start
10755                };
10756                selection.collapse_to(cursor, SelectionGoal::None);
10757            });
10758        })
10759    }
10760
10761    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10762        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10763        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10764            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10765        })
10766    }
10767
10768    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10769        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10770        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10771            s.move_with(|map, selection| {
10772                let cursor = if selection.is_empty() {
10773                    movement::right(map, selection.end)
10774                } else {
10775                    selection.end
10776                };
10777                selection.collapse_to(cursor, SelectionGoal::None)
10778            });
10779        })
10780    }
10781
10782    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10783        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10784        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10785            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10786        })
10787    }
10788
10789    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10790        if self.take_rename(true, window, cx).is_some() {
10791            return;
10792        }
10793
10794        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10795            cx.propagate();
10796            return;
10797        }
10798
10799        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10800
10801        let text_layout_details = &self.text_layout_details(window);
10802        let selection_count = self.selections.count();
10803        let first_selection = self.selections.first_anchor();
10804
10805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10806            s.move_with(|map, selection| {
10807                if !selection.is_empty() {
10808                    selection.goal = SelectionGoal::None;
10809                }
10810                let (cursor, goal) = movement::up(
10811                    map,
10812                    selection.start,
10813                    selection.goal,
10814                    false,
10815                    text_layout_details,
10816                );
10817                selection.collapse_to(cursor, goal);
10818            });
10819        });
10820
10821        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10822        {
10823            cx.propagate();
10824        }
10825    }
10826
10827    pub fn move_up_by_lines(
10828        &mut self,
10829        action: &MoveUpByLines,
10830        window: &mut Window,
10831        cx: &mut Context<Self>,
10832    ) {
10833        if self.take_rename(true, window, cx).is_some() {
10834            return;
10835        }
10836
10837        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10838            cx.propagate();
10839            return;
10840        }
10841
10842        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10843
10844        let text_layout_details = &self.text_layout_details(window);
10845
10846        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10847            s.move_with(|map, selection| {
10848                if !selection.is_empty() {
10849                    selection.goal = SelectionGoal::None;
10850                }
10851                let (cursor, goal) = movement::up_by_rows(
10852                    map,
10853                    selection.start,
10854                    action.lines,
10855                    selection.goal,
10856                    false,
10857                    text_layout_details,
10858                );
10859                selection.collapse_to(cursor, goal);
10860            });
10861        })
10862    }
10863
10864    pub fn move_down_by_lines(
10865        &mut self,
10866        action: &MoveDownByLines,
10867        window: &mut Window,
10868        cx: &mut Context<Self>,
10869    ) {
10870        if self.take_rename(true, window, cx).is_some() {
10871            return;
10872        }
10873
10874        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10875            cx.propagate();
10876            return;
10877        }
10878
10879        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10880
10881        let text_layout_details = &self.text_layout_details(window);
10882
10883        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10884            s.move_with(|map, selection| {
10885                if !selection.is_empty() {
10886                    selection.goal = SelectionGoal::None;
10887                }
10888                let (cursor, goal) = movement::down_by_rows(
10889                    map,
10890                    selection.start,
10891                    action.lines,
10892                    selection.goal,
10893                    false,
10894                    text_layout_details,
10895                );
10896                selection.collapse_to(cursor, goal);
10897            });
10898        })
10899    }
10900
10901    pub fn select_down_by_lines(
10902        &mut self,
10903        action: &SelectDownByLines,
10904        window: &mut Window,
10905        cx: &mut Context<Self>,
10906    ) {
10907        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10908        let text_layout_details = &self.text_layout_details(window);
10909        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10910            s.move_heads_with(|map, head, goal| {
10911                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10912            })
10913        })
10914    }
10915
10916    pub fn select_up_by_lines(
10917        &mut self,
10918        action: &SelectUpByLines,
10919        window: &mut Window,
10920        cx: &mut Context<Self>,
10921    ) {
10922        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10923        let text_layout_details = &self.text_layout_details(window);
10924        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10925            s.move_heads_with(|map, head, goal| {
10926                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10927            })
10928        })
10929    }
10930
10931    pub fn select_page_up(
10932        &mut self,
10933        _: &SelectPageUp,
10934        window: &mut Window,
10935        cx: &mut Context<Self>,
10936    ) {
10937        let Some(row_count) = self.visible_row_count() else {
10938            return;
10939        };
10940
10941        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10942
10943        let text_layout_details = &self.text_layout_details(window);
10944
10945        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10946            s.move_heads_with(|map, head, goal| {
10947                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10948            })
10949        })
10950    }
10951
10952    pub fn move_page_up(
10953        &mut self,
10954        action: &MovePageUp,
10955        window: &mut Window,
10956        cx: &mut Context<Self>,
10957    ) {
10958        if self.take_rename(true, window, cx).is_some() {
10959            return;
10960        }
10961
10962        if self
10963            .context_menu
10964            .borrow_mut()
10965            .as_mut()
10966            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10967            .unwrap_or(false)
10968        {
10969            return;
10970        }
10971
10972        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10973            cx.propagate();
10974            return;
10975        }
10976
10977        let Some(row_count) = self.visible_row_count() else {
10978            return;
10979        };
10980
10981        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10982
10983        let autoscroll = if action.center_cursor {
10984            Autoscroll::center()
10985        } else {
10986            Autoscroll::fit()
10987        };
10988
10989        let text_layout_details = &self.text_layout_details(window);
10990
10991        self.change_selections(Some(autoscroll), window, cx, |s| {
10992            s.move_with(|map, selection| {
10993                if !selection.is_empty() {
10994                    selection.goal = SelectionGoal::None;
10995                }
10996                let (cursor, goal) = movement::up_by_rows(
10997                    map,
10998                    selection.end,
10999                    row_count,
11000                    selection.goal,
11001                    false,
11002                    text_layout_details,
11003                );
11004                selection.collapse_to(cursor, goal);
11005            });
11006        });
11007    }
11008
11009    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11010        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11011        let text_layout_details = &self.text_layout_details(window);
11012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11013            s.move_heads_with(|map, head, goal| {
11014                movement::up(map, head, goal, false, text_layout_details)
11015            })
11016        })
11017    }
11018
11019    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11020        self.take_rename(true, window, cx);
11021
11022        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11023            cx.propagate();
11024            return;
11025        }
11026
11027        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11028
11029        let text_layout_details = &self.text_layout_details(window);
11030        let selection_count = self.selections.count();
11031        let first_selection = self.selections.first_anchor();
11032
11033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11034            s.move_with(|map, selection| {
11035                if !selection.is_empty() {
11036                    selection.goal = SelectionGoal::None;
11037                }
11038                let (cursor, goal) = movement::down(
11039                    map,
11040                    selection.end,
11041                    selection.goal,
11042                    false,
11043                    text_layout_details,
11044                );
11045                selection.collapse_to(cursor, goal);
11046            });
11047        });
11048
11049        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11050        {
11051            cx.propagate();
11052        }
11053    }
11054
11055    pub fn select_page_down(
11056        &mut self,
11057        _: &SelectPageDown,
11058        window: &mut Window,
11059        cx: &mut Context<Self>,
11060    ) {
11061        let Some(row_count) = self.visible_row_count() else {
11062            return;
11063        };
11064
11065        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11066
11067        let text_layout_details = &self.text_layout_details(window);
11068
11069        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11070            s.move_heads_with(|map, head, goal| {
11071                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11072            })
11073        })
11074    }
11075
11076    pub fn move_page_down(
11077        &mut self,
11078        action: &MovePageDown,
11079        window: &mut Window,
11080        cx: &mut Context<Self>,
11081    ) {
11082        if self.take_rename(true, window, cx).is_some() {
11083            return;
11084        }
11085
11086        if self
11087            .context_menu
11088            .borrow_mut()
11089            .as_mut()
11090            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11091            .unwrap_or(false)
11092        {
11093            return;
11094        }
11095
11096        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11097            cx.propagate();
11098            return;
11099        }
11100
11101        let Some(row_count) = self.visible_row_count() else {
11102            return;
11103        };
11104
11105        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11106
11107        let autoscroll = if action.center_cursor {
11108            Autoscroll::center()
11109        } else {
11110            Autoscroll::fit()
11111        };
11112
11113        let text_layout_details = &self.text_layout_details(window);
11114        self.change_selections(Some(autoscroll), window, cx, |s| {
11115            s.move_with(|map, selection| {
11116                if !selection.is_empty() {
11117                    selection.goal = SelectionGoal::None;
11118                }
11119                let (cursor, goal) = movement::down_by_rows(
11120                    map,
11121                    selection.end,
11122                    row_count,
11123                    selection.goal,
11124                    false,
11125                    text_layout_details,
11126                );
11127                selection.collapse_to(cursor, goal);
11128            });
11129        });
11130    }
11131
11132    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11133        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11134        let text_layout_details = &self.text_layout_details(window);
11135        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11136            s.move_heads_with(|map, head, goal| {
11137                movement::down(map, head, goal, false, text_layout_details)
11138            })
11139        });
11140    }
11141
11142    pub fn context_menu_first(
11143        &mut self,
11144        _: &ContextMenuFirst,
11145        _window: &mut Window,
11146        cx: &mut Context<Self>,
11147    ) {
11148        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11149            context_menu.select_first(self.completion_provider.as_deref(), cx);
11150        }
11151    }
11152
11153    pub fn context_menu_prev(
11154        &mut self,
11155        _: &ContextMenuPrevious,
11156        _window: &mut Window,
11157        cx: &mut Context<Self>,
11158    ) {
11159        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11160            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11161        }
11162    }
11163
11164    pub fn context_menu_next(
11165        &mut self,
11166        _: &ContextMenuNext,
11167        _window: &mut Window,
11168        cx: &mut Context<Self>,
11169    ) {
11170        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11171            context_menu.select_next(self.completion_provider.as_deref(), cx);
11172        }
11173    }
11174
11175    pub fn context_menu_last(
11176        &mut self,
11177        _: &ContextMenuLast,
11178        _window: &mut Window,
11179        cx: &mut Context<Self>,
11180    ) {
11181        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11182            context_menu.select_last(self.completion_provider.as_deref(), cx);
11183        }
11184    }
11185
11186    pub fn move_to_previous_word_start(
11187        &mut self,
11188        _: &MoveToPreviousWordStart,
11189        window: &mut Window,
11190        cx: &mut Context<Self>,
11191    ) {
11192        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11193        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11194            s.move_cursors_with(|map, head, _| {
11195                (
11196                    movement::previous_word_start(map, head),
11197                    SelectionGoal::None,
11198                )
11199            });
11200        })
11201    }
11202
11203    pub fn move_to_previous_subword_start(
11204        &mut self,
11205        _: &MoveToPreviousSubwordStart,
11206        window: &mut Window,
11207        cx: &mut Context<Self>,
11208    ) {
11209        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11210        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11211            s.move_cursors_with(|map, head, _| {
11212                (
11213                    movement::previous_subword_start(map, head),
11214                    SelectionGoal::None,
11215                )
11216            });
11217        })
11218    }
11219
11220    pub fn select_to_previous_word_start(
11221        &mut self,
11222        _: &SelectToPreviousWordStart,
11223        window: &mut Window,
11224        cx: &mut Context<Self>,
11225    ) {
11226        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11227        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11228            s.move_heads_with(|map, head, _| {
11229                (
11230                    movement::previous_word_start(map, head),
11231                    SelectionGoal::None,
11232                )
11233            });
11234        })
11235    }
11236
11237    pub fn select_to_previous_subword_start(
11238        &mut self,
11239        _: &SelectToPreviousSubwordStart,
11240        window: &mut Window,
11241        cx: &mut Context<Self>,
11242    ) {
11243        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11244        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11245            s.move_heads_with(|map, head, _| {
11246                (
11247                    movement::previous_subword_start(map, head),
11248                    SelectionGoal::None,
11249                )
11250            });
11251        })
11252    }
11253
11254    pub fn delete_to_previous_word_start(
11255        &mut self,
11256        action: &DeleteToPreviousWordStart,
11257        window: &mut Window,
11258        cx: &mut Context<Self>,
11259    ) {
11260        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11261        self.transact(window, cx, |this, window, cx| {
11262            this.select_autoclose_pair(window, cx);
11263            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11264                s.move_with(|map, selection| {
11265                    if selection.is_empty() {
11266                        let cursor = if action.ignore_newlines {
11267                            movement::previous_word_start(map, selection.head())
11268                        } else {
11269                            movement::previous_word_start_or_newline(map, selection.head())
11270                        };
11271                        selection.set_head(cursor, SelectionGoal::None);
11272                    }
11273                });
11274            });
11275            this.insert("", window, cx);
11276        });
11277    }
11278
11279    pub fn delete_to_previous_subword_start(
11280        &mut self,
11281        _: &DeleteToPreviousSubwordStart,
11282        window: &mut Window,
11283        cx: &mut Context<Self>,
11284    ) {
11285        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11286        self.transact(window, cx, |this, window, cx| {
11287            this.select_autoclose_pair(window, cx);
11288            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289                s.move_with(|map, selection| {
11290                    if selection.is_empty() {
11291                        let cursor = movement::previous_subword_start(map, selection.head());
11292                        selection.set_head(cursor, SelectionGoal::None);
11293                    }
11294                });
11295            });
11296            this.insert("", window, cx);
11297        });
11298    }
11299
11300    pub fn move_to_next_word_end(
11301        &mut self,
11302        _: &MoveToNextWordEnd,
11303        window: &mut Window,
11304        cx: &mut Context<Self>,
11305    ) {
11306        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11307        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11308            s.move_cursors_with(|map, head, _| {
11309                (movement::next_word_end(map, head), SelectionGoal::None)
11310            });
11311        })
11312    }
11313
11314    pub fn move_to_next_subword_end(
11315        &mut self,
11316        _: &MoveToNextSubwordEnd,
11317        window: &mut Window,
11318        cx: &mut Context<Self>,
11319    ) {
11320        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11321        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11322            s.move_cursors_with(|map, head, _| {
11323                (movement::next_subword_end(map, head), SelectionGoal::None)
11324            });
11325        })
11326    }
11327
11328    pub fn select_to_next_word_end(
11329        &mut self,
11330        _: &SelectToNextWordEnd,
11331        window: &mut Window,
11332        cx: &mut Context<Self>,
11333    ) {
11334        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11335        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11336            s.move_heads_with(|map, head, _| {
11337                (movement::next_word_end(map, head), SelectionGoal::None)
11338            });
11339        })
11340    }
11341
11342    pub fn select_to_next_subword_end(
11343        &mut self,
11344        _: &SelectToNextSubwordEnd,
11345        window: &mut Window,
11346        cx: &mut Context<Self>,
11347    ) {
11348        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11349        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11350            s.move_heads_with(|map, head, _| {
11351                (movement::next_subword_end(map, head), SelectionGoal::None)
11352            });
11353        })
11354    }
11355
11356    pub fn delete_to_next_word_end(
11357        &mut self,
11358        action: &DeleteToNextWordEnd,
11359        window: &mut Window,
11360        cx: &mut Context<Self>,
11361    ) {
11362        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11363        self.transact(window, cx, |this, window, cx| {
11364            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11365                s.move_with(|map, selection| {
11366                    if selection.is_empty() {
11367                        let cursor = if action.ignore_newlines {
11368                            movement::next_word_end(map, selection.head())
11369                        } else {
11370                            movement::next_word_end_or_newline(map, selection.head())
11371                        };
11372                        selection.set_head(cursor, SelectionGoal::None);
11373                    }
11374                });
11375            });
11376            this.insert("", window, cx);
11377        });
11378    }
11379
11380    pub fn delete_to_next_subword_end(
11381        &mut self,
11382        _: &DeleteToNextSubwordEnd,
11383        window: &mut Window,
11384        cx: &mut Context<Self>,
11385    ) {
11386        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11387        self.transact(window, cx, |this, window, cx| {
11388            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11389                s.move_with(|map, selection| {
11390                    if selection.is_empty() {
11391                        let cursor = movement::next_subword_end(map, selection.head());
11392                        selection.set_head(cursor, SelectionGoal::None);
11393                    }
11394                });
11395            });
11396            this.insert("", window, cx);
11397        });
11398    }
11399
11400    pub fn move_to_beginning_of_line(
11401        &mut self,
11402        action: &MoveToBeginningOfLine,
11403        window: &mut Window,
11404        cx: &mut Context<Self>,
11405    ) {
11406        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11407        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11408            s.move_cursors_with(|map, head, _| {
11409                (
11410                    movement::indented_line_beginning(
11411                        map,
11412                        head,
11413                        action.stop_at_soft_wraps,
11414                        action.stop_at_indent,
11415                    ),
11416                    SelectionGoal::None,
11417                )
11418            });
11419        })
11420    }
11421
11422    pub fn select_to_beginning_of_line(
11423        &mut self,
11424        action: &SelectToBeginningOfLine,
11425        window: &mut Window,
11426        cx: &mut Context<Self>,
11427    ) {
11428        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11429        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11430            s.move_heads_with(|map, head, _| {
11431                (
11432                    movement::indented_line_beginning(
11433                        map,
11434                        head,
11435                        action.stop_at_soft_wraps,
11436                        action.stop_at_indent,
11437                    ),
11438                    SelectionGoal::None,
11439                )
11440            });
11441        });
11442    }
11443
11444    pub fn delete_to_beginning_of_line(
11445        &mut self,
11446        action: &DeleteToBeginningOfLine,
11447        window: &mut Window,
11448        cx: &mut Context<Self>,
11449    ) {
11450        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11451        self.transact(window, cx, |this, window, cx| {
11452            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11453                s.move_with(|_, selection| {
11454                    selection.reversed = true;
11455                });
11456            });
11457
11458            this.select_to_beginning_of_line(
11459                &SelectToBeginningOfLine {
11460                    stop_at_soft_wraps: false,
11461                    stop_at_indent: action.stop_at_indent,
11462                },
11463                window,
11464                cx,
11465            );
11466            this.backspace(&Backspace, window, cx);
11467        });
11468    }
11469
11470    pub fn move_to_end_of_line(
11471        &mut self,
11472        action: &MoveToEndOfLine,
11473        window: &mut Window,
11474        cx: &mut Context<Self>,
11475    ) {
11476        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11477        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11478            s.move_cursors_with(|map, head, _| {
11479                (
11480                    movement::line_end(map, head, action.stop_at_soft_wraps),
11481                    SelectionGoal::None,
11482                )
11483            });
11484        })
11485    }
11486
11487    pub fn select_to_end_of_line(
11488        &mut self,
11489        action: &SelectToEndOfLine,
11490        window: &mut Window,
11491        cx: &mut Context<Self>,
11492    ) {
11493        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11495            s.move_heads_with(|map, head, _| {
11496                (
11497                    movement::line_end(map, head, action.stop_at_soft_wraps),
11498                    SelectionGoal::None,
11499                )
11500            });
11501        })
11502    }
11503
11504    pub fn delete_to_end_of_line(
11505        &mut self,
11506        _: &DeleteToEndOfLine,
11507        window: &mut Window,
11508        cx: &mut Context<Self>,
11509    ) {
11510        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11511        self.transact(window, cx, |this, window, cx| {
11512            this.select_to_end_of_line(
11513                &SelectToEndOfLine {
11514                    stop_at_soft_wraps: false,
11515                },
11516                window,
11517                cx,
11518            );
11519            this.delete(&Delete, window, cx);
11520        });
11521    }
11522
11523    pub fn cut_to_end_of_line(
11524        &mut self,
11525        _: &CutToEndOfLine,
11526        window: &mut Window,
11527        cx: &mut Context<Self>,
11528    ) {
11529        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11530        self.transact(window, cx, |this, window, cx| {
11531            this.select_to_end_of_line(
11532                &SelectToEndOfLine {
11533                    stop_at_soft_wraps: false,
11534                },
11535                window,
11536                cx,
11537            );
11538            this.cut(&Cut, window, cx);
11539        });
11540    }
11541
11542    pub fn move_to_start_of_paragraph(
11543        &mut self,
11544        _: &MoveToStartOfParagraph,
11545        window: &mut Window,
11546        cx: &mut Context<Self>,
11547    ) {
11548        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11549            cx.propagate();
11550            return;
11551        }
11552        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11553        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11554            s.move_with(|map, selection| {
11555                selection.collapse_to(
11556                    movement::start_of_paragraph(map, selection.head(), 1),
11557                    SelectionGoal::None,
11558                )
11559            });
11560        })
11561    }
11562
11563    pub fn move_to_end_of_paragraph(
11564        &mut self,
11565        _: &MoveToEndOfParagraph,
11566        window: &mut Window,
11567        cx: &mut Context<Self>,
11568    ) {
11569        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11570            cx.propagate();
11571            return;
11572        }
11573        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11574        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11575            s.move_with(|map, selection| {
11576                selection.collapse_to(
11577                    movement::end_of_paragraph(map, selection.head(), 1),
11578                    SelectionGoal::None,
11579                )
11580            });
11581        })
11582    }
11583
11584    pub fn select_to_start_of_paragraph(
11585        &mut self,
11586        _: &SelectToStartOfParagraph,
11587        window: &mut Window,
11588        cx: &mut Context<Self>,
11589    ) {
11590        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11591            cx.propagate();
11592            return;
11593        }
11594        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11595        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11596            s.move_heads_with(|map, head, _| {
11597                (
11598                    movement::start_of_paragraph(map, head, 1),
11599                    SelectionGoal::None,
11600                )
11601            });
11602        })
11603    }
11604
11605    pub fn select_to_end_of_paragraph(
11606        &mut self,
11607        _: &SelectToEndOfParagraph,
11608        window: &mut Window,
11609        cx: &mut Context<Self>,
11610    ) {
11611        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11612            cx.propagate();
11613            return;
11614        }
11615        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11616        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11617            s.move_heads_with(|map, head, _| {
11618                (
11619                    movement::end_of_paragraph(map, head, 1),
11620                    SelectionGoal::None,
11621                )
11622            });
11623        })
11624    }
11625
11626    pub fn move_to_start_of_excerpt(
11627        &mut self,
11628        _: &MoveToStartOfExcerpt,
11629        window: &mut Window,
11630        cx: &mut Context<Self>,
11631    ) {
11632        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11633            cx.propagate();
11634            return;
11635        }
11636        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11637        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11638            s.move_with(|map, selection| {
11639                selection.collapse_to(
11640                    movement::start_of_excerpt(
11641                        map,
11642                        selection.head(),
11643                        workspace::searchable::Direction::Prev,
11644                    ),
11645                    SelectionGoal::None,
11646                )
11647            });
11648        })
11649    }
11650
11651    pub fn move_to_start_of_next_excerpt(
11652        &mut self,
11653        _: &MoveToStartOfNextExcerpt,
11654        window: &mut Window,
11655        cx: &mut Context<Self>,
11656    ) {
11657        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11658            cx.propagate();
11659            return;
11660        }
11661
11662        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11663            s.move_with(|map, selection| {
11664                selection.collapse_to(
11665                    movement::start_of_excerpt(
11666                        map,
11667                        selection.head(),
11668                        workspace::searchable::Direction::Next,
11669                    ),
11670                    SelectionGoal::None,
11671                )
11672            });
11673        })
11674    }
11675
11676    pub fn move_to_end_of_excerpt(
11677        &mut self,
11678        _: &MoveToEndOfExcerpt,
11679        window: &mut Window,
11680        cx: &mut Context<Self>,
11681    ) {
11682        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11683            cx.propagate();
11684            return;
11685        }
11686        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11687        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11688            s.move_with(|map, selection| {
11689                selection.collapse_to(
11690                    movement::end_of_excerpt(
11691                        map,
11692                        selection.head(),
11693                        workspace::searchable::Direction::Next,
11694                    ),
11695                    SelectionGoal::None,
11696                )
11697            });
11698        })
11699    }
11700
11701    pub fn move_to_end_of_previous_excerpt(
11702        &mut self,
11703        _: &MoveToEndOfPreviousExcerpt,
11704        window: &mut Window,
11705        cx: &mut Context<Self>,
11706    ) {
11707        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11708            cx.propagate();
11709            return;
11710        }
11711        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11712        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11713            s.move_with(|map, selection| {
11714                selection.collapse_to(
11715                    movement::end_of_excerpt(
11716                        map,
11717                        selection.head(),
11718                        workspace::searchable::Direction::Prev,
11719                    ),
11720                    SelectionGoal::None,
11721                )
11722            });
11723        })
11724    }
11725
11726    pub fn select_to_start_of_excerpt(
11727        &mut self,
11728        _: &SelectToStartOfExcerpt,
11729        window: &mut Window,
11730        cx: &mut Context<Self>,
11731    ) {
11732        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11733            cx.propagate();
11734            return;
11735        }
11736        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11737        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11738            s.move_heads_with(|map, head, _| {
11739                (
11740                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11741                    SelectionGoal::None,
11742                )
11743            });
11744        })
11745    }
11746
11747    pub fn select_to_start_of_next_excerpt(
11748        &mut self,
11749        _: &SelectToStartOfNextExcerpt,
11750        window: &mut Window,
11751        cx: &mut Context<Self>,
11752    ) {
11753        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11754            cx.propagate();
11755            return;
11756        }
11757        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11758        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11759            s.move_heads_with(|map, head, _| {
11760                (
11761                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11762                    SelectionGoal::None,
11763                )
11764            });
11765        })
11766    }
11767
11768    pub fn select_to_end_of_excerpt(
11769        &mut self,
11770        _: &SelectToEndOfExcerpt,
11771        window: &mut Window,
11772        cx: &mut Context<Self>,
11773    ) {
11774        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11775            cx.propagate();
11776            return;
11777        }
11778        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11779        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11780            s.move_heads_with(|map, head, _| {
11781                (
11782                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11783                    SelectionGoal::None,
11784                )
11785            });
11786        })
11787    }
11788
11789    pub fn select_to_end_of_previous_excerpt(
11790        &mut self,
11791        _: &SelectToEndOfPreviousExcerpt,
11792        window: &mut Window,
11793        cx: &mut Context<Self>,
11794    ) {
11795        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11796            cx.propagate();
11797            return;
11798        }
11799        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11800        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11801            s.move_heads_with(|map, head, _| {
11802                (
11803                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11804                    SelectionGoal::None,
11805                )
11806            });
11807        })
11808    }
11809
11810    pub fn move_to_beginning(
11811        &mut self,
11812        _: &MoveToBeginning,
11813        window: &mut Window,
11814        cx: &mut Context<Self>,
11815    ) {
11816        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11817            cx.propagate();
11818            return;
11819        }
11820        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11822            s.select_ranges(vec![0..0]);
11823        });
11824    }
11825
11826    pub fn select_to_beginning(
11827        &mut self,
11828        _: &SelectToBeginning,
11829        window: &mut Window,
11830        cx: &mut Context<Self>,
11831    ) {
11832        let mut selection = self.selections.last::<Point>(cx);
11833        selection.set_head(Point::zero(), SelectionGoal::None);
11834        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11835        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11836            s.select(vec![selection]);
11837        });
11838    }
11839
11840    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11841        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11842            cx.propagate();
11843            return;
11844        }
11845        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11846        let cursor = self.buffer.read(cx).read(cx).len();
11847        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11848            s.select_ranges(vec![cursor..cursor])
11849        });
11850    }
11851
11852    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11853        self.nav_history = nav_history;
11854    }
11855
11856    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11857        self.nav_history.as_ref()
11858    }
11859
11860    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11861        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11862    }
11863
11864    fn push_to_nav_history(
11865        &mut self,
11866        cursor_anchor: Anchor,
11867        new_position: Option<Point>,
11868        is_deactivate: bool,
11869        cx: &mut Context<Self>,
11870    ) {
11871        if let Some(nav_history) = self.nav_history.as_mut() {
11872            let buffer = self.buffer.read(cx).read(cx);
11873            let cursor_position = cursor_anchor.to_point(&buffer);
11874            let scroll_state = self.scroll_manager.anchor();
11875            let scroll_top_row = scroll_state.top_row(&buffer);
11876            drop(buffer);
11877
11878            if let Some(new_position) = new_position {
11879                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11880                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11881                    return;
11882                }
11883            }
11884
11885            nav_history.push(
11886                Some(NavigationData {
11887                    cursor_anchor,
11888                    cursor_position,
11889                    scroll_anchor: scroll_state,
11890                    scroll_top_row,
11891                }),
11892                cx,
11893            );
11894            cx.emit(EditorEvent::PushedToNavHistory {
11895                anchor: cursor_anchor,
11896                is_deactivate,
11897            })
11898        }
11899    }
11900
11901    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11902        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11903        let buffer = self.buffer.read(cx).snapshot(cx);
11904        let mut selection = self.selections.first::<usize>(cx);
11905        selection.set_head(buffer.len(), SelectionGoal::None);
11906        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11907            s.select(vec![selection]);
11908        });
11909    }
11910
11911    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11912        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11913        let end = self.buffer.read(cx).read(cx).len();
11914        self.change_selections(None, window, cx, |s| {
11915            s.select_ranges(vec![0..end]);
11916        });
11917    }
11918
11919    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11920        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11921        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11922        let mut selections = self.selections.all::<Point>(cx);
11923        let max_point = display_map.buffer_snapshot.max_point();
11924        for selection in &mut selections {
11925            let rows = selection.spanned_rows(true, &display_map);
11926            selection.start = Point::new(rows.start.0, 0);
11927            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11928            selection.reversed = false;
11929        }
11930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11931            s.select(selections);
11932        });
11933    }
11934
11935    pub fn split_selection_into_lines(
11936        &mut self,
11937        _: &SplitSelectionIntoLines,
11938        window: &mut Window,
11939        cx: &mut Context<Self>,
11940    ) {
11941        let selections = self
11942            .selections
11943            .all::<Point>(cx)
11944            .into_iter()
11945            .map(|selection| selection.start..selection.end)
11946            .collect::<Vec<_>>();
11947        self.unfold_ranges(&selections, true, true, cx);
11948
11949        let mut new_selection_ranges = Vec::new();
11950        {
11951            let buffer = self.buffer.read(cx).read(cx);
11952            for selection in selections {
11953                for row in selection.start.row..selection.end.row {
11954                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11955                    new_selection_ranges.push(cursor..cursor);
11956                }
11957
11958                let is_multiline_selection = selection.start.row != selection.end.row;
11959                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11960                // so this action feels more ergonomic when paired with other selection operations
11961                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11962                if !should_skip_last {
11963                    new_selection_ranges.push(selection.end..selection.end);
11964                }
11965            }
11966        }
11967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11968            s.select_ranges(new_selection_ranges);
11969        });
11970    }
11971
11972    pub fn add_selection_above(
11973        &mut self,
11974        _: &AddSelectionAbove,
11975        window: &mut Window,
11976        cx: &mut Context<Self>,
11977    ) {
11978        self.add_selection(true, window, cx);
11979    }
11980
11981    pub fn add_selection_below(
11982        &mut self,
11983        _: &AddSelectionBelow,
11984        window: &mut Window,
11985        cx: &mut Context<Self>,
11986    ) {
11987        self.add_selection(false, window, cx);
11988    }
11989
11990    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11991        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11992
11993        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11994        let mut selections = self.selections.all::<Point>(cx);
11995        let text_layout_details = self.text_layout_details(window);
11996        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11997            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11998            let range = oldest_selection.display_range(&display_map).sorted();
11999
12000            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12001            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12002            let positions = start_x.min(end_x)..start_x.max(end_x);
12003
12004            selections.clear();
12005            let mut stack = Vec::new();
12006            for row in range.start.row().0..=range.end.row().0 {
12007                if let Some(selection) = self.selections.build_columnar_selection(
12008                    &display_map,
12009                    DisplayRow(row),
12010                    &positions,
12011                    oldest_selection.reversed,
12012                    &text_layout_details,
12013                ) {
12014                    stack.push(selection.id);
12015                    selections.push(selection);
12016                }
12017            }
12018
12019            if above {
12020                stack.reverse();
12021            }
12022
12023            AddSelectionsState { above, stack }
12024        });
12025
12026        let last_added_selection = *state.stack.last().unwrap();
12027        let mut new_selections = Vec::new();
12028        if above == state.above {
12029            let end_row = if above {
12030                DisplayRow(0)
12031            } else {
12032                display_map.max_point().row()
12033            };
12034
12035            'outer: for selection in selections {
12036                if selection.id == last_added_selection {
12037                    let range = selection.display_range(&display_map).sorted();
12038                    debug_assert_eq!(range.start.row(), range.end.row());
12039                    let mut row = range.start.row();
12040                    let positions =
12041                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12042                            px(start)..px(end)
12043                        } else {
12044                            let start_x =
12045                                display_map.x_for_display_point(range.start, &text_layout_details);
12046                            let end_x =
12047                                display_map.x_for_display_point(range.end, &text_layout_details);
12048                            start_x.min(end_x)..start_x.max(end_x)
12049                        };
12050
12051                    while row != end_row {
12052                        if above {
12053                            row.0 -= 1;
12054                        } else {
12055                            row.0 += 1;
12056                        }
12057
12058                        if let Some(new_selection) = self.selections.build_columnar_selection(
12059                            &display_map,
12060                            row,
12061                            &positions,
12062                            selection.reversed,
12063                            &text_layout_details,
12064                        ) {
12065                            state.stack.push(new_selection.id);
12066                            if above {
12067                                new_selections.push(new_selection);
12068                                new_selections.push(selection);
12069                            } else {
12070                                new_selections.push(selection);
12071                                new_selections.push(new_selection);
12072                            }
12073
12074                            continue 'outer;
12075                        }
12076                    }
12077                }
12078
12079                new_selections.push(selection);
12080            }
12081        } else {
12082            new_selections = selections;
12083            new_selections.retain(|s| s.id != last_added_selection);
12084            state.stack.pop();
12085        }
12086
12087        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12088            s.select(new_selections);
12089        });
12090        if state.stack.len() > 1 {
12091            self.add_selections_state = Some(state);
12092        }
12093    }
12094
12095    fn select_match_ranges(
12096        &mut self,
12097        range: Range<usize>,
12098        reversed: bool,
12099        replace_newest: bool,
12100        auto_scroll: Option<Autoscroll>,
12101        window: &mut Window,
12102        cx: &mut Context<Editor>,
12103    ) {
12104        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12105        self.change_selections(auto_scroll, window, cx, |s| {
12106            if replace_newest {
12107                s.delete(s.newest_anchor().id);
12108            }
12109            if reversed {
12110                s.insert_range(range.end..range.start);
12111            } else {
12112                s.insert_range(range);
12113            }
12114        });
12115    }
12116
12117    pub fn select_next_match_internal(
12118        &mut self,
12119        display_map: &DisplaySnapshot,
12120        replace_newest: bool,
12121        autoscroll: Option<Autoscroll>,
12122        window: &mut Window,
12123        cx: &mut Context<Self>,
12124    ) -> Result<()> {
12125        let buffer = &display_map.buffer_snapshot;
12126        let mut selections = self.selections.all::<usize>(cx);
12127        if let Some(mut select_next_state) = self.select_next_state.take() {
12128            let query = &select_next_state.query;
12129            if !select_next_state.done {
12130                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12131                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12132                let mut next_selected_range = None;
12133
12134                let bytes_after_last_selection =
12135                    buffer.bytes_in_range(last_selection.end..buffer.len());
12136                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12137                let query_matches = query
12138                    .stream_find_iter(bytes_after_last_selection)
12139                    .map(|result| (last_selection.end, result))
12140                    .chain(
12141                        query
12142                            .stream_find_iter(bytes_before_first_selection)
12143                            .map(|result| (0, result)),
12144                    );
12145
12146                for (start_offset, query_match) in query_matches {
12147                    let query_match = query_match.unwrap(); // can only fail due to I/O
12148                    let offset_range =
12149                        start_offset + query_match.start()..start_offset + query_match.end();
12150                    let display_range = offset_range.start.to_display_point(display_map)
12151                        ..offset_range.end.to_display_point(display_map);
12152
12153                    if !select_next_state.wordwise
12154                        || (!movement::is_inside_word(display_map, display_range.start)
12155                            && !movement::is_inside_word(display_map, display_range.end))
12156                    {
12157                        // TODO: This is n^2, because we might check all the selections
12158                        if !selections
12159                            .iter()
12160                            .any(|selection| selection.range().overlaps(&offset_range))
12161                        {
12162                            next_selected_range = Some(offset_range);
12163                            break;
12164                        }
12165                    }
12166                }
12167
12168                if let Some(next_selected_range) = next_selected_range {
12169                    self.select_match_ranges(
12170                        next_selected_range,
12171                        last_selection.reversed,
12172                        replace_newest,
12173                        autoscroll,
12174                        window,
12175                        cx,
12176                    );
12177                } else {
12178                    select_next_state.done = true;
12179                }
12180            }
12181
12182            self.select_next_state = Some(select_next_state);
12183        } else {
12184            let mut only_carets = true;
12185            let mut same_text_selected = true;
12186            let mut selected_text = None;
12187
12188            let mut selections_iter = selections.iter().peekable();
12189            while let Some(selection) = selections_iter.next() {
12190                if selection.start != selection.end {
12191                    only_carets = false;
12192                }
12193
12194                if same_text_selected {
12195                    if selected_text.is_none() {
12196                        selected_text =
12197                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12198                    }
12199
12200                    if let Some(next_selection) = selections_iter.peek() {
12201                        if next_selection.range().len() == selection.range().len() {
12202                            let next_selected_text = buffer
12203                                .text_for_range(next_selection.range())
12204                                .collect::<String>();
12205                            if Some(next_selected_text) != selected_text {
12206                                same_text_selected = false;
12207                                selected_text = None;
12208                            }
12209                        } else {
12210                            same_text_selected = false;
12211                            selected_text = None;
12212                        }
12213                    }
12214                }
12215            }
12216
12217            if only_carets {
12218                for selection in &mut selections {
12219                    let word_range = movement::surrounding_word(
12220                        display_map,
12221                        selection.start.to_display_point(display_map),
12222                    );
12223                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12224                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12225                    selection.goal = SelectionGoal::None;
12226                    selection.reversed = false;
12227                    self.select_match_ranges(
12228                        selection.start..selection.end,
12229                        selection.reversed,
12230                        replace_newest,
12231                        autoscroll,
12232                        window,
12233                        cx,
12234                    );
12235                }
12236
12237                if selections.len() == 1 {
12238                    let selection = selections
12239                        .last()
12240                        .expect("ensured that there's only one selection");
12241                    let query = buffer
12242                        .text_for_range(selection.start..selection.end)
12243                        .collect::<String>();
12244                    let is_empty = query.is_empty();
12245                    let select_state = SelectNextState {
12246                        query: AhoCorasick::new(&[query])?,
12247                        wordwise: true,
12248                        done: is_empty,
12249                    };
12250                    self.select_next_state = Some(select_state);
12251                } else {
12252                    self.select_next_state = None;
12253                }
12254            } else if let Some(selected_text) = selected_text {
12255                self.select_next_state = Some(SelectNextState {
12256                    query: AhoCorasick::new(&[selected_text])?,
12257                    wordwise: false,
12258                    done: false,
12259                });
12260                self.select_next_match_internal(
12261                    display_map,
12262                    replace_newest,
12263                    autoscroll,
12264                    window,
12265                    cx,
12266                )?;
12267            }
12268        }
12269        Ok(())
12270    }
12271
12272    pub fn select_all_matches(
12273        &mut self,
12274        _action: &SelectAllMatches,
12275        window: &mut Window,
12276        cx: &mut Context<Self>,
12277    ) -> Result<()> {
12278        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12279
12280        self.push_to_selection_history();
12281        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12282
12283        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12284        let Some(select_next_state) = self.select_next_state.as_mut() else {
12285            return Ok(());
12286        };
12287        if select_next_state.done {
12288            return Ok(());
12289        }
12290
12291        let mut new_selections = Vec::new();
12292
12293        let reversed = self.selections.oldest::<usize>(cx).reversed;
12294        let buffer = &display_map.buffer_snapshot;
12295        let query_matches = select_next_state
12296            .query
12297            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12298
12299        for query_match in query_matches.into_iter() {
12300            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12301            let offset_range = if reversed {
12302                query_match.end()..query_match.start()
12303            } else {
12304                query_match.start()..query_match.end()
12305            };
12306            let display_range = offset_range.start.to_display_point(&display_map)
12307                ..offset_range.end.to_display_point(&display_map);
12308
12309            if !select_next_state.wordwise
12310                || (!movement::is_inside_word(&display_map, display_range.start)
12311                    && !movement::is_inside_word(&display_map, display_range.end))
12312            {
12313                new_selections.push(offset_range.start..offset_range.end);
12314            }
12315        }
12316
12317        select_next_state.done = true;
12318        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12319        self.change_selections(None, window, cx, |selections| {
12320            selections.select_ranges(new_selections)
12321        });
12322
12323        Ok(())
12324    }
12325
12326    pub fn select_next(
12327        &mut self,
12328        action: &SelectNext,
12329        window: &mut Window,
12330        cx: &mut Context<Self>,
12331    ) -> Result<()> {
12332        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12333        self.push_to_selection_history();
12334        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12335        self.select_next_match_internal(
12336            &display_map,
12337            action.replace_newest,
12338            Some(Autoscroll::newest()),
12339            window,
12340            cx,
12341        )?;
12342        Ok(())
12343    }
12344
12345    pub fn select_previous(
12346        &mut self,
12347        action: &SelectPrevious,
12348        window: &mut Window,
12349        cx: &mut Context<Self>,
12350    ) -> Result<()> {
12351        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12352        self.push_to_selection_history();
12353        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12354        let buffer = &display_map.buffer_snapshot;
12355        let mut selections = self.selections.all::<usize>(cx);
12356        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12357            let query = &select_prev_state.query;
12358            if !select_prev_state.done {
12359                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12360                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12361                let mut next_selected_range = None;
12362                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12363                let bytes_before_last_selection =
12364                    buffer.reversed_bytes_in_range(0..last_selection.start);
12365                let bytes_after_first_selection =
12366                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12367                let query_matches = query
12368                    .stream_find_iter(bytes_before_last_selection)
12369                    .map(|result| (last_selection.start, result))
12370                    .chain(
12371                        query
12372                            .stream_find_iter(bytes_after_first_selection)
12373                            .map(|result| (buffer.len(), result)),
12374                    );
12375                for (end_offset, query_match) in query_matches {
12376                    let query_match = query_match.unwrap(); // can only fail due to I/O
12377                    let offset_range =
12378                        end_offset - query_match.end()..end_offset - query_match.start();
12379                    let display_range = offset_range.start.to_display_point(&display_map)
12380                        ..offset_range.end.to_display_point(&display_map);
12381
12382                    if !select_prev_state.wordwise
12383                        || (!movement::is_inside_word(&display_map, display_range.start)
12384                            && !movement::is_inside_word(&display_map, display_range.end))
12385                    {
12386                        next_selected_range = Some(offset_range);
12387                        break;
12388                    }
12389                }
12390
12391                if let Some(next_selected_range) = next_selected_range {
12392                    self.select_match_ranges(
12393                        next_selected_range,
12394                        last_selection.reversed,
12395                        action.replace_newest,
12396                        Some(Autoscroll::newest()),
12397                        window,
12398                        cx,
12399                    );
12400                } else {
12401                    select_prev_state.done = true;
12402                }
12403            }
12404
12405            self.select_prev_state = Some(select_prev_state);
12406        } else {
12407            let mut only_carets = true;
12408            let mut same_text_selected = true;
12409            let mut selected_text = None;
12410
12411            let mut selections_iter = selections.iter().peekable();
12412            while let Some(selection) = selections_iter.next() {
12413                if selection.start != selection.end {
12414                    only_carets = false;
12415                }
12416
12417                if same_text_selected {
12418                    if selected_text.is_none() {
12419                        selected_text =
12420                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12421                    }
12422
12423                    if let Some(next_selection) = selections_iter.peek() {
12424                        if next_selection.range().len() == selection.range().len() {
12425                            let next_selected_text = buffer
12426                                .text_for_range(next_selection.range())
12427                                .collect::<String>();
12428                            if Some(next_selected_text) != selected_text {
12429                                same_text_selected = false;
12430                                selected_text = None;
12431                            }
12432                        } else {
12433                            same_text_selected = false;
12434                            selected_text = None;
12435                        }
12436                    }
12437                }
12438            }
12439
12440            if only_carets {
12441                for selection in &mut selections {
12442                    let word_range = movement::surrounding_word(
12443                        &display_map,
12444                        selection.start.to_display_point(&display_map),
12445                    );
12446                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12447                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12448                    selection.goal = SelectionGoal::None;
12449                    selection.reversed = false;
12450                    self.select_match_ranges(
12451                        selection.start..selection.end,
12452                        selection.reversed,
12453                        action.replace_newest,
12454                        Some(Autoscroll::newest()),
12455                        window,
12456                        cx,
12457                    );
12458                }
12459                if selections.len() == 1 {
12460                    let selection = selections
12461                        .last()
12462                        .expect("ensured that there's only one selection");
12463                    let query = buffer
12464                        .text_for_range(selection.start..selection.end)
12465                        .collect::<String>();
12466                    let is_empty = query.is_empty();
12467                    let select_state = SelectNextState {
12468                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12469                        wordwise: true,
12470                        done: is_empty,
12471                    };
12472                    self.select_prev_state = Some(select_state);
12473                } else {
12474                    self.select_prev_state = None;
12475                }
12476            } else if let Some(selected_text) = selected_text {
12477                self.select_prev_state = Some(SelectNextState {
12478                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12479                    wordwise: false,
12480                    done: false,
12481                });
12482                self.select_previous(action, window, cx)?;
12483            }
12484        }
12485        Ok(())
12486    }
12487
12488    pub fn find_next_match(
12489        &mut self,
12490        _: &FindNextMatch,
12491        window: &mut Window,
12492        cx: &mut Context<Self>,
12493    ) -> Result<()> {
12494        let selections = self.selections.disjoint_anchors();
12495        match selections.first() {
12496            Some(first) if selections.len() >= 2 => {
12497                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12498                    s.select_ranges([first.range()]);
12499                });
12500            }
12501            _ => self.select_next(
12502                &SelectNext {
12503                    replace_newest: true,
12504                },
12505                window,
12506                cx,
12507            )?,
12508        }
12509        Ok(())
12510    }
12511
12512    pub fn find_previous_match(
12513        &mut self,
12514        _: &FindPreviousMatch,
12515        window: &mut Window,
12516        cx: &mut Context<Self>,
12517    ) -> Result<()> {
12518        let selections = self.selections.disjoint_anchors();
12519        match selections.last() {
12520            Some(last) if selections.len() >= 2 => {
12521                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12522                    s.select_ranges([last.range()]);
12523                });
12524            }
12525            _ => self.select_previous(
12526                &SelectPrevious {
12527                    replace_newest: true,
12528                },
12529                window,
12530                cx,
12531            )?,
12532        }
12533        Ok(())
12534    }
12535
12536    pub fn toggle_comments(
12537        &mut self,
12538        action: &ToggleComments,
12539        window: &mut Window,
12540        cx: &mut Context<Self>,
12541    ) {
12542        if self.read_only(cx) {
12543            return;
12544        }
12545        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12546        let text_layout_details = &self.text_layout_details(window);
12547        self.transact(window, cx, |this, window, cx| {
12548            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12549            let mut edits = Vec::new();
12550            let mut selection_edit_ranges = Vec::new();
12551            let mut last_toggled_row = None;
12552            let snapshot = this.buffer.read(cx).read(cx);
12553            let empty_str: Arc<str> = Arc::default();
12554            let mut suffixes_inserted = Vec::new();
12555            let ignore_indent = action.ignore_indent;
12556
12557            fn comment_prefix_range(
12558                snapshot: &MultiBufferSnapshot,
12559                row: MultiBufferRow,
12560                comment_prefix: &str,
12561                comment_prefix_whitespace: &str,
12562                ignore_indent: bool,
12563            ) -> Range<Point> {
12564                let indent_size = if ignore_indent {
12565                    0
12566                } else {
12567                    snapshot.indent_size_for_line(row).len
12568                };
12569
12570                let start = Point::new(row.0, indent_size);
12571
12572                let mut line_bytes = snapshot
12573                    .bytes_in_range(start..snapshot.max_point())
12574                    .flatten()
12575                    .copied();
12576
12577                // If this line currently begins with the line comment prefix, then record
12578                // the range containing the prefix.
12579                if line_bytes
12580                    .by_ref()
12581                    .take(comment_prefix.len())
12582                    .eq(comment_prefix.bytes())
12583                {
12584                    // Include any whitespace that matches the comment prefix.
12585                    let matching_whitespace_len = line_bytes
12586                        .zip(comment_prefix_whitespace.bytes())
12587                        .take_while(|(a, b)| a == b)
12588                        .count() as u32;
12589                    let end = Point::new(
12590                        start.row,
12591                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12592                    );
12593                    start..end
12594                } else {
12595                    start..start
12596                }
12597            }
12598
12599            fn comment_suffix_range(
12600                snapshot: &MultiBufferSnapshot,
12601                row: MultiBufferRow,
12602                comment_suffix: &str,
12603                comment_suffix_has_leading_space: bool,
12604            ) -> Range<Point> {
12605                let end = Point::new(row.0, snapshot.line_len(row));
12606                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12607
12608                let mut line_end_bytes = snapshot
12609                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12610                    .flatten()
12611                    .copied();
12612
12613                let leading_space_len = if suffix_start_column > 0
12614                    && line_end_bytes.next() == Some(b' ')
12615                    && comment_suffix_has_leading_space
12616                {
12617                    1
12618                } else {
12619                    0
12620                };
12621
12622                // If this line currently begins with the line comment prefix, then record
12623                // the range containing the prefix.
12624                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12625                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12626                    start..end
12627                } else {
12628                    end..end
12629                }
12630            }
12631
12632            // TODO: Handle selections that cross excerpts
12633            for selection in &mut selections {
12634                let start_column = snapshot
12635                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12636                    .len;
12637                let language = if let Some(language) =
12638                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12639                {
12640                    language
12641                } else {
12642                    continue;
12643                };
12644
12645                selection_edit_ranges.clear();
12646
12647                // If multiple selections contain a given row, avoid processing that
12648                // row more than once.
12649                let mut start_row = MultiBufferRow(selection.start.row);
12650                if last_toggled_row == Some(start_row) {
12651                    start_row = start_row.next_row();
12652                }
12653                let end_row =
12654                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12655                        MultiBufferRow(selection.end.row - 1)
12656                    } else {
12657                        MultiBufferRow(selection.end.row)
12658                    };
12659                last_toggled_row = Some(end_row);
12660
12661                if start_row > end_row {
12662                    continue;
12663                }
12664
12665                // If the language has line comments, toggle those.
12666                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12667
12668                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12669                if ignore_indent {
12670                    full_comment_prefixes = full_comment_prefixes
12671                        .into_iter()
12672                        .map(|s| Arc::from(s.trim_end()))
12673                        .collect();
12674                }
12675
12676                if !full_comment_prefixes.is_empty() {
12677                    let first_prefix = full_comment_prefixes
12678                        .first()
12679                        .expect("prefixes is non-empty");
12680                    let prefix_trimmed_lengths = full_comment_prefixes
12681                        .iter()
12682                        .map(|p| p.trim_end_matches(' ').len())
12683                        .collect::<SmallVec<[usize; 4]>>();
12684
12685                    let mut all_selection_lines_are_comments = true;
12686
12687                    for row in start_row.0..=end_row.0 {
12688                        let row = MultiBufferRow(row);
12689                        if start_row < end_row && snapshot.is_line_blank(row) {
12690                            continue;
12691                        }
12692
12693                        let prefix_range = full_comment_prefixes
12694                            .iter()
12695                            .zip(prefix_trimmed_lengths.iter().copied())
12696                            .map(|(prefix, trimmed_prefix_len)| {
12697                                comment_prefix_range(
12698                                    snapshot.deref(),
12699                                    row,
12700                                    &prefix[..trimmed_prefix_len],
12701                                    &prefix[trimmed_prefix_len..],
12702                                    ignore_indent,
12703                                )
12704                            })
12705                            .max_by_key(|range| range.end.column - range.start.column)
12706                            .expect("prefixes is non-empty");
12707
12708                        if prefix_range.is_empty() {
12709                            all_selection_lines_are_comments = false;
12710                        }
12711
12712                        selection_edit_ranges.push(prefix_range);
12713                    }
12714
12715                    if all_selection_lines_are_comments {
12716                        edits.extend(
12717                            selection_edit_ranges
12718                                .iter()
12719                                .cloned()
12720                                .map(|range| (range, empty_str.clone())),
12721                        );
12722                    } else {
12723                        let min_column = selection_edit_ranges
12724                            .iter()
12725                            .map(|range| range.start.column)
12726                            .min()
12727                            .unwrap_or(0);
12728                        edits.extend(selection_edit_ranges.iter().map(|range| {
12729                            let position = Point::new(range.start.row, min_column);
12730                            (position..position, first_prefix.clone())
12731                        }));
12732                    }
12733                } else if let Some((full_comment_prefix, comment_suffix)) =
12734                    language.block_comment_delimiters()
12735                {
12736                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12737                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12738                    let prefix_range = comment_prefix_range(
12739                        snapshot.deref(),
12740                        start_row,
12741                        comment_prefix,
12742                        comment_prefix_whitespace,
12743                        ignore_indent,
12744                    );
12745                    let suffix_range = comment_suffix_range(
12746                        snapshot.deref(),
12747                        end_row,
12748                        comment_suffix.trim_start_matches(' '),
12749                        comment_suffix.starts_with(' '),
12750                    );
12751
12752                    if prefix_range.is_empty() || suffix_range.is_empty() {
12753                        edits.push((
12754                            prefix_range.start..prefix_range.start,
12755                            full_comment_prefix.clone(),
12756                        ));
12757                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12758                        suffixes_inserted.push((end_row, comment_suffix.len()));
12759                    } else {
12760                        edits.push((prefix_range, empty_str.clone()));
12761                        edits.push((suffix_range, empty_str.clone()));
12762                    }
12763                } else {
12764                    continue;
12765                }
12766            }
12767
12768            drop(snapshot);
12769            this.buffer.update(cx, |buffer, cx| {
12770                buffer.edit(edits, None, cx);
12771            });
12772
12773            // Adjust selections so that they end before any comment suffixes that
12774            // were inserted.
12775            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12776            let mut selections = this.selections.all::<Point>(cx);
12777            let snapshot = this.buffer.read(cx).read(cx);
12778            for selection in &mut selections {
12779                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12780                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12781                        Ordering::Less => {
12782                            suffixes_inserted.next();
12783                            continue;
12784                        }
12785                        Ordering::Greater => break,
12786                        Ordering::Equal => {
12787                            if selection.end.column == snapshot.line_len(row) {
12788                                if selection.is_empty() {
12789                                    selection.start.column -= suffix_len as u32;
12790                                }
12791                                selection.end.column -= suffix_len as u32;
12792                            }
12793                            break;
12794                        }
12795                    }
12796                }
12797            }
12798
12799            drop(snapshot);
12800            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12801                s.select(selections)
12802            });
12803
12804            let selections = this.selections.all::<Point>(cx);
12805            let selections_on_single_row = selections.windows(2).all(|selections| {
12806                selections[0].start.row == selections[1].start.row
12807                    && selections[0].end.row == selections[1].end.row
12808                    && selections[0].start.row == selections[0].end.row
12809            });
12810            let selections_selecting = selections
12811                .iter()
12812                .any(|selection| selection.start != selection.end);
12813            let advance_downwards = action.advance_downwards
12814                && selections_on_single_row
12815                && !selections_selecting
12816                && !matches!(this.mode, EditorMode::SingleLine { .. });
12817
12818            if advance_downwards {
12819                let snapshot = this.buffer.read(cx).snapshot(cx);
12820
12821                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12822                    s.move_cursors_with(|display_snapshot, display_point, _| {
12823                        let mut point = display_point.to_point(display_snapshot);
12824                        point.row += 1;
12825                        point = snapshot.clip_point(point, Bias::Left);
12826                        let display_point = point.to_display_point(display_snapshot);
12827                        let goal = SelectionGoal::HorizontalPosition(
12828                            display_snapshot
12829                                .x_for_display_point(display_point, text_layout_details)
12830                                .into(),
12831                        );
12832                        (display_point, goal)
12833                    })
12834                });
12835            }
12836        });
12837    }
12838
12839    pub fn select_enclosing_symbol(
12840        &mut self,
12841        _: &SelectEnclosingSymbol,
12842        window: &mut Window,
12843        cx: &mut Context<Self>,
12844    ) {
12845        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12846
12847        let buffer = self.buffer.read(cx).snapshot(cx);
12848        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12849
12850        fn update_selection(
12851            selection: &Selection<usize>,
12852            buffer_snap: &MultiBufferSnapshot,
12853        ) -> Option<Selection<usize>> {
12854            let cursor = selection.head();
12855            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12856            for symbol in symbols.iter().rev() {
12857                let start = symbol.range.start.to_offset(buffer_snap);
12858                let end = symbol.range.end.to_offset(buffer_snap);
12859                let new_range = start..end;
12860                if start < selection.start || end > selection.end {
12861                    return Some(Selection {
12862                        id: selection.id,
12863                        start: new_range.start,
12864                        end: new_range.end,
12865                        goal: SelectionGoal::None,
12866                        reversed: selection.reversed,
12867                    });
12868                }
12869            }
12870            None
12871        }
12872
12873        let mut selected_larger_symbol = false;
12874        let new_selections = old_selections
12875            .iter()
12876            .map(|selection| match update_selection(selection, &buffer) {
12877                Some(new_selection) => {
12878                    if new_selection.range() != selection.range() {
12879                        selected_larger_symbol = true;
12880                    }
12881                    new_selection
12882                }
12883                None => selection.clone(),
12884            })
12885            .collect::<Vec<_>>();
12886
12887        if selected_larger_symbol {
12888            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12889                s.select(new_selections);
12890            });
12891        }
12892    }
12893
12894    pub fn select_larger_syntax_node(
12895        &mut self,
12896        _: &SelectLargerSyntaxNode,
12897        window: &mut Window,
12898        cx: &mut Context<Self>,
12899    ) {
12900        let Some(visible_row_count) = self.visible_row_count() else {
12901            return;
12902        };
12903        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12904        if old_selections.is_empty() {
12905            return;
12906        }
12907
12908        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12909
12910        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12911        let buffer = self.buffer.read(cx).snapshot(cx);
12912
12913        let mut selected_larger_node = false;
12914        let mut new_selections = old_selections
12915            .iter()
12916            .map(|selection| {
12917                let old_range = selection.start..selection.end;
12918
12919                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12920                    // manually select word at selection
12921                    if ["string_content", "inline"].contains(&node.kind()) {
12922                        let word_range = {
12923                            let display_point = buffer
12924                                .offset_to_point(old_range.start)
12925                                .to_display_point(&display_map);
12926                            let Range { start, end } =
12927                                movement::surrounding_word(&display_map, display_point);
12928                            start.to_point(&display_map).to_offset(&buffer)
12929                                ..end.to_point(&display_map).to_offset(&buffer)
12930                        };
12931                        // ignore if word is already selected
12932                        if !word_range.is_empty() && old_range != word_range {
12933                            let last_word_range = {
12934                                let display_point = buffer
12935                                    .offset_to_point(old_range.end)
12936                                    .to_display_point(&display_map);
12937                                let Range { start, end } =
12938                                    movement::surrounding_word(&display_map, display_point);
12939                                start.to_point(&display_map).to_offset(&buffer)
12940                                    ..end.to_point(&display_map).to_offset(&buffer)
12941                            };
12942                            // only select word if start and end point belongs to same word
12943                            if word_range == last_word_range {
12944                                selected_larger_node = true;
12945                                return Selection {
12946                                    id: selection.id,
12947                                    start: word_range.start,
12948                                    end: word_range.end,
12949                                    goal: SelectionGoal::None,
12950                                    reversed: selection.reversed,
12951                                };
12952                            }
12953                        }
12954                    }
12955                }
12956
12957                let mut new_range = old_range.clone();
12958                while let Some((_node, containing_range)) =
12959                    buffer.syntax_ancestor(new_range.clone())
12960                {
12961                    new_range = match containing_range {
12962                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12963                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12964                    };
12965                    if !display_map.intersects_fold(new_range.start)
12966                        && !display_map.intersects_fold(new_range.end)
12967                    {
12968                        break;
12969                    }
12970                }
12971
12972                selected_larger_node |= new_range != old_range;
12973                Selection {
12974                    id: selection.id,
12975                    start: new_range.start,
12976                    end: new_range.end,
12977                    goal: SelectionGoal::None,
12978                    reversed: selection.reversed,
12979                }
12980            })
12981            .collect::<Vec<_>>();
12982
12983        if !selected_larger_node {
12984            return; // don't put this call in the history
12985        }
12986
12987        // scroll based on transformation done to the last selection created by the user
12988        let (last_old, last_new) = old_selections
12989            .last()
12990            .zip(new_selections.last().cloned())
12991            .expect("old_selections isn't empty");
12992
12993        // revert selection
12994        let is_selection_reversed = {
12995            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12996            new_selections.last_mut().expect("checked above").reversed =
12997                should_newest_selection_be_reversed;
12998            should_newest_selection_be_reversed
12999        };
13000
13001        if selected_larger_node {
13002            self.select_syntax_node_history.disable_clearing = true;
13003            self.change_selections(None, window, cx, |s| {
13004                s.select(new_selections.clone());
13005            });
13006            self.select_syntax_node_history.disable_clearing = false;
13007        }
13008
13009        let start_row = last_new.start.to_display_point(&display_map).row().0;
13010        let end_row = last_new.end.to_display_point(&display_map).row().0;
13011        let selection_height = end_row - start_row + 1;
13012        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13013
13014        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13015        let scroll_behavior = if fits_on_the_screen {
13016            self.request_autoscroll(Autoscroll::fit(), cx);
13017            SelectSyntaxNodeScrollBehavior::FitSelection
13018        } else if is_selection_reversed {
13019            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13020            SelectSyntaxNodeScrollBehavior::CursorTop
13021        } else {
13022            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13023            SelectSyntaxNodeScrollBehavior::CursorBottom
13024        };
13025
13026        self.select_syntax_node_history.push((
13027            old_selections,
13028            scroll_behavior,
13029            is_selection_reversed,
13030        ));
13031    }
13032
13033    pub fn select_smaller_syntax_node(
13034        &mut self,
13035        _: &SelectSmallerSyntaxNode,
13036        window: &mut Window,
13037        cx: &mut Context<Self>,
13038    ) {
13039        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13040
13041        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13042            self.select_syntax_node_history.pop()
13043        {
13044            if let Some(selection) = selections.last_mut() {
13045                selection.reversed = is_selection_reversed;
13046            }
13047
13048            self.select_syntax_node_history.disable_clearing = true;
13049            self.change_selections(None, window, cx, |s| {
13050                s.select(selections.to_vec());
13051            });
13052            self.select_syntax_node_history.disable_clearing = false;
13053
13054            match scroll_behavior {
13055                SelectSyntaxNodeScrollBehavior::CursorTop => {
13056                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13057                }
13058                SelectSyntaxNodeScrollBehavior::FitSelection => {
13059                    self.request_autoscroll(Autoscroll::fit(), cx);
13060                }
13061                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13062                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13063                }
13064            }
13065        }
13066    }
13067
13068    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13069        if !EditorSettings::get_global(cx).gutter.runnables {
13070            self.clear_tasks();
13071            return Task::ready(());
13072        }
13073        let project = self.project.as_ref().map(Entity::downgrade);
13074        let task_sources = self.lsp_task_sources(cx);
13075        cx.spawn_in(window, async move |editor, cx| {
13076            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13077            let Some(project) = project.and_then(|p| p.upgrade()) else {
13078                return;
13079            };
13080            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13081                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13082            }) else {
13083                return;
13084            };
13085
13086            let hide_runnables = project
13087                .update(cx, |project, cx| {
13088                    // Do not display any test indicators in non-dev server remote projects.
13089                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13090                })
13091                .unwrap_or(true);
13092            if hide_runnables {
13093                return;
13094            }
13095            let new_rows =
13096                cx.background_spawn({
13097                    let snapshot = display_snapshot.clone();
13098                    async move {
13099                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13100                    }
13101                })
13102                    .await;
13103            let Ok(lsp_tasks) =
13104                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13105            else {
13106                return;
13107            };
13108            let lsp_tasks = lsp_tasks.await;
13109
13110            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13111                lsp_tasks
13112                    .into_iter()
13113                    .flat_map(|(kind, tasks)| {
13114                        tasks.into_iter().filter_map(move |(location, task)| {
13115                            Some((kind.clone(), location?, task))
13116                        })
13117                    })
13118                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13119                        let buffer = location.target.buffer;
13120                        let buffer_snapshot = buffer.read(cx).snapshot();
13121                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13122                            |(excerpt_id, snapshot, _)| {
13123                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13124                                    display_snapshot
13125                                        .buffer_snapshot
13126                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13127                                } else {
13128                                    None
13129                                }
13130                            },
13131                        );
13132                        if let Some(offset) = offset {
13133                            let task_buffer_range =
13134                                location.target.range.to_point(&buffer_snapshot);
13135                            let context_buffer_range =
13136                                task_buffer_range.to_offset(&buffer_snapshot);
13137                            let context_range = BufferOffset(context_buffer_range.start)
13138                                ..BufferOffset(context_buffer_range.end);
13139
13140                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13141                                .or_insert_with(|| RunnableTasks {
13142                                    templates: Vec::new(),
13143                                    offset,
13144                                    column: task_buffer_range.start.column,
13145                                    extra_variables: HashMap::default(),
13146                                    context_range,
13147                                })
13148                                .templates
13149                                .push((kind, task.original_task().clone()));
13150                        }
13151
13152                        acc
13153                    })
13154            }) else {
13155                return;
13156            };
13157
13158            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13159            editor
13160                .update(cx, |editor, _| {
13161                    editor.clear_tasks();
13162                    for (key, mut value) in rows {
13163                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13164                            value.templates.extend(lsp_tasks.templates);
13165                        }
13166
13167                        editor.insert_tasks(key, value);
13168                    }
13169                    for (key, value) in lsp_tasks_by_rows {
13170                        editor.insert_tasks(key, value);
13171                    }
13172                })
13173                .ok();
13174        })
13175    }
13176    fn fetch_runnable_ranges(
13177        snapshot: &DisplaySnapshot,
13178        range: Range<Anchor>,
13179    ) -> Vec<language::RunnableRange> {
13180        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13181    }
13182
13183    fn runnable_rows(
13184        project: Entity<Project>,
13185        snapshot: DisplaySnapshot,
13186        runnable_ranges: Vec<RunnableRange>,
13187        mut cx: AsyncWindowContext,
13188    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13189        runnable_ranges
13190            .into_iter()
13191            .filter_map(|mut runnable| {
13192                let tasks = cx
13193                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13194                    .ok()?;
13195                if tasks.is_empty() {
13196                    return None;
13197                }
13198
13199                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13200
13201                let row = snapshot
13202                    .buffer_snapshot
13203                    .buffer_line_for_row(MultiBufferRow(point.row))?
13204                    .1
13205                    .start
13206                    .row;
13207
13208                let context_range =
13209                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13210                Some((
13211                    (runnable.buffer_id, row),
13212                    RunnableTasks {
13213                        templates: tasks,
13214                        offset: snapshot
13215                            .buffer_snapshot
13216                            .anchor_before(runnable.run_range.start),
13217                        context_range,
13218                        column: point.column,
13219                        extra_variables: runnable.extra_captures,
13220                    },
13221                ))
13222            })
13223            .collect()
13224    }
13225
13226    fn templates_with_tags(
13227        project: &Entity<Project>,
13228        runnable: &mut Runnable,
13229        cx: &mut App,
13230    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13231        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13232            let (worktree_id, file) = project
13233                .buffer_for_id(runnable.buffer, cx)
13234                .and_then(|buffer| buffer.read(cx).file())
13235                .map(|file| (file.worktree_id(cx), file.clone()))
13236                .unzip();
13237
13238            (
13239                project.task_store().read(cx).task_inventory().cloned(),
13240                worktree_id,
13241                file,
13242            )
13243        });
13244
13245        let mut templates_with_tags = mem::take(&mut runnable.tags)
13246            .into_iter()
13247            .flat_map(|RunnableTag(tag)| {
13248                inventory
13249                    .as_ref()
13250                    .into_iter()
13251                    .flat_map(|inventory| {
13252                        inventory.read(cx).list_tasks(
13253                            file.clone(),
13254                            Some(runnable.language.clone()),
13255                            worktree_id,
13256                            cx,
13257                        )
13258                    })
13259                    .filter(move |(_, template)| {
13260                        template.tags.iter().any(|source_tag| source_tag == &tag)
13261                    })
13262            })
13263            .sorted_by_key(|(kind, _)| kind.to_owned())
13264            .collect::<Vec<_>>();
13265        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13266            // Strongest source wins; if we have worktree tag binding, prefer that to
13267            // global and language bindings;
13268            // if we have a global binding, prefer that to language binding.
13269            let first_mismatch = templates_with_tags
13270                .iter()
13271                .position(|(tag_source, _)| tag_source != leading_tag_source);
13272            if let Some(index) = first_mismatch {
13273                templates_with_tags.truncate(index);
13274            }
13275        }
13276
13277        templates_with_tags
13278    }
13279
13280    pub fn move_to_enclosing_bracket(
13281        &mut self,
13282        _: &MoveToEnclosingBracket,
13283        window: &mut Window,
13284        cx: &mut Context<Self>,
13285    ) {
13286        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13287        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13288            s.move_offsets_with(|snapshot, selection| {
13289                let Some(enclosing_bracket_ranges) =
13290                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13291                else {
13292                    return;
13293                };
13294
13295                let mut best_length = usize::MAX;
13296                let mut best_inside = false;
13297                let mut best_in_bracket_range = false;
13298                let mut best_destination = None;
13299                for (open, close) in enclosing_bracket_ranges {
13300                    let close = close.to_inclusive();
13301                    let length = close.end() - open.start;
13302                    let inside = selection.start >= open.end && selection.end <= *close.start();
13303                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13304                        || close.contains(&selection.head());
13305
13306                    // If best is next to a bracket and current isn't, skip
13307                    if !in_bracket_range && best_in_bracket_range {
13308                        continue;
13309                    }
13310
13311                    // Prefer smaller lengths unless best is inside and current isn't
13312                    if length > best_length && (best_inside || !inside) {
13313                        continue;
13314                    }
13315
13316                    best_length = length;
13317                    best_inside = inside;
13318                    best_in_bracket_range = in_bracket_range;
13319                    best_destination = Some(
13320                        if close.contains(&selection.start) && close.contains(&selection.end) {
13321                            if inside { open.end } else { open.start }
13322                        } else if inside {
13323                            *close.start()
13324                        } else {
13325                            *close.end()
13326                        },
13327                    );
13328                }
13329
13330                if let Some(destination) = best_destination {
13331                    selection.collapse_to(destination, SelectionGoal::None);
13332                }
13333            })
13334        });
13335    }
13336
13337    pub fn undo_selection(
13338        &mut self,
13339        _: &UndoSelection,
13340        window: &mut Window,
13341        cx: &mut Context<Self>,
13342    ) {
13343        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13344        self.end_selection(window, cx);
13345        self.selection_history.mode = SelectionHistoryMode::Undoing;
13346        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13347            self.change_selections(None, window, cx, |s| {
13348                s.select_anchors(entry.selections.to_vec())
13349            });
13350            self.select_next_state = entry.select_next_state;
13351            self.select_prev_state = entry.select_prev_state;
13352            self.add_selections_state = entry.add_selections_state;
13353            self.request_autoscroll(Autoscroll::newest(), cx);
13354        }
13355        self.selection_history.mode = SelectionHistoryMode::Normal;
13356    }
13357
13358    pub fn redo_selection(
13359        &mut self,
13360        _: &RedoSelection,
13361        window: &mut Window,
13362        cx: &mut Context<Self>,
13363    ) {
13364        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13365        self.end_selection(window, cx);
13366        self.selection_history.mode = SelectionHistoryMode::Redoing;
13367        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13368            self.change_selections(None, window, cx, |s| {
13369                s.select_anchors(entry.selections.to_vec())
13370            });
13371            self.select_next_state = entry.select_next_state;
13372            self.select_prev_state = entry.select_prev_state;
13373            self.add_selections_state = entry.add_selections_state;
13374            self.request_autoscroll(Autoscroll::newest(), cx);
13375        }
13376        self.selection_history.mode = SelectionHistoryMode::Normal;
13377    }
13378
13379    pub fn expand_excerpts(
13380        &mut self,
13381        action: &ExpandExcerpts,
13382        _: &mut Window,
13383        cx: &mut Context<Self>,
13384    ) {
13385        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13386    }
13387
13388    pub fn expand_excerpts_down(
13389        &mut self,
13390        action: &ExpandExcerptsDown,
13391        _: &mut Window,
13392        cx: &mut Context<Self>,
13393    ) {
13394        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13395    }
13396
13397    pub fn expand_excerpts_up(
13398        &mut self,
13399        action: &ExpandExcerptsUp,
13400        _: &mut Window,
13401        cx: &mut Context<Self>,
13402    ) {
13403        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13404    }
13405
13406    pub fn expand_excerpts_for_direction(
13407        &mut self,
13408        lines: u32,
13409        direction: ExpandExcerptDirection,
13410
13411        cx: &mut Context<Self>,
13412    ) {
13413        let selections = self.selections.disjoint_anchors();
13414
13415        let lines = if lines == 0 {
13416            EditorSettings::get_global(cx).expand_excerpt_lines
13417        } else {
13418            lines
13419        };
13420
13421        self.buffer.update(cx, |buffer, cx| {
13422            let snapshot = buffer.snapshot(cx);
13423            let mut excerpt_ids = selections
13424                .iter()
13425                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13426                .collect::<Vec<_>>();
13427            excerpt_ids.sort();
13428            excerpt_ids.dedup();
13429            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13430        })
13431    }
13432
13433    pub fn expand_excerpt(
13434        &mut self,
13435        excerpt: ExcerptId,
13436        direction: ExpandExcerptDirection,
13437        window: &mut Window,
13438        cx: &mut Context<Self>,
13439    ) {
13440        let current_scroll_position = self.scroll_position(cx);
13441        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13442        let mut should_scroll_up = false;
13443
13444        if direction == ExpandExcerptDirection::Down {
13445            let multi_buffer = self.buffer.read(cx);
13446            let snapshot = multi_buffer.snapshot(cx);
13447            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13448                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13449                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13450                        let buffer_snapshot = buffer.read(cx).snapshot();
13451                        let excerpt_end_row =
13452                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13453                        let last_row = buffer_snapshot.max_point().row;
13454                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13455                        should_scroll_up = lines_below >= lines_to_expand;
13456                    }
13457                }
13458            }
13459        }
13460
13461        self.buffer.update(cx, |buffer, cx| {
13462            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13463        });
13464
13465        if should_scroll_up {
13466            let new_scroll_position =
13467                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13468            self.set_scroll_position(new_scroll_position, window, cx);
13469        }
13470    }
13471
13472    pub fn go_to_singleton_buffer_point(
13473        &mut self,
13474        point: Point,
13475        window: &mut Window,
13476        cx: &mut Context<Self>,
13477    ) {
13478        self.go_to_singleton_buffer_range(point..point, window, cx);
13479    }
13480
13481    pub fn go_to_singleton_buffer_range(
13482        &mut self,
13483        range: Range<Point>,
13484        window: &mut Window,
13485        cx: &mut Context<Self>,
13486    ) {
13487        let multibuffer = self.buffer().read(cx);
13488        let Some(buffer) = multibuffer.as_singleton() else {
13489            return;
13490        };
13491        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13492            return;
13493        };
13494        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13495            return;
13496        };
13497        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13498            s.select_anchor_ranges([start..end])
13499        });
13500    }
13501
13502    pub fn go_to_diagnostic(
13503        &mut self,
13504        _: &GoToDiagnostic,
13505        window: &mut Window,
13506        cx: &mut Context<Self>,
13507    ) {
13508        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13509        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13510    }
13511
13512    pub fn go_to_prev_diagnostic(
13513        &mut self,
13514        _: &GoToPreviousDiagnostic,
13515        window: &mut Window,
13516        cx: &mut Context<Self>,
13517    ) {
13518        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13519        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13520    }
13521
13522    pub fn go_to_diagnostic_impl(
13523        &mut self,
13524        direction: Direction,
13525        window: &mut Window,
13526        cx: &mut Context<Self>,
13527    ) {
13528        let buffer = self.buffer.read(cx).snapshot(cx);
13529        let selection = self.selections.newest::<usize>(cx);
13530
13531        let mut active_group_id = None;
13532        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13533            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13534                active_group_id = Some(active_group.group_id);
13535            }
13536        }
13537
13538        fn filtered(
13539            snapshot: EditorSnapshot,
13540            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13541        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13542            diagnostics
13543                .filter(|entry| entry.range.start != entry.range.end)
13544                .filter(|entry| !entry.diagnostic.is_unnecessary)
13545                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13546        }
13547
13548        let snapshot = self.snapshot(window, cx);
13549        let before = filtered(
13550            snapshot.clone(),
13551            buffer
13552                .diagnostics_in_range(0..selection.start)
13553                .filter(|entry| entry.range.start <= selection.start),
13554        );
13555        let after = filtered(
13556            snapshot,
13557            buffer
13558                .diagnostics_in_range(selection.start..buffer.len())
13559                .filter(|entry| entry.range.start >= selection.start),
13560        );
13561
13562        let mut found: Option<DiagnosticEntry<usize>> = None;
13563        if direction == Direction::Prev {
13564            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13565            {
13566                for diagnostic in prev_diagnostics.into_iter().rev() {
13567                    if diagnostic.range.start != selection.start
13568                        || active_group_id
13569                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13570                    {
13571                        found = Some(diagnostic);
13572                        break 'outer;
13573                    }
13574                }
13575            }
13576        } else {
13577            for diagnostic in after.chain(before) {
13578                if diagnostic.range.start != selection.start
13579                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13580                {
13581                    found = Some(diagnostic);
13582                    break;
13583                }
13584            }
13585        }
13586        let Some(next_diagnostic) = found else {
13587            return;
13588        };
13589
13590        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13591            return;
13592        };
13593        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13594            s.select_ranges(vec![
13595                next_diagnostic.range.start..next_diagnostic.range.start,
13596            ])
13597        });
13598        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13599        self.refresh_inline_completion(false, true, window, cx);
13600    }
13601
13602    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13603        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13604        let snapshot = self.snapshot(window, cx);
13605        let selection = self.selections.newest::<Point>(cx);
13606        self.go_to_hunk_before_or_after_position(
13607            &snapshot,
13608            selection.head(),
13609            Direction::Next,
13610            window,
13611            cx,
13612        );
13613    }
13614
13615    pub fn go_to_hunk_before_or_after_position(
13616        &mut self,
13617        snapshot: &EditorSnapshot,
13618        position: Point,
13619        direction: Direction,
13620        window: &mut Window,
13621        cx: &mut Context<Editor>,
13622    ) {
13623        let row = if direction == Direction::Next {
13624            self.hunk_after_position(snapshot, position)
13625                .map(|hunk| hunk.row_range.start)
13626        } else {
13627            self.hunk_before_position(snapshot, position)
13628        };
13629
13630        if let Some(row) = row {
13631            let destination = Point::new(row.0, 0);
13632            let autoscroll = Autoscroll::center();
13633
13634            self.unfold_ranges(&[destination..destination], false, false, cx);
13635            self.change_selections(Some(autoscroll), window, cx, |s| {
13636                s.select_ranges([destination..destination]);
13637            });
13638        }
13639    }
13640
13641    fn hunk_after_position(
13642        &mut self,
13643        snapshot: &EditorSnapshot,
13644        position: Point,
13645    ) -> Option<MultiBufferDiffHunk> {
13646        snapshot
13647            .buffer_snapshot
13648            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13649            .find(|hunk| hunk.row_range.start.0 > position.row)
13650            .or_else(|| {
13651                snapshot
13652                    .buffer_snapshot
13653                    .diff_hunks_in_range(Point::zero()..position)
13654                    .find(|hunk| hunk.row_range.end.0 < position.row)
13655            })
13656    }
13657
13658    fn go_to_prev_hunk(
13659        &mut self,
13660        _: &GoToPreviousHunk,
13661        window: &mut Window,
13662        cx: &mut Context<Self>,
13663    ) {
13664        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13665        let snapshot = self.snapshot(window, cx);
13666        let selection = self.selections.newest::<Point>(cx);
13667        self.go_to_hunk_before_or_after_position(
13668            &snapshot,
13669            selection.head(),
13670            Direction::Prev,
13671            window,
13672            cx,
13673        );
13674    }
13675
13676    fn hunk_before_position(
13677        &mut self,
13678        snapshot: &EditorSnapshot,
13679        position: Point,
13680    ) -> Option<MultiBufferRow> {
13681        snapshot
13682            .buffer_snapshot
13683            .diff_hunk_before(position)
13684            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13685    }
13686
13687    fn go_to_next_change(
13688        &mut self,
13689        _: &GoToNextChange,
13690        window: &mut Window,
13691        cx: &mut Context<Self>,
13692    ) {
13693        if let Some(selections) = self
13694            .change_list
13695            .next_change(1, Direction::Next)
13696            .map(|s| s.to_vec())
13697        {
13698            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13699                let map = s.display_map();
13700                s.select_display_ranges(selections.iter().map(|a| {
13701                    let point = a.to_display_point(&map);
13702                    point..point
13703                }))
13704            })
13705        }
13706    }
13707
13708    fn go_to_previous_change(
13709        &mut self,
13710        _: &GoToPreviousChange,
13711        window: &mut Window,
13712        cx: &mut Context<Self>,
13713    ) {
13714        if let Some(selections) = self
13715            .change_list
13716            .next_change(1, Direction::Prev)
13717            .map(|s| s.to_vec())
13718        {
13719            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13720                let map = s.display_map();
13721                s.select_display_ranges(selections.iter().map(|a| {
13722                    let point = a.to_display_point(&map);
13723                    point..point
13724                }))
13725            })
13726        }
13727    }
13728
13729    fn go_to_line<T: 'static>(
13730        &mut self,
13731        position: Anchor,
13732        highlight_color: Option<Hsla>,
13733        window: &mut Window,
13734        cx: &mut Context<Self>,
13735    ) {
13736        let snapshot = self.snapshot(window, cx).display_snapshot;
13737        let position = position.to_point(&snapshot.buffer_snapshot);
13738        let start = snapshot
13739            .buffer_snapshot
13740            .clip_point(Point::new(position.row, 0), Bias::Left);
13741        let end = start + Point::new(1, 0);
13742        let start = snapshot.buffer_snapshot.anchor_before(start);
13743        let end = snapshot.buffer_snapshot.anchor_before(end);
13744
13745        self.highlight_rows::<T>(
13746            start..end,
13747            highlight_color
13748                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13749            Default::default(),
13750            cx,
13751        );
13752        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13753    }
13754
13755    pub fn go_to_definition(
13756        &mut self,
13757        _: &GoToDefinition,
13758        window: &mut Window,
13759        cx: &mut Context<Self>,
13760    ) -> Task<Result<Navigated>> {
13761        let definition =
13762            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13763        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13764        cx.spawn_in(window, async move |editor, cx| {
13765            if definition.await? == Navigated::Yes {
13766                return Ok(Navigated::Yes);
13767            }
13768            match fallback_strategy {
13769                GoToDefinitionFallback::None => Ok(Navigated::No),
13770                GoToDefinitionFallback::FindAllReferences => {
13771                    match editor.update_in(cx, |editor, window, cx| {
13772                        editor.find_all_references(&FindAllReferences, window, cx)
13773                    })? {
13774                        Some(references) => references.await,
13775                        None => Ok(Navigated::No),
13776                    }
13777                }
13778            }
13779        })
13780    }
13781
13782    pub fn go_to_declaration(
13783        &mut self,
13784        _: &GoToDeclaration,
13785        window: &mut Window,
13786        cx: &mut Context<Self>,
13787    ) -> Task<Result<Navigated>> {
13788        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13789    }
13790
13791    pub fn go_to_declaration_split(
13792        &mut self,
13793        _: &GoToDeclaration,
13794        window: &mut Window,
13795        cx: &mut Context<Self>,
13796    ) -> Task<Result<Navigated>> {
13797        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13798    }
13799
13800    pub fn go_to_implementation(
13801        &mut self,
13802        _: &GoToImplementation,
13803        window: &mut Window,
13804        cx: &mut Context<Self>,
13805    ) -> Task<Result<Navigated>> {
13806        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13807    }
13808
13809    pub fn go_to_implementation_split(
13810        &mut self,
13811        _: &GoToImplementationSplit,
13812        window: &mut Window,
13813        cx: &mut Context<Self>,
13814    ) -> Task<Result<Navigated>> {
13815        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13816    }
13817
13818    pub fn go_to_type_definition(
13819        &mut self,
13820        _: &GoToTypeDefinition,
13821        window: &mut Window,
13822        cx: &mut Context<Self>,
13823    ) -> Task<Result<Navigated>> {
13824        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13825    }
13826
13827    pub fn go_to_definition_split(
13828        &mut self,
13829        _: &GoToDefinitionSplit,
13830        window: &mut Window,
13831        cx: &mut Context<Self>,
13832    ) -> Task<Result<Navigated>> {
13833        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13834    }
13835
13836    pub fn go_to_type_definition_split(
13837        &mut self,
13838        _: &GoToTypeDefinitionSplit,
13839        window: &mut Window,
13840        cx: &mut Context<Self>,
13841    ) -> Task<Result<Navigated>> {
13842        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13843    }
13844
13845    fn go_to_definition_of_kind(
13846        &mut self,
13847        kind: GotoDefinitionKind,
13848        split: bool,
13849        window: &mut Window,
13850        cx: &mut Context<Self>,
13851    ) -> Task<Result<Navigated>> {
13852        let Some(provider) = self.semantics_provider.clone() else {
13853            return Task::ready(Ok(Navigated::No));
13854        };
13855        let head = self.selections.newest::<usize>(cx).head();
13856        let buffer = self.buffer.read(cx);
13857        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13858            text_anchor
13859        } else {
13860            return Task::ready(Ok(Navigated::No));
13861        };
13862
13863        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13864            return Task::ready(Ok(Navigated::No));
13865        };
13866
13867        cx.spawn_in(window, async move |editor, cx| {
13868            let definitions = definitions.await?;
13869            let navigated = editor
13870                .update_in(cx, |editor, window, cx| {
13871                    editor.navigate_to_hover_links(
13872                        Some(kind),
13873                        definitions
13874                            .into_iter()
13875                            .filter(|location| {
13876                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13877                            })
13878                            .map(HoverLink::Text)
13879                            .collect::<Vec<_>>(),
13880                        split,
13881                        window,
13882                        cx,
13883                    )
13884                })?
13885                .await?;
13886            anyhow::Ok(navigated)
13887        })
13888    }
13889
13890    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13891        let selection = self.selections.newest_anchor();
13892        let head = selection.head();
13893        let tail = selection.tail();
13894
13895        let Some((buffer, start_position)) =
13896            self.buffer.read(cx).text_anchor_for_position(head, cx)
13897        else {
13898            return;
13899        };
13900
13901        let end_position = if head != tail {
13902            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13903                return;
13904            };
13905            Some(pos)
13906        } else {
13907            None
13908        };
13909
13910        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13911            let url = if let Some(end_pos) = end_position {
13912                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13913            } else {
13914                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13915            };
13916
13917            if let Some(url) = url {
13918                editor.update(cx, |_, cx| {
13919                    cx.open_url(&url);
13920                })
13921            } else {
13922                Ok(())
13923            }
13924        });
13925
13926        url_finder.detach();
13927    }
13928
13929    pub fn open_selected_filename(
13930        &mut self,
13931        _: &OpenSelectedFilename,
13932        window: &mut Window,
13933        cx: &mut Context<Self>,
13934    ) {
13935        let Some(workspace) = self.workspace() else {
13936            return;
13937        };
13938
13939        let position = self.selections.newest_anchor().head();
13940
13941        let Some((buffer, buffer_position)) =
13942            self.buffer.read(cx).text_anchor_for_position(position, cx)
13943        else {
13944            return;
13945        };
13946
13947        let project = self.project.clone();
13948
13949        cx.spawn_in(window, async move |_, cx| {
13950            let result = find_file(&buffer, project, buffer_position, cx).await;
13951
13952            if let Some((_, path)) = result {
13953                workspace
13954                    .update_in(cx, |workspace, window, cx| {
13955                        workspace.open_resolved_path(path, window, cx)
13956                    })?
13957                    .await?;
13958            }
13959            anyhow::Ok(())
13960        })
13961        .detach();
13962    }
13963
13964    pub(crate) fn navigate_to_hover_links(
13965        &mut self,
13966        kind: Option<GotoDefinitionKind>,
13967        mut definitions: Vec<HoverLink>,
13968        split: bool,
13969        window: &mut Window,
13970        cx: &mut Context<Editor>,
13971    ) -> Task<Result<Navigated>> {
13972        // If there is one definition, just open it directly
13973        if definitions.len() == 1 {
13974            let definition = definitions.pop().unwrap();
13975
13976            enum TargetTaskResult {
13977                Location(Option<Location>),
13978                AlreadyNavigated,
13979            }
13980
13981            let target_task = match definition {
13982                HoverLink::Text(link) => {
13983                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13984                }
13985                HoverLink::InlayHint(lsp_location, server_id) => {
13986                    let computation =
13987                        self.compute_target_location(lsp_location, server_id, window, cx);
13988                    cx.background_spawn(async move {
13989                        let location = computation.await?;
13990                        Ok(TargetTaskResult::Location(location))
13991                    })
13992                }
13993                HoverLink::Url(url) => {
13994                    cx.open_url(&url);
13995                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13996                }
13997                HoverLink::File(path) => {
13998                    if let Some(workspace) = self.workspace() {
13999                        cx.spawn_in(window, async move |_, cx| {
14000                            workspace
14001                                .update_in(cx, |workspace, window, cx| {
14002                                    workspace.open_resolved_path(path, window, cx)
14003                                })?
14004                                .await
14005                                .map(|_| TargetTaskResult::AlreadyNavigated)
14006                        })
14007                    } else {
14008                        Task::ready(Ok(TargetTaskResult::Location(None)))
14009                    }
14010                }
14011            };
14012            cx.spawn_in(window, async move |editor, cx| {
14013                let target = match target_task.await.context("target resolution task")? {
14014                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14015                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14016                    TargetTaskResult::Location(Some(target)) => target,
14017                };
14018
14019                editor.update_in(cx, |editor, window, cx| {
14020                    let Some(workspace) = editor.workspace() else {
14021                        return Navigated::No;
14022                    };
14023                    let pane = workspace.read(cx).active_pane().clone();
14024
14025                    let range = target.range.to_point(target.buffer.read(cx));
14026                    let range = editor.range_for_match(&range);
14027                    let range = collapse_multiline_range(range);
14028
14029                    if !split
14030                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14031                    {
14032                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14033                    } else {
14034                        window.defer(cx, move |window, cx| {
14035                            let target_editor: Entity<Self> =
14036                                workspace.update(cx, |workspace, cx| {
14037                                    let pane = if split {
14038                                        workspace.adjacent_pane(window, cx)
14039                                    } else {
14040                                        workspace.active_pane().clone()
14041                                    };
14042
14043                                    workspace.open_project_item(
14044                                        pane,
14045                                        target.buffer.clone(),
14046                                        true,
14047                                        true,
14048                                        window,
14049                                        cx,
14050                                    )
14051                                });
14052                            target_editor.update(cx, |target_editor, cx| {
14053                                // When selecting a definition in a different buffer, disable the nav history
14054                                // to avoid creating a history entry at the previous cursor location.
14055                                pane.update(cx, |pane, _| pane.disable_history());
14056                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14057                                pane.update(cx, |pane, _| pane.enable_history());
14058                            });
14059                        });
14060                    }
14061                    Navigated::Yes
14062                })
14063            })
14064        } else if !definitions.is_empty() {
14065            cx.spawn_in(window, async move |editor, cx| {
14066                let (title, location_tasks, workspace) = editor
14067                    .update_in(cx, |editor, window, cx| {
14068                        let tab_kind = match kind {
14069                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14070                            _ => "Definitions",
14071                        };
14072                        let title = definitions
14073                            .iter()
14074                            .find_map(|definition| match definition {
14075                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14076                                    let buffer = origin.buffer.read(cx);
14077                                    format!(
14078                                        "{} for {}",
14079                                        tab_kind,
14080                                        buffer
14081                                            .text_for_range(origin.range.clone())
14082                                            .collect::<String>()
14083                                    )
14084                                }),
14085                                HoverLink::InlayHint(_, _) => None,
14086                                HoverLink::Url(_) => None,
14087                                HoverLink::File(_) => None,
14088                            })
14089                            .unwrap_or(tab_kind.to_string());
14090                        let location_tasks = definitions
14091                            .into_iter()
14092                            .map(|definition| match definition {
14093                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14094                                HoverLink::InlayHint(lsp_location, server_id) => editor
14095                                    .compute_target_location(lsp_location, server_id, window, cx),
14096                                HoverLink::Url(_) => Task::ready(Ok(None)),
14097                                HoverLink::File(_) => Task::ready(Ok(None)),
14098                            })
14099                            .collect::<Vec<_>>();
14100                        (title, location_tasks, editor.workspace().clone())
14101                    })
14102                    .context("location tasks preparation")?;
14103
14104                let locations = future::join_all(location_tasks)
14105                    .await
14106                    .into_iter()
14107                    .filter_map(|location| location.transpose())
14108                    .collect::<Result<_>>()
14109                    .context("location tasks")?;
14110
14111                let Some(workspace) = workspace else {
14112                    return Ok(Navigated::No);
14113                };
14114                let opened = workspace
14115                    .update_in(cx, |workspace, window, cx| {
14116                        Self::open_locations_in_multibuffer(
14117                            workspace,
14118                            locations,
14119                            title,
14120                            split,
14121                            MultibufferSelectionMode::First,
14122                            window,
14123                            cx,
14124                        )
14125                    })
14126                    .ok();
14127
14128                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14129            })
14130        } else {
14131            Task::ready(Ok(Navigated::No))
14132        }
14133    }
14134
14135    fn compute_target_location(
14136        &self,
14137        lsp_location: lsp::Location,
14138        server_id: LanguageServerId,
14139        window: &mut Window,
14140        cx: &mut Context<Self>,
14141    ) -> Task<anyhow::Result<Option<Location>>> {
14142        let Some(project) = self.project.clone() else {
14143            return Task::ready(Ok(None));
14144        };
14145
14146        cx.spawn_in(window, async move |editor, cx| {
14147            let location_task = editor.update(cx, |_, cx| {
14148                project.update(cx, |project, cx| {
14149                    let language_server_name = project
14150                        .language_server_statuses(cx)
14151                        .find(|(id, _)| server_id == *id)
14152                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14153                    language_server_name.map(|language_server_name| {
14154                        project.open_local_buffer_via_lsp(
14155                            lsp_location.uri.clone(),
14156                            server_id,
14157                            language_server_name,
14158                            cx,
14159                        )
14160                    })
14161                })
14162            })?;
14163            let location = match location_task {
14164                Some(task) => Some({
14165                    let target_buffer_handle = task.await.context("open local buffer")?;
14166                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14167                        let target_start = target_buffer
14168                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14169                        let target_end = target_buffer
14170                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14171                        target_buffer.anchor_after(target_start)
14172                            ..target_buffer.anchor_before(target_end)
14173                    })?;
14174                    Location {
14175                        buffer: target_buffer_handle,
14176                        range,
14177                    }
14178                }),
14179                None => None,
14180            };
14181            Ok(location)
14182        })
14183    }
14184
14185    pub fn find_all_references(
14186        &mut self,
14187        _: &FindAllReferences,
14188        window: &mut Window,
14189        cx: &mut Context<Self>,
14190    ) -> Option<Task<Result<Navigated>>> {
14191        let selection = self.selections.newest::<usize>(cx);
14192        let multi_buffer = self.buffer.read(cx);
14193        let head = selection.head();
14194
14195        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14196        let head_anchor = multi_buffer_snapshot.anchor_at(
14197            head,
14198            if head < selection.tail() {
14199                Bias::Right
14200            } else {
14201                Bias::Left
14202            },
14203        );
14204
14205        match self
14206            .find_all_references_task_sources
14207            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14208        {
14209            Ok(_) => {
14210                log::info!(
14211                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14212                );
14213                return None;
14214            }
14215            Err(i) => {
14216                self.find_all_references_task_sources.insert(i, head_anchor);
14217            }
14218        }
14219
14220        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14221        let workspace = self.workspace()?;
14222        let project = workspace.read(cx).project().clone();
14223        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14224        Some(cx.spawn_in(window, async move |editor, cx| {
14225            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14226                if let Ok(i) = editor
14227                    .find_all_references_task_sources
14228                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14229                {
14230                    editor.find_all_references_task_sources.remove(i);
14231                }
14232            });
14233
14234            let locations = references.await?;
14235            if locations.is_empty() {
14236                return anyhow::Ok(Navigated::No);
14237            }
14238
14239            workspace.update_in(cx, |workspace, window, cx| {
14240                let title = locations
14241                    .first()
14242                    .as_ref()
14243                    .map(|location| {
14244                        let buffer = location.buffer.read(cx);
14245                        format!(
14246                            "References to `{}`",
14247                            buffer
14248                                .text_for_range(location.range.clone())
14249                                .collect::<String>()
14250                        )
14251                    })
14252                    .unwrap();
14253                Self::open_locations_in_multibuffer(
14254                    workspace,
14255                    locations,
14256                    title,
14257                    false,
14258                    MultibufferSelectionMode::First,
14259                    window,
14260                    cx,
14261                );
14262                Navigated::Yes
14263            })
14264        }))
14265    }
14266
14267    /// Opens a multibuffer with the given project locations in it
14268    pub fn open_locations_in_multibuffer(
14269        workspace: &mut Workspace,
14270        mut locations: Vec<Location>,
14271        title: String,
14272        split: bool,
14273        multibuffer_selection_mode: MultibufferSelectionMode,
14274        window: &mut Window,
14275        cx: &mut Context<Workspace>,
14276    ) {
14277        // If there are multiple definitions, open them in a multibuffer
14278        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14279        let mut locations = locations.into_iter().peekable();
14280        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14281        let capability = workspace.project().read(cx).capability();
14282
14283        let excerpt_buffer = cx.new(|cx| {
14284            let mut multibuffer = MultiBuffer::new(capability);
14285            while let Some(location) = locations.next() {
14286                let buffer = location.buffer.read(cx);
14287                let mut ranges_for_buffer = Vec::new();
14288                let range = location.range.to_point(buffer);
14289                ranges_for_buffer.push(range.clone());
14290
14291                while let Some(next_location) = locations.peek() {
14292                    if next_location.buffer == location.buffer {
14293                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14294                        locations.next();
14295                    } else {
14296                        break;
14297                    }
14298                }
14299
14300                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14301                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14302                    PathKey::for_buffer(&location.buffer, cx),
14303                    location.buffer.clone(),
14304                    ranges_for_buffer,
14305                    DEFAULT_MULTIBUFFER_CONTEXT,
14306                    cx,
14307                );
14308                ranges.extend(new_ranges)
14309            }
14310
14311            multibuffer.with_title(title)
14312        });
14313
14314        let editor = cx.new(|cx| {
14315            Editor::for_multibuffer(
14316                excerpt_buffer,
14317                Some(workspace.project().clone()),
14318                window,
14319                cx,
14320            )
14321        });
14322        editor.update(cx, |editor, cx| {
14323            match multibuffer_selection_mode {
14324                MultibufferSelectionMode::First => {
14325                    if let Some(first_range) = ranges.first() {
14326                        editor.change_selections(None, window, cx, |selections| {
14327                            selections.clear_disjoint();
14328                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14329                        });
14330                    }
14331                    editor.highlight_background::<Self>(
14332                        &ranges,
14333                        |theme| theme.editor_highlighted_line_background,
14334                        cx,
14335                    );
14336                }
14337                MultibufferSelectionMode::All => {
14338                    editor.change_selections(None, window, cx, |selections| {
14339                        selections.clear_disjoint();
14340                        selections.select_anchor_ranges(ranges);
14341                    });
14342                }
14343            }
14344            editor.register_buffers_with_language_servers(cx);
14345        });
14346
14347        let item = Box::new(editor);
14348        let item_id = item.item_id();
14349
14350        if split {
14351            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14352        } else {
14353            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14354                let (preview_item_id, preview_item_idx) =
14355                    workspace.active_pane().update(cx, |pane, _| {
14356                        (pane.preview_item_id(), pane.preview_item_idx())
14357                    });
14358
14359                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14360
14361                if let Some(preview_item_id) = preview_item_id {
14362                    workspace.active_pane().update(cx, |pane, cx| {
14363                        pane.remove_item(preview_item_id, false, false, window, cx);
14364                    });
14365                }
14366            } else {
14367                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14368            }
14369        }
14370        workspace.active_pane().update(cx, |pane, cx| {
14371            pane.set_preview_item_id(Some(item_id), cx);
14372        });
14373    }
14374
14375    pub fn rename(
14376        &mut self,
14377        _: &Rename,
14378        window: &mut Window,
14379        cx: &mut Context<Self>,
14380    ) -> Option<Task<Result<()>>> {
14381        use language::ToOffset as _;
14382
14383        let provider = self.semantics_provider.clone()?;
14384        let selection = self.selections.newest_anchor().clone();
14385        let (cursor_buffer, cursor_buffer_position) = self
14386            .buffer
14387            .read(cx)
14388            .text_anchor_for_position(selection.head(), cx)?;
14389        let (tail_buffer, cursor_buffer_position_end) = self
14390            .buffer
14391            .read(cx)
14392            .text_anchor_for_position(selection.tail(), cx)?;
14393        if tail_buffer != cursor_buffer {
14394            return None;
14395        }
14396
14397        let snapshot = cursor_buffer.read(cx).snapshot();
14398        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14399        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14400        let prepare_rename = provider
14401            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14402            .unwrap_or_else(|| Task::ready(Ok(None)));
14403        drop(snapshot);
14404
14405        Some(cx.spawn_in(window, async move |this, cx| {
14406            let rename_range = if let Some(range) = prepare_rename.await? {
14407                Some(range)
14408            } else {
14409                this.update(cx, |this, cx| {
14410                    let buffer = this.buffer.read(cx).snapshot(cx);
14411                    let mut buffer_highlights = this
14412                        .document_highlights_for_position(selection.head(), &buffer)
14413                        .filter(|highlight| {
14414                            highlight.start.excerpt_id == selection.head().excerpt_id
14415                                && highlight.end.excerpt_id == selection.head().excerpt_id
14416                        });
14417                    buffer_highlights
14418                        .next()
14419                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14420                })?
14421            };
14422            if let Some(rename_range) = rename_range {
14423                this.update_in(cx, |this, window, cx| {
14424                    let snapshot = cursor_buffer.read(cx).snapshot();
14425                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14426                    let cursor_offset_in_rename_range =
14427                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14428                    let cursor_offset_in_rename_range_end =
14429                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14430
14431                    this.take_rename(false, window, cx);
14432                    let buffer = this.buffer.read(cx).read(cx);
14433                    let cursor_offset = selection.head().to_offset(&buffer);
14434                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14435                    let rename_end = rename_start + rename_buffer_range.len();
14436                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14437                    let mut old_highlight_id = None;
14438                    let old_name: Arc<str> = buffer
14439                        .chunks(rename_start..rename_end, true)
14440                        .map(|chunk| {
14441                            if old_highlight_id.is_none() {
14442                                old_highlight_id = chunk.syntax_highlight_id;
14443                            }
14444                            chunk.text
14445                        })
14446                        .collect::<String>()
14447                        .into();
14448
14449                    drop(buffer);
14450
14451                    // Position the selection in the rename editor so that it matches the current selection.
14452                    this.show_local_selections = false;
14453                    let rename_editor = cx.new(|cx| {
14454                        let mut editor = Editor::single_line(window, cx);
14455                        editor.buffer.update(cx, |buffer, cx| {
14456                            buffer.edit([(0..0, old_name.clone())], None, cx)
14457                        });
14458                        let rename_selection_range = match cursor_offset_in_rename_range
14459                            .cmp(&cursor_offset_in_rename_range_end)
14460                        {
14461                            Ordering::Equal => {
14462                                editor.select_all(&SelectAll, window, cx);
14463                                return editor;
14464                            }
14465                            Ordering::Less => {
14466                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14467                            }
14468                            Ordering::Greater => {
14469                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14470                            }
14471                        };
14472                        if rename_selection_range.end > old_name.len() {
14473                            editor.select_all(&SelectAll, window, cx);
14474                        } else {
14475                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14476                                s.select_ranges([rename_selection_range]);
14477                            });
14478                        }
14479                        editor
14480                    });
14481                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14482                        if e == &EditorEvent::Focused {
14483                            cx.emit(EditorEvent::FocusedIn)
14484                        }
14485                    })
14486                    .detach();
14487
14488                    let write_highlights =
14489                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14490                    let read_highlights =
14491                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14492                    let ranges = write_highlights
14493                        .iter()
14494                        .flat_map(|(_, ranges)| ranges.iter())
14495                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14496                        .cloned()
14497                        .collect();
14498
14499                    this.highlight_text::<Rename>(
14500                        ranges,
14501                        HighlightStyle {
14502                            fade_out: Some(0.6),
14503                            ..Default::default()
14504                        },
14505                        cx,
14506                    );
14507                    let rename_focus_handle = rename_editor.focus_handle(cx);
14508                    window.focus(&rename_focus_handle);
14509                    let block_id = this.insert_blocks(
14510                        [BlockProperties {
14511                            style: BlockStyle::Flex,
14512                            placement: BlockPlacement::Below(range.start),
14513                            height: Some(1),
14514                            render: Arc::new({
14515                                let rename_editor = rename_editor.clone();
14516                                move |cx: &mut BlockContext| {
14517                                    let mut text_style = cx.editor_style.text.clone();
14518                                    if let Some(highlight_style) = old_highlight_id
14519                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14520                                    {
14521                                        text_style = text_style.highlight(highlight_style);
14522                                    }
14523                                    div()
14524                                        .block_mouse_down()
14525                                        .pl(cx.anchor_x)
14526                                        .child(EditorElement::new(
14527                                            &rename_editor,
14528                                            EditorStyle {
14529                                                background: cx.theme().system().transparent,
14530                                                local_player: cx.editor_style.local_player,
14531                                                text: text_style,
14532                                                scrollbar_width: cx.editor_style.scrollbar_width,
14533                                                syntax: cx.editor_style.syntax.clone(),
14534                                                status: cx.editor_style.status.clone(),
14535                                                inlay_hints_style: HighlightStyle {
14536                                                    font_weight: Some(FontWeight::BOLD),
14537                                                    ..make_inlay_hints_style(cx.app)
14538                                                },
14539                                                inline_completion_styles: make_suggestion_styles(
14540                                                    cx.app,
14541                                                ),
14542                                                ..EditorStyle::default()
14543                                            },
14544                                        ))
14545                                        .into_any_element()
14546                                }
14547                            }),
14548                            priority: 0,
14549                        }],
14550                        Some(Autoscroll::fit()),
14551                        cx,
14552                    )[0];
14553                    this.pending_rename = Some(RenameState {
14554                        range,
14555                        old_name,
14556                        editor: rename_editor,
14557                        block_id,
14558                    });
14559                })?;
14560            }
14561
14562            Ok(())
14563        }))
14564    }
14565
14566    pub fn confirm_rename(
14567        &mut self,
14568        _: &ConfirmRename,
14569        window: &mut Window,
14570        cx: &mut Context<Self>,
14571    ) -> Option<Task<Result<()>>> {
14572        let rename = self.take_rename(false, window, cx)?;
14573        let workspace = self.workspace()?.downgrade();
14574        let (buffer, start) = self
14575            .buffer
14576            .read(cx)
14577            .text_anchor_for_position(rename.range.start, cx)?;
14578        let (end_buffer, _) = self
14579            .buffer
14580            .read(cx)
14581            .text_anchor_for_position(rename.range.end, cx)?;
14582        if buffer != end_buffer {
14583            return None;
14584        }
14585
14586        let old_name = rename.old_name;
14587        let new_name = rename.editor.read(cx).text(cx);
14588
14589        let rename = self.semantics_provider.as_ref()?.perform_rename(
14590            &buffer,
14591            start,
14592            new_name.clone(),
14593            cx,
14594        )?;
14595
14596        Some(cx.spawn_in(window, async move |editor, cx| {
14597            let project_transaction = rename.await?;
14598            Self::open_project_transaction(
14599                &editor,
14600                workspace,
14601                project_transaction,
14602                format!("Rename: {}{}", old_name, new_name),
14603                cx,
14604            )
14605            .await?;
14606
14607            editor.update(cx, |editor, cx| {
14608                editor.refresh_document_highlights(cx);
14609            })?;
14610            Ok(())
14611        }))
14612    }
14613
14614    fn take_rename(
14615        &mut self,
14616        moving_cursor: bool,
14617        window: &mut Window,
14618        cx: &mut Context<Self>,
14619    ) -> Option<RenameState> {
14620        let rename = self.pending_rename.take()?;
14621        if rename.editor.focus_handle(cx).is_focused(window) {
14622            window.focus(&self.focus_handle);
14623        }
14624
14625        self.remove_blocks(
14626            [rename.block_id].into_iter().collect(),
14627            Some(Autoscroll::fit()),
14628            cx,
14629        );
14630        self.clear_highlights::<Rename>(cx);
14631        self.show_local_selections = true;
14632
14633        if moving_cursor {
14634            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14635                editor.selections.newest::<usize>(cx).head()
14636            });
14637
14638            // Update the selection to match the position of the selection inside
14639            // the rename editor.
14640            let snapshot = self.buffer.read(cx).read(cx);
14641            let rename_range = rename.range.to_offset(&snapshot);
14642            let cursor_in_editor = snapshot
14643                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14644                .min(rename_range.end);
14645            drop(snapshot);
14646
14647            self.change_selections(None, window, cx, |s| {
14648                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14649            });
14650        } else {
14651            self.refresh_document_highlights(cx);
14652        }
14653
14654        Some(rename)
14655    }
14656
14657    pub fn pending_rename(&self) -> Option<&RenameState> {
14658        self.pending_rename.as_ref()
14659    }
14660
14661    fn format(
14662        &mut self,
14663        _: &Format,
14664        window: &mut Window,
14665        cx: &mut Context<Self>,
14666    ) -> Option<Task<Result<()>>> {
14667        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14668
14669        let project = match &self.project {
14670            Some(project) => project.clone(),
14671            None => return None,
14672        };
14673
14674        Some(self.perform_format(
14675            project,
14676            FormatTrigger::Manual,
14677            FormatTarget::Buffers,
14678            window,
14679            cx,
14680        ))
14681    }
14682
14683    fn format_selections(
14684        &mut self,
14685        _: &FormatSelections,
14686        window: &mut Window,
14687        cx: &mut Context<Self>,
14688    ) -> Option<Task<Result<()>>> {
14689        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14690
14691        let project = match &self.project {
14692            Some(project) => project.clone(),
14693            None => return None,
14694        };
14695
14696        let ranges = self
14697            .selections
14698            .all_adjusted(cx)
14699            .into_iter()
14700            .map(|selection| selection.range())
14701            .collect_vec();
14702
14703        Some(self.perform_format(
14704            project,
14705            FormatTrigger::Manual,
14706            FormatTarget::Ranges(ranges),
14707            window,
14708            cx,
14709        ))
14710    }
14711
14712    fn perform_format(
14713        &mut self,
14714        project: Entity<Project>,
14715        trigger: FormatTrigger,
14716        target: FormatTarget,
14717        window: &mut Window,
14718        cx: &mut Context<Self>,
14719    ) -> Task<Result<()>> {
14720        let buffer = self.buffer.clone();
14721        let (buffers, target) = match target {
14722            FormatTarget::Buffers => {
14723                let mut buffers = buffer.read(cx).all_buffers();
14724                if trigger == FormatTrigger::Save {
14725                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14726                }
14727                (buffers, LspFormatTarget::Buffers)
14728            }
14729            FormatTarget::Ranges(selection_ranges) => {
14730                let multi_buffer = buffer.read(cx);
14731                let snapshot = multi_buffer.read(cx);
14732                let mut buffers = HashSet::default();
14733                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14734                    BTreeMap::new();
14735                for selection_range in selection_ranges {
14736                    for (buffer, buffer_range, _) in
14737                        snapshot.range_to_buffer_ranges(selection_range)
14738                    {
14739                        let buffer_id = buffer.remote_id();
14740                        let start = buffer.anchor_before(buffer_range.start);
14741                        let end = buffer.anchor_after(buffer_range.end);
14742                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14743                        buffer_id_to_ranges
14744                            .entry(buffer_id)
14745                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14746                            .or_insert_with(|| vec![start..end]);
14747                    }
14748                }
14749                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14750            }
14751        };
14752
14753        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14754        let selections_prev = transaction_id_prev
14755            .and_then(|transaction_id_prev| {
14756                // default to selections as they were after the last edit, if we have them,
14757                // instead of how they are now.
14758                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14759                // will take you back to where you made the last edit, instead of staying where you scrolled
14760                self.selection_history
14761                    .transaction(transaction_id_prev)
14762                    .map(|t| t.0.clone())
14763            })
14764            .unwrap_or_else(|| {
14765                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14766                self.selections.disjoint_anchors()
14767            });
14768
14769        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14770        let format = project.update(cx, |project, cx| {
14771            project.format(buffers, target, true, trigger, cx)
14772        });
14773
14774        cx.spawn_in(window, async move |editor, cx| {
14775            let transaction = futures::select_biased! {
14776                transaction = format.log_err().fuse() => transaction,
14777                () = timeout => {
14778                    log::warn!("timed out waiting for formatting");
14779                    None
14780                }
14781            };
14782
14783            buffer
14784                .update(cx, |buffer, cx| {
14785                    if let Some(transaction) = transaction {
14786                        if !buffer.is_singleton() {
14787                            buffer.push_transaction(&transaction.0, cx);
14788                        }
14789                    }
14790                    cx.notify();
14791                })
14792                .ok();
14793
14794            if let Some(transaction_id_now) =
14795                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14796            {
14797                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14798                if has_new_transaction {
14799                    _ = editor.update(cx, |editor, _| {
14800                        editor
14801                            .selection_history
14802                            .insert_transaction(transaction_id_now, selections_prev);
14803                    });
14804                }
14805            }
14806
14807            Ok(())
14808        })
14809    }
14810
14811    fn organize_imports(
14812        &mut self,
14813        _: &OrganizeImports,
14814        window: &mut Window,
14815        cx: &mut Context<Self>,
14816    ) -> Option<Task<Result<()>>> {
14817        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14818        let project = match &self.project {
14819            Some(project) => project.clone(),
14820            None => return None,
14821        };
14822        Some(self.perform_code_action_kind(
14823            project,
14824            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14825            window,
14826            cx,
14827        ))
14828    }
14829
14830    fn perform_code_action_kind(
14831        &mut self,
14832        project: Entity<Project>,
14833        kind: CodeActionKind,
14834        window: &mut Window,
14835        cx: &mut Context<Self>,
14836    ) -> Task<Result<()>> {
14837        let buffer = self.buffer.clone();
14838        let buffers = buffer.read(cx).all_buffers();
14839        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14840        let apply_action = project.update(cx, |project, cx| {
14841            project.apply_code_action_kind(buffers, kind, true, cx)
14842        });
14843        cx.spawn_in(window, async move |_, cx| {
14844            let transaction = futures::select_biased! {
14845                () = timeout => {
14846                    log::warn!("timed out waiting for executing code action");
14847                    None
14848                }
14849                transaction = apply_action.log_err().fuse() => transaction,
14850            };
14851            buffer
14852                .update(cx, |buffer, cx| {
14853                    // check if we need this
14854                    if let Some(transaction) = transaction {
14855                        if !buffer.is_singleton() {
14856                            buffer.push_transaction(&transaction.0, cx);
14857                        }
14858                    }
14859                    cx.notify();
14860                })
14861                .ok();
14862            Ok(())
14863        })
14864    }
14865
14866    fn restart_language_server(
14867        &mut self,
14868        _: &RestartLanguageServer,
14869        _: &mut Window,
14870        cx: &mut Context<Self>,
14871    ) {
14872        if let Some(project) = self.project.clone() {
14873            self.buffer.update(cx, |multi_buffer, cx| {
14874                project.update(cx, |project, cx| {
14875                    project.restart_language_servers_for_buffers(
14876                        multi_buffer.all_buffers().into_iter().collect(),
14877                        cx,
14878                    );
14879                });
14880            })
14881        }
14882    }
14883
14884    fn stop_language_server(
14885        &mut self,
14886        _: &StopLanguageServer,
14887        _: &mut Window,
14888        cx: &mut Context<Self>,
14889    ) {
14890        if let Some(project) = self.project.clone() {
14891            self.buffer.update(cx, |multi_buffer, cx| {
14892                project.update(cx, |project, cx| {
14893                    project.stop_language_servers_for_buffers(
14894                        multi_buffer.all_buffers().into_iter().collect(),
14895                        cx,
14896                    );
14897                    cx.emit(project::Event::RefreshInlayHints);
14898                });
14899            });
14900        }
14901    }
14902
14903    fn cancel_language_server_work(
14904        workspace: &mut Workspace,
14905        _: &actions::CancelLanguageServerWork,
14906        _: &mut Window,
14907        cx: &mut Context<Workspace>,
14908    ) {
14909        let project = workspace.project();
14910        let buffers = workspace
14911            .active_item(cx)
14912            .and_then(|item| item.act_as::<Editor>(cx))
14913            .map_or(HashSet::default(), |editor| {
14914                editor.read(cx).buffer.read(cx).all_buffers()
14915            });
14916        project.update(cx, |project, cx| {
14917            project.cancel_language_server_work_for_buffers(buffers, cx);
14918        });
14919    }
14920
14921    fn show_character_palette(
14922        &mut self,
14923        _: &ShowCharacterPalette,
14924        window: &mut Window,
14925        _: &mut Context<Self>,
14926    ) {
14927        window.show_character_palette();
14928    }
14929
14930    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14931        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14932            let buffer = self.buffer.read(cx).snapshot(cx);
14933            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14934            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14935            let is_valid = buffer
14936                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14937                .any(|entry| {
14938                    entry.diagnostic.is_primary
14939                        && !entry.range.is_empty()
14940                        && entry.range.start == primary_range_start
14941                        && entry.diagnostic.message == active_diagnostics.active_message
14942                });
14943
14944            if !is_valid {
14945                self.dismiss_diagnostics(cx);
14946            }
14947        }
14948    }
14949
14950    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14951        match &self.active_diagnostics {
14952            ActiveDiagnostic::Group(group) => Some(group),
14953            _ => None,
14954        }
14955    }
14956
14957    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14958        self.dismiss_diagnostics(cx);
14959        self.active_diagnostics = ActiveDiagnostic::All;
14960    }
14961
14962    fn activate_diagnostics(
14963        &mut self,
14964        buffer_id: BufferId,
14965        diagnostic: DiagnosticEntry<usize>,
14966        window: &mut Window,
14967        cx: &mut Context<Self>,
14968    ) {
14969        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14970            return;
14971        }
14972        self.dismiss_diagnostics(cx);
14973        let snapshot = self.snapshot(window, cx);
14974        let buffer = self.buffer.read(cx).snapshot(cx);
14975        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
14976            return;
14977        };
14978
14979        let diagnostic_group = buffer
14980            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14981            .collect::<Vec<_>>();
14982
14983        let blocks =
14984            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
14985
14986        let blocks = self.display_map.update(cx, |display_map, cx| {
14987            display_map.insert_blocks(blocks, cx).into_iter().collect()
14988        });
14989        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14990            active_range: buffer.anchor_before(diagnostic.range.start)
14991                ..buffer.anchor_after(diagnostic.range.end),
14992            active_message: diagnostic.diagnostic.message.clone(),
14993            group_id: diagnostic.diagnostic.group_id,
14994            blocks,
14995        });
14996        cx.notify();
14997    }
14998
14999    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15000        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15001            return;
15002        };
15003
15004        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15005        if let ActiveDiagnostic::Group(group) = prev {
15006            self.display_map.update(cx, |display_map, cx| {
15007                display_map.remove_blocks(group.blocks, cx);
15008            });
15009            cx.notify();
15010        }
15011    }
15012
15013    /// Disable inline diagnostics rendering for this editor.
15014    pub fn disable_inline_diagnostics(&mut self) {
15015        self.inline_diagnostics_enabled = false;
15016        self.inline_diagnostics_update = Task::ready(());
15017        self.inline_diagnostics.clear();
15018    }
15019
15020    pub fn inline_diagnostics_enabled(&self) -> bool {
15021        self.inline_diagnostics_enabled
15022    }
15023
15024    pub fn show_inline_diagnostics(&self) -> bool {
15025        self.show_inline_diagnostics
15026    }
15027
15028    pub fn toggle_inline_diagnostics(
15029        &mut self,
15030        _: &ToggleInlineDiagnostics,
15031        window: &mut Window,
15032        cx: &mut Context<Editor>,
15033    ) {
15034        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15035        self.refresh_inline_diagnostics(false, window, cx);
15036    }
15037
15038    fn refresh_inline_diagnostics(
15039        &mut self,
15040        debounce: bool,
15041        window: &mut Window,
15042        cx: &mut Context<Self>,
15043    ) {
15044        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15045            self.inline_diagnostics_update = Task::ready(());
15046            self.inline_diagnostics.clear();
15047            return;
15048        }
15049
15050        let debounce_ms = ProjectSettings::get_global(cx)
15051            .diagnostics
15052            .inline
15053            .update_debounce_ms;
15054        let debounce = if debounce && debounce_ms > 0 {
15055            Some(Duration::from_millis(debounce_ms))
15056        } else {
15057            None
15058        };
15059        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15060            let editor = editor.upgrade().unwrap();
15061
15062            if let Some(debounce) = debounce {
15063                cx.background_executor().timer(debounce).await;
15064            }
15065            let Some(snapshot) = editor
15066                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15067                .ok()
15068            else {
15069                return;
15070            };
15071
15072            let new_inline_diagnostics = cx
15073                .background_spawn(async move {
15074                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15075                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15076                        let message = diagnostic_entry
15077                            .diagnostic
15078                            .message
15079                            .split_once('\n')
15080                            .map(|(line, _)| line)
15081                            .map(SharedString::new)
15082                            .unwrap_or_else(|| {
15083                                SharedString::from(diagnostic_entry.diagnostic.message)
15084                            });
15085                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15086                        let (Ok(i) | Err(i)) = inline_diagnostics
15087                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15088                        inline_diagnostics.insert(
15089                            i,
15090                            (
15091                                start_anchor,
15092                                InlineDiagnostic {
15093                                    message,
15094                                    group_id: diagnostic_entry.diagnostic.group_id,
15095                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15096                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15097                                    severity: diagnostic_entry.diagnostic.severity,
15098                                },
15099                            ),
15100                        );
15101                    }
15102                    inline_diagnostics
15103                })
15104                .await;
15105
15106            editor
15107                .update(cx, |editor, cx| {
15108                    editor.inline_diagnostics = new_inline_diagnostics;
15109                    cx.notify();
15110                })
15111                .ok();
15112        });
15113    }
15114
15115    pub fn set_selections_from_remote(
15116        &mut self,
15117        selections: Vec<Selection<Anchor>>,
15118        pending_selection: Option<Selection<Anchor>>,
15119        window: &mut Window,
15120        cx: &mut Context<Self>,
15121    ) {
15122        let old_cursor_position = self.selections.newest_anchor().head();
15123        self.selections.change_with(cx, |s| {
15124            s.select_anchors(selections);
15125            if let Some(pending_selection) = pending_selection {
15126                s.set_pending(pending_selection, SelectMode::Character);
15127            } else {
15128                s.clear_pending();
15129            }
15130        });
15131        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15132    }
15133
15134    fn push_to_selection_history(&mut self) {
15135        self.selection_history.push(SelectionHistoryEntry {
15136            selections: self.selections.disjoint_anchors(),
15137            select_next_state: self.select_next_state.clone(),
15138            select_prev_state: self.select_prev_state.clone(),
15139            add_selections_state: self.add_selections_state.clone(),
15140        });
15141    }
15142
15143    pub fn transact(
15144        &mut self,
15145        window: &mut Window,
15146        cx: &mut Context<Self>,
15147        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15148    ) -> Option<TransactionId> {
15149        self.start_transaction_at(Instant::now(), window, cx);
15150        update(self, window, cx);
15151        self.end_transaction_at(Instant::now(), cx)
15152    }
15153
15154    pub fn start_transaction_at(
15155        &mut self,
15156        now: Instant,
15157        window: &mut Window,
15158        cx: &mut Context<Self>,
15159    ) {
15160        self.end_selection(window, cx);
15161        if let Some(tx_id) = self
15162            .buffer
15163            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15164        {
15165            self.selection_history
15166                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15167            cx.emit(EditorEvent::TransactionBegun {
15168                transaction_id: tx_id,
15169            })
15170        }
15171    }
15172
15173    pub fn end_transaction_at(
15174        &mut self,
15175        now: Instant,
15176        cx: &mut Context<Self>,
15177    ) -> Option<TransactionId> {
15178        if let Some(transaction_id) = self
15179            .buffer
15180            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15181        {
15182            if let Some((_, end_selections)) =
15183                self.selection_history.transaction_mut(transaction_id)
15184            {
15185                *end_selections = Some(self.selections.disjoint_anchors());
15186            } else {
15187                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15188            }
15189
15190            cx.emit(EditorEvent::Edited { transaction_id });
15191            Some(transaction_id)
15192        } else {
15193            None
15194        }
15195    }
15196
15197    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15198        if self.selection_mark_mode {
15199            self.change_selections(None, window, cx, |s| {
15200                s.move_with(|_, sel| {
15201                    sel.collapse_to(sel.head(), SelectionGoal::None);
15202                });
15203            })
15204        }
15205        self.selection_mark_mode = true;
15206        cx.notify();
15207    }
15208
15209    pub fn swap_selection_ends(
15210        &mut self,
15211        _: &actions::SwapSelectionEnds,
15212        window: &mut Window,
15213        cx: &mut Context<Self>,
15214    ) {
15215        self.change_selections(None, window, cx, |s| {
15216            s.move_with(|_, sel| {
15217                if sel.start != sel.end {
15218                    sel.reversed = !sel.reversed
15219                }
15220            });
15221        });
15222        self.request_autoscroll(Autoscroll::newest(), cx);
15223        cx.notify();
15224    }
15225
15226    pub fn toggle_fold(
15227        &mut self,
15228        _: &actions::ToggleFold,
15229        window: &mut Window,
15230        cx: &mut Context<Self>,
15231    ) {
15232        if self.is_singleton(cx) {
15233            let selection = self.selections.newest::<Point>(cx);
15234
15235            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15236            let range = if selection.is_empty() {
15237                let point = selection.head().to_display_point(&display_map);
15238                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15239                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15240                    .to_point(&display_map);
15241                start..end
15242            } else {
15243                selection.range()
15244            };
15245            if display_map.folds_in_range(range).next().is_some() {
15246                self.unfold_lines(&Default::default(), window, cx)
15247            } else {
15248                self.fold(&Default::default(), window, cx)
15249            }
15250        } else {
15251            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15252            let buffer_ids: HashSet<_> = self
15253                .selections
15254                .disjoint_anchor_ranges()
15255                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15256                .collect();
15257
15258            let should_unfold = buffer_ids
15259                .iter()
15260                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15261
15262            for buffer_id in buffer_ids {
15263                if should_unfold {
15264                    self.unfold_buffer(buffer_id, cx);
15265                } else {
15266                    self.fold_buffer(buffer_id, cx);
15267                }
15268            }
15269        }
15270    }
15271
15272    pub fn toggle_fold_recursive(
15273        &mut self,
15274        _: &actions::ToggleFoldRecursive,
15275        window: &mut Window,
15276        cx: &mut Context<Self>,
15277    ) {
15278        let selection = self.selections.newest::<Point>(cx);
15279
15280        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15281        let range = if selection.is_empty() {
15282            let point = selection.head().to_display_point(&display_map);
15283            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15284            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15285                .to_point(&display_map);
15286            start..end
15287        } else {
15288            selection.range()
15289        };
15290        if display_map.folds_in_range(range).next().is_some() {
15291            self.unfold_recursive(&Default::default(), window, cx)
15292        } else {
15293            self.fold_recursive(&Default::default(), window, cx)
15294        }
15295    }
15296
15297    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15298        if self.is_singleton(cx) {
15299            let mut to_fold = Vec::new();
15300            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15301            let selections = self.selections.all_adjusted(cx);
15302
15303            for selection in selections {
15304                let range = selection.range().sorted();
15305                let buffer_start_row = range.start.row;
15306
15307                if range.start.row != range.end.row {
15308                    let mut found = false;
15309                    let mut row = range.start.row;
15310                    while row <= range.end.row {
15311                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15312                        {
15313                            found = true;
15314                            row = crease.range().end.row + 1;
15315                            to_fold.push(crease);
15316                        } else {
15317                            row += 1
15318                        }
15319                    }
15320                    if found {
15321                        continue;
15322                    }
15323                }
15324
15325                for row in (0..=range.start.row).rev() {
15326                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15327                        if crease.range().end.row >= buffer_start_row {
15328                            to_fold.push(crease);
15329                            if row <= range.start.row {
15330                                break;
15331                            }
15332                        }
15333                    }
15334                }
15335            }
15336
15337            self.fold_creases(to_fold, true, window, cx);
15338        } else {
15339            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15340            let buffer_ids = self
15341                .selections
15342                .disjoint_anchor_ranges()
15343                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15344                .collect::<HashSet<_>>();
15345            for buffer_id in buffer_ids {
15346                self.fold_buffer(buffer_id, cx);
15347            }
15348        }
15349    }
15350
15351    fn fold_at_level(
15352        &mut self,
15353        fold_at: &FoldAtLevel,
15354        window: &mut Window,
15355        cx: &mut Context<Self>,
15356    ) {
15357        if !self.buffer.read(cx).is_singleton() {
15358            return;
15359        }
15360
15361        let fold_at_level = fold_at.0;
15362        let snapshot = self.buffer.read(cx).snapshot(cx);
15363        let mut to_fold = Vec::new();
15364        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15365
15366        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15367            while start_row < end_row {
15368                match self
15369                    .snapshot(window, cx)
15370                    .crease_for_buffer_row(MultiBufferRow(start_row))
15371                {
15372                    Some(crease) => {
15373                        let nested_start_row = crease.range().start.row + 1;
15374                        let nested_end_row = crease.range().end.row;
15375
15376                        if current_level < fold_at_level {
15377                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15378                        } else if current_level == fold_at_level {
15379                            to_fold.push(crease);
15380                        }
15381
15382                        start_row = nested_end_row + 1;
15383                    }
15384                    None => start_row += 1,
15385                }
15386            }
15387        }
15388
15389        self.fold_creases(to_fold, true, window, cx);
15390    }
15391
15392    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15393        if self.buffer.read(cx).is_singleton() {
15394            let mut fold_ranges = Vec::new();
15395            let snapshot = self.buffer.read(cx).snapshot(cx);
15396
15397            for row in 0..snapshot.max_row().0 {
15398                if let Some(foldable_range) = self
15399                    .snapshot(window, cx)
15400                    .crease_for_buffer_row(MultiBufferRow(row))
15401                {
15402                    fold_ranges.push(foldable_range);
15403                }
15404            }
15405
15406            self.fold_creases(fold_ranges, true, window, cx);
15407        } else {
15408            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15409                editor
15410                    .update_in(cx, |editor, _, cx| {
15411                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15412                            editor.fold_buffer(buffer_id, cx);
15413                        }
15414                    })
15415                    .ok();
15416            });
15417        }
15418    }
15419
15420    pub fn fold_function_bodies(
15421        &mut self,
15422        _: &actions::FoldFunctionBodies,
15423        window: &mut Window,
15424        cx: &mut Context<Self>,
15425    ) {
15426        let snapshot = self.buffer.read(cx).snapshot(cx);
15427
15428        let ranges = snapshot
15429            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15430            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15431            .collect::<Vec<_>>();
15432
15433        let creases = ranges
15434            .into_iter()
15435            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15436            .collect();
15437
15438        self.fold_creases(creases, true, window, cx);
15439    }
15440
15441    pub fn fold_recursive(
15442        &mut self,
15443        _: &actions::FoldRecursive,
15444        window: &mut Window,
15445        cx: &mut Context<Self>,
15446    ) {
15447        let mut to_fold = Vec::new();
15448        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15449        let selections = self.selections.all_adjusted(cx);
15450
15451        for selection in selections {
15452            let range = selection.range().sorted();
15453            let buffer_start_row = range.start.row;
15454
15455            if range.start.row != range.end.row {
15456                let mut found = false;
15457                for row in range.start.row..=range.end.row {
15458                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15459                        found = true;
15460                        to_fold.push(crease);
15461                    }
15462                }
15463                if found {
15464                    continue;
15465                }
15466            }
15467
15468            for row in (0..=range.start.row).rev() {
15469                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15470                    if crease.range().end.row >= buffer_start_row {
15471                        to_fold.push(crease);
15472                    } else {
15473                        break;
15474                    }
15475                }
15476            }
15477        }
15478
15479        self.fold_creases(to_fold, true, window, cx);
15480    }
15481
15482    pub fn fold_at(
15483        &mut self,
15484        buffer_row: MultiBufferRow,
15485        window: &mut Window,
15486        cx: &mut Context<Self>,
15487    ) {
15488        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15489
15490        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15491            let autoscroll = self
15492                .selections
15493                .all::<Point>(cx)
15494                .iter()
15495                .any(|selection| crease.range().overlaps(&selection.range()));
15496
15497            self.fold_creases(vec![crease], autoscroll, window, cx);
15498        }
15499    }
15500
15501    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15502        if self.is_singleton(cx) {
15503            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15504            let buffer = &display_map.buffer_snapshot;
15505            let selections = self.selections.all::<Point>(cx);
15506            let ranges = selections
15507                .iter()
15508                .map(|s| {
15509                    let range = s.display_range(&display_map).sorted();
15510                    let mut start = range.start.to_point(&display_map);
15511                    let mut end = range.end.to_point(&display_map);
15512                    start.column = 0;
15513                    end.column = buffer.line_len(MultiBufferRow(end.row));
15514                    start..end
15515                })
15516                .collect::<Vec<_>>();
15517
15518            self.unfold_ranges(&ranges, true, true, cx);
15519        } else {
15520            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15521            let buffer_ids = self
15522                .selections
15523                .disjoint_anchor_ranges()
15524                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15525                .collect::<HashSet<_>>();
15526            for buffer_id in buffer_ids {
15527                self.unfold_buffer(buffer_id, cx);
15528            }
15529        }
15530    }
15531
15532    pub fn unfold_recursive(
15533        &mut self,
15534        _: &UnfoldRecursive,
15535        _window: &mut Window,
15536        cx: &mut Context<Self>,
15537    ) {
15538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15539        let selections = self.selections.all::<Point>(cx);
15540        let ranges = selections
15541            .iter()
15542            .map(|s| {
15543                let mut range = s.display_range(&display_map).sorted();
15544                *range.start.column_mut() = 0;
15545                *range.end.column_mut() = display_map.line_len(range.end.row());
15546                let start = range.start.to_point(&display_map);
15547                let end = range.end.to_point(&display_map);
15548                start..end
15549            })
15550            .collect::<Vec<_>>();
15551
15552        self.unfold_ranges(&ranges, true, true, cx);
15553    }
15554
15555    pub fn unfold_at(
15556        &mut self,
15557        buffer_row: MultiBufferRow,
15558        _window: &mut Window,
15559        cx: &mut Context<Self>,
15560    ) {
15561        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15562
15563        let intersection_range = Point::new(buffer_row.0, 0)
15564            ..Point::new(
15565                buffer_row.0,
15566                display_map.buffer_snapshot.line_len(buffer_row),
15567            );
15568
15569        let autoscroll = self
15570            .selections
15571            .all::<Point>(cx)
15572            .iter()
15573            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15574
15575        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15576    }
15577
15578    pub fn unfold_all(
15579        &mut self,
15580        _: &actions::UnfoldAll,
15581        _window: &mut Window,
15582        cx: &mut Context<Self>,
15583    ) {
15584        if self.buffer.read(cx).is_singleton() {
15585            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15586            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15587        } else {
15588            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15589                editor
15590                    .update(cx, |editor, cx| {
15591                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15592                            editor.unfold_buffer(buffer_id, cx);
15593                        }
15594                    })
15595                    .ok();
15596            });
15597        }
15598    }
15599
15600    pub fn fold_selected_ranges(
15601        &mut self,
15602        _: &FoldSelectedRanges,
15603        window: &mut Window,
15604        cx: &mut Context<Self>,
15605    ) {
15606        let selections = self.selections.all_adjusted(cx);
15607        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15608        let ranges = selections
15609            .into_iter()
15610            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15611            .collect::<Vec<_>>();
15612        self.fold_creases(ranges, true, window, cx);
15613    }
15614
15615    pub fn fold_ranges<T: ToOffset + Clone>(
15616        &mut self,
15617        ranges: Vec<Range<T>>,
15618        auto_scroll: bool,
15619        window: &mut Window,
15620        cx: &mut Context<Self>,
15621    ) {
15622        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15623        let ranges = ranges
15624            .into_iter()
15625            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15626            .collect::<Vec<_>>();
15627        self.fold_creases(ranges, auto_scroll, window, cx);
15628    }
15629
15630    pub fn fold_creases<T: ToOffset + Clone>(
15631        &mut self,
15632        creases: Vec<Crease<T>>,
15633        auto_scroll: bool,
15634        _window: &mut Window,
15635        cx: &mut Context<Self>,
15636    ) {
15637        if creases.is_empty() {
15638            return;
15639        }
15640
15641        let mut buffers_affected = HashSet::default();
15642        let multi_buffer = self.buffer().read(cx);
15643        for crease in &creases {
15644            if let Some((_, buffer, _)) =
15645                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15646            {
15647                buffers_affected.insert(buffer.read(cx).remote_id());
15648            };
15649        }
15650
15651        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15652
15653        if auto_scroll {
15654            self.request_autoscroll(Autoscroll::fit(), cx);
15655        }
15656
15657        cx.notify();
15658
15659        self.scrollbar_marker_state.dirty = true;
15660        self.folds_did_change(cx);
15661    }
15662
15663    /// Removes any folds whose ranges intersect any of the given ranges.
15664    pub fn unfold_ranges<T: ToOffset + Clone>(
15665        &mut self,
15666        ranges: &[Range<T>],
15667        inclusive: bool,
15668        auto_scroll: bool,
15669        cx: &mut Context<Self>,
15670    ) {
15671        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15672            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15673        });
15674        self.folds_did_change(cx);
15675    }
15676
15677    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15678        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15679            return;
15680        }
15681        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15682        self.display_map.update(cx, |display_map, cx| {
15683            display_map.fold_buffers([buffer_id], cx)
15684        });
15685        cx.emit(EditorEvent::BufferFoldToggled {
15686            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15687            folded: true,
15688        });
15689        cx.notify();
15690    }
15691
15692    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15693        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15694            return;
15695        }
15696        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15697        self.display_map.update(cx, |display_map, cx| {
15698            display_map.unfold_buffers([buffer_id], cx);
15699        });
15700        cx.emit(EditorEvent::BufferFoldToggled {
15701            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15702            folded: false,
15703        });
15704        cx.notify();
15705    }
15706
15707    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15708        self.display_map.read(cx).is_buffer_folded(buffer)
15709    }
15710
15711    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15712        self.display_map.read(cx).folded_buffers()
15713    }
15714
15715    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15716        self.display_map.update(cx, |display_map, cx| {
15717            display_map.disable_header_for_buffer(buffer_id, cx);
15718        });
15719        cx.notify();
15720    }
15721
15722    /// Removes any folds with the given ranges.
15723    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15724        &mut self,
15725        ranges: &[Range<T>],
15726        type_id: TypeId,
15727        auto_scroll: bool,
15728        cx: &mut Context<Self>,
15729    ) {
15730        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15731            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15732        });
15733        self.folds_did_change(cx);
15734    }
15735
15736    fn remove_folds_with<T: ToOffset + Clone>(
15737        &mut self,
15738        ranges: &[Range<T>],
15739        auto_scroll: bool,
15740        cx: &mut Context<Self>,
15741        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15742    ) {
15743        if ranges.is_empty() {
15744            return;
15745        }
15746
15747        let mut buffers_affected = HashSet::default();
15748        let multi_buffer = self.buffer().read(cx);
15749        for range in ranges {
15750            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15751                buffers_affected.insert(buffer.read(cx).remote_id());
15752            };
15753        }
15754
15755        self.display_map.update(cx, update);
15756
15757        if auto_scroll {
15758            self.request_autoscroll(Autoscroll::fit(), cx);
15759        }
15760
15761        cx.notify();
15762        self.scrollbar_marker_state.dirty = true;
15763        self.active_indent_guides_state.dirty = true;
15764    }
15765
15766    pub fn update_fold_widths(
15767        &mut self,
15768        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15769        cx: &mut Context<Self>,
15770    ) -> bool {
15771        self.display_map
15772            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15773    }
15774
15775    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15776        self.display_map.read(cx).fold_placeholder.clone()
15777    }
15778
15779    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15780        self.buffer.update(cx, |buffer, cx| {
15781            buffer.set_all_diff_hunks_expanded(cx);
15782        });
15783    }
15784
15785    pub fn expand_all_diff_hunks(
15786        &mut self,
15787        _: &ExpandAllDiffHunks,
15788        _window: &mut Window,
15789        cx: &mut Context<Self>,
15790    ) {
15791        self.buffer.update(cx, |buffer, cx| {
15792            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15793        });
15794    }
15795
15796    pub fn toggle_selected_diff_hunks(
15797        &mut self,
15798        _: &ToggleSelectedDiffHunks,
15799        _window: &mut Window,
15800        cx: &mut Context<Self>,
15801    ) {
15802        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15803        self.toggle_diff_hunks_in_ranges(ranges, cx);
15804    }
15805
15806    pub fn diff_hunks_in_ranges<'a>(
15807        &'a self,
15808        ranges: &'a [Range<Anchor>],
15809        buffer: &'a MultiBufferSnapshot,
15810    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15811        ranges.iter().flat_map(move |range| {
15812            let end_excerpt_id = range.end.excerpt_id;
15813            let range = range.to_point(buffer);
15814            let mut peek_end = range.end;
15815            if range.end.row < buffer.max_row().0 {
15816                peek_end = Point::new(range.end.row + 1, 0);
15817            }
15818            buffer
15819                .diff_hunks_in_range(range.start..peek_end)
15820                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15821        })
15822    }
15823
15824    pub fn has_stageable_diff_hunks_in_ranges(
15825        &self,
15826        ranges: &[Range<Anchor>],
15827        snapshot: &MultiBufferSnapshot,
15828    ) -> bool {
15829        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15830        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15831    }
15832
15833    pub fn toggle_staged_selected_diff_hunks(
15834        &mut self,
15835        _: &::git::ToggleStaged,
15836        _: &mut Window,
15837        cx: &mut Context<Self>,
15838    ) {
15839        let snapshot = self.buffer.read(cx).snapshot(cx);
15840        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15841        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15842        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15843    }
15844
15845    pub fn set_render_diff_hunk_controls(
15846        &mut self,
15847        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15848        cx: &mut Context<Self>,
15849    ) {
15850        self.render_diff_hunk_controls = render_diff_hunk_controls;
15851        cx.notify();
15852    }
15853
15854    pub fn stage_and_next(
15855        &mut self,
15856        _: &::git::StageAndNext,
15857        window: &mut Window,
15858        cx: &mut Context<Self>,
15859    ) {
15860        self.do_stage_or_unstage_and_next(true, window, cx);
15861    }
15862
15863    pub fn unstage_and_next(
15864        &mut self,
15865        _: &::git::UnstageAndNext,
15866        window: &mut Window,
15867        cx: &mut Context<Self>,
15868    ) {
15869        self.do_stage_or_unstage_and_next(false, window, cx);
15870    }
15871
15872    pub fn stage_or_unstage_diff_hunks(
15873        &mut self,
15874        stage: bool,
15875        ranges: Vec<Range<Anchor>>,
15876        cx: &mut Context<Self>,
15877    ) {
15878        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15879        cx.spawn(async move |this, cx| {
15880            task.await?;
15881            this.update(cx, |this, cx| {
15882                let snapshot = this.buffer.read(cx).snapshot(cx);
15883                let chunk_by = this
15884                    .diff_hunks_in_ranges(&ranges, &snapshot)
15885                    .chunk_by(|hunk| hunk.buffer_id);
15886                for (buffer_id, hunks) in &chunk_by {
15887                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15888                }
15889            })
15890        })
15891        .detach_and_log_err(cx);
15892    }
15893
15894    fn save_buffers_for_ranges_if_needed(
15895        &mut self,
15896        ranges: &[Range<Anchor>],
15897        cx: &mut Context<Editor>,
15898    ) -> Task<Result<()>> {
15899        let multibuffer = self.buffer.read(cx);
15900        let snapshot = multibuffer.read(cx);
15901        let buffer_ids: HashSet<_> = ranges
15902            .iter()
15903            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15904            .collect();
15905        drop(snapshot);
15906
15907        let mut buffers = HashSet::default();
15908        for buffer_id in buffer_ids {
15909            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15910                let buffer = buffer_entity.read(cx);
15911                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15912                {
15913                    buffers.insert(buffer_entity);
15914                }
15915            }
15916        }
15917
15918        if let Some(project) = &self.project {
15919            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15920        } else {
15921            Task::ready(Ok(()))
15922        }
15923    }
15924
15925    fn do_stage_or_unstage_and_next(
15926        &mut self,
15927        stage: bool,
15928        window: &mut Window,
15929        cx: &mut Context<Self>,
15930    ) {
15931        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15932
15933        if ranges.iter().any(|range| range.start != range.end) {
15934            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15935            return;
15936        }
15937
15938        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15939        let snapshot = self.snapshot(window, cx);
15940        let position = self.selections.newest::<Point>(cx).head();
15941        let mut row = snapshot
15942            .buffer_snapshot
15943            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15944            .find(|hunk| hunk.row_range.start.0 > position.row)
15945            .map(|hunk| hunk.row_range.start);
15946
15947        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15948        // Outside of the project diff editor, wrap around to the beginning.
15949        if !all_diff_hunks_expanded {
15950            row = row.or_else(|| {
15951                snapshot
15952                    .buffer_snapshot
15953                    .diff_hunks_in_range(Point::zero()..position)
15954                    .find(|hunk| hunk.row_range.end.0 < position.row)
15955                    .map(|hunk| hunk.row_range.start)
15956            });
15957        }
15958
15959        if let Some(row) = row {
15960            let destination = Point::new(row.0, 0);
15961            let autoscroll = Autoscroll::center();
15962
15963            self.unfold_ranges(&[destination..destination], false, false, cx);
15964            self.change_selections(Some(autoscroll), window, cx, |s| {
15965                s.select_ranges([destination..destination]);
15966            });
15967        }
15968    }
15969
15970    fn do_stage_or_unstage(
15971        &self,
15972        stage: bool,
15973        buffer_id: BufferId,
15974        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15975        cx: &mut App,
15976    ) -> Option<()> {
15977        let project = self.project.as_ref()?;
15978        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15979        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15980        let buffer_snapshot = buffer.read(cx).snapshot();
15981        let file_exists = buffer_snapshot
15982            .file()
15983            .is_some_and(|file| file.disk_state().exists());
15984        diff.update(cx, |diff, cx| {
15985            diff.stage_or_unstage_hunks(
15986                stage,
15987                &hunks
15988                    .map(|hunk| buffer_diff::DiffHunk {
15989                        buffer_range: hunk.buffer_range,
15990                        diff_base_byte_range: hunk.diff_base_byte_range,
15991                        secondary_status: hunk.secondary_status,
15992                        range: Point::zero()..Point::zero(), // unused
15993                    })
15994                    .collect::<Vec<_>>(),
15995                &buffer_snapshot,
15996                file_exists,
15997                cx,
15998            )
15999        });
16000        None
16001    }
16002
16003    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16004        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16005        self.buffer
16006            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16007    }
16008
16009    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16010        self.buffer.update(cx, |buffer, cx| {
16011            let ranges = vec![Anchor::min()..Anchor::max()];
16012            if !buffer.all_diff_hunks_expanded()
16013                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16014            {
16015                buffer.collapse_diff_hunks(ranges, cx);
16016                true
16017            } else {
16018                false
16019            }
16020        })
16021    }
16022
16023    fn toggle_diff_hunks_in_ranges(
16024        &mut self,
16025        ranges: Vec<Range<Anchor>>,
16026        cx: &mut Context<Editor>,
16027    ) {
16028        self.buffer.update(cx, |buffer, cx| {
16029            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16030            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16031        })
16032    }
16033
16034    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16035        self.buffer.update(cx, |buffer, cx| {
16036            let snapshot = buffer.snapshot(cx);
16037            let excerpt_id = range.end.excerpt_id;
16038            let point_range = range.to_point(&snapshot);
16039            let expand = !buffer.single_hunk_is_expanded(range, cx);
16040            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16041        })
16042    }
16043
16044    pub(crate) fn apply_all_diff_hunks(
16045        &mut self,
16046        _: &ApplyAllDiffHunks,
16047        window: &mut Window,
16048        cx: &mut Context<Self>,
16049    ) {
16050        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16051
16052        let buffers = self.buffer.read(cx).all_buffers();
16053        for branch_buffer in buffers {
16054            branch_buffer.update(cx, |branch_buffer, cx| {
16055                branch_buffer.merge_into_base(Vec::new(), cx);
16056            });
16057        }
16058
16059        if let Some(project) = self.project.clone() {
16060            self.save(true, project, window, cx).detach_and_log_err(cx);
16061        }
16062    }
16063
16064    pub(crate) fn apply_selected_diff_hunks(
16065        &mut self,
16066        _: &ApplyDiffHunk,
16067        window: &mut Window,
16068        cx: &mut Context<Self>,
16069    ) {
16070        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16071        let snapshot = self.snapshot(window, cx);
16072        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16073        let mut ranges_by_buffer = HashMap::default();
16074        self.transact(window, cx, |editor, _window, cx| {
16075            for hunk in hunks {
16076                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16077                    ranges_by_buffer
16078                        .entry(buffer.clone())
16079                        .or_insert_with(Vec::new)
16080                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16081                }
16082            }
16083
16084            for (buffer, ranges) in ranges_by_buffer {
16085                buffer.update(cx, |buffer, cx| {
16086                    buffer.merge_into_base(ranges, cx);
16087                });
16088            }
16089        });
16090
16091        if let Some(project) = self.project.clone() {
16092            self.save(true, project, window, cx).detach_and_log_err(cx);
16093        }
16094    }
16095
16096    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16097        if hovered != self.gutter_hovered {
16098            self.gutter_hovered = hovered;
16099            cx.notify();
16100        }
16101    }
16102
16103    pub fn insert_blocks(
16104        &mut self,
16105        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16106        autoscroll: Option<Autoscroll>,
16107        cx: &mut Context<Self>,
16108    ) -> Vec<CustomBlockId> {
16109        let blocks = self
16110            .display_map
16111            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16112        if let Some(autoscroll) = autoscroll {
16113            self.request_autoscroll(autoscroll, cx);
16114        }
16115        cx.notify();
16116        blocks
16117    }
16118
16119    pub fn resize_blocks(
16120        &mut self,
16121        heights: HashMap<CustomBlockId, u32>,
16122        autoscroll: Option<Autoscroll>,
16123        cx: &mut Context<Self>,
16124    ) {
16125        self.display_map
16126            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16127        if let Some(autoscroll) = autoscroll {
16128            self.request_autoscroll(autoscroll, cx);
16129        }
16130        cx.notify();
16131    }
16132
16133    pub fn replace_blocks(
16134        &mut self,
16135        renderers: HashMap<CustomBlockId, RenderBlock>,
16136        autoscroll: Option<Autoscroll>,
16137        cx: &mut Context<Self>,
16138    ) {
16139        self.display_map
16140            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16141        if let Some(autoscroll) = autoscroll {
16142            self.request_autoscroll(autoscroll, cx);
16143        }
16144        cx.notify();
16145    }
16146
16147    pub fn remove_blocks(
16148        &mut self,
16149        block_ids: HashSet<CustomBlockId>,
16150        autoscroll: Option<Autoscroll>,
16151        cx: &mut Context<Self>,
16152    ) {
16153        self.display_map.update(cx, |display_map, cx| {
16154            display_map.remove_blocks(block_ids, cx)
16155        });
16156        if let Some(autoscroll) = autoscroll {
16157            self.request_autoscroll(autoscroll, cx);
16158        }
16159        cx.notify();
16160    }
16161
16162    pub fn row_for_block(
16163        &self,
16164        block_id: CustomBlockId,
16165        cx: &mut Context<Self>,
16166    ) -> Option<DisplayRow> {
16167        self.display_map
16168            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16169    }
16170
16171    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16172        self.focused_block = Some(focused_block);
16173    }
16174
16175    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16176        self.focused_block.take()
16177    }
16178
16179    pub fn insert_creases(
16180        &mut self,
16181        creases: impl IntoIterator<Item = Crease<Anchor>>,
16182        cx: &mut Context<Self>,
16183    ) -> Vec<CreaseId> {
16184        self.display_map
16185            .update(cx, |map, cx| map.insert_creases(creases, cx))
16186    }
16187
16188    pub fn remove_creases(
16189        &mut self,
16190        ids: impl IntoIterator<Item = CreaseId>,
16191        cx: &mut Context<Self>,
16192    ) -> Vec<(CreaseId, Range<Anchor>)> {
16193        self.display_map
16194            .update(cx, |map, cx| map.remove_creases(ids, cx))
16195    }
16196
16197    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16198        self.display_map
16199            .update(cx, |map, cx| map.snapshot(cx))
16200            .longest_row()
16201    }
16202
16203    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16204        self.display_map
16205            .update(cx, |map, cx| map.snapshot(cx))
16206            .max_point()
16207    }
16208
16209    pub fn text(&self, cx: &App) -> String {
16210        self.buffer.read(cx).read(cx).text()
16211    }
16212
16213    pub fn is_empty(&self, cx: &App) -> bool {
16214        self.buffer.read(cx).read(cx).is_empty()
16215    }
16216
16217    pub fn text_option(&self, cx: &App) -> Option<String> {
16218        let text = self.text(cx);
16219        let text = text.trim();
16220
16221        if text.is_empty() {
16222            return None;
16223        }
16224
16225        Some(text.to_string())
16226    }
16227
16228    pub fn set_text(
16229        &mut self,
16230        text: impl Into<Arc<str>>,
16231        window: &mut Window,
16232        cx: &mut Context<Self>,
16233    ) {
16234        self.transact(window, cx, |this, _, cx| {
16235            this.buffer
16236                .read(cx)
16237                .as_singleton()
16238                .expect("you can only call set_text on editors for singleton buffers")
16239                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16240        });
16241    }
16242
16243    pub fn display_text(&self, cx: &mut App) -> String {
16244        self.display_map
16245            .update(cx, |map, cx| map.snapshot(cx))
16246            .text()
16247    }
16248
16249    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16250        let mut wrap_guides = smallvec::smallvec![];
16251
16252        if self.show_wrap_guides == Some(false) {
16253            return wrap_guides;
16254        }
16255
16256        let settings = self.buffer.read(cx).language_settings(cx);
16257        if settings.show_wrap_guides {
16258            match self.soft_wrap_mode(cx) {
16259                SoftWrap::Column(soft_wrap) => {
16260                    wrap_guides.push((soft_wrap as usize, true));
16261                }
16262                SoftWrap::Bounded(soft_wrap) => {
16263                    wrap_guides.push((soft_wrap as usize, true));
16264                }
16265                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16266            }
16267            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16268        }
16269
16270        wrap_guides
16271    }
16272
16273    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16274        let settings = self.buffer.read(cx).language_settings(cx);
16275        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16276        match mode {
16277            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16278                SoftWrap::None
16279            }
16280            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16281            language_settings::SoftWrap::PreferredLineLength => {
16282                SoftWrap::Column(settings.preferred_line_length)
16283            }
16284            language_settings::SoftWrap::Bounded => {
16285                SoftWrap::Bounded(settings.preferred_line_length)
16286            }
16287        }
16288    }
16289
16290    pub fn set_soft_wrap_mode(
16291        &mut self,
16292        mode: language_settings::SoftWrap,
16293
16294        cx: &mut Context<Self>,
16295    ) {
16296        self.soft_wrap_mode_override = Some(mode);
16297        cx.notify();
16298    }
16299
16300    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16301        self.hard_wrap = hard_wrap;
16302        cx.notify();
16303    }
16304
16305    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16306        self.text_style_refinement = Some(style);
16307    }
16308
16309    /// called by the Element so we know what style we were most recently rendered with.
16310    pub(crate) fn set_style(
16311        &mut self,
16312        style: EditorStyle,
16313        window: &mut Window,
16314        cx: &mut Context<Self>,
16315    ) {
16316        let rem_size = window.rem_size();
16317        self.display_map.update(cx, |map, cx| {
16318            map.set_font(
16319                style.text.font(),
16320                style.text.font_size.to_pixels(rem_size),
16321                cx,
16322            )
16323        });
16324        self.style = Some(style);
16325    }
16326
16327    pub fn style(&self) -> Option<&EditorStyle> {
16328        self.style.as_ref()
16329    }
16330
16331    // Called by the element. This method is not designed to be called outside of the editor
16332    // element's layout code because it does not notify when rewrapping is computed synchronously.
16333    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16334        self.display_map
16335            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16336    }
16337
16338    pub fn set_soft_wrap(&mut self) {
16339        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16340    }
16341
16342    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16343        if self.soft_wrap_mode_override.is_some() {
16344            self.soft_wrap_mode_override.take();
16345        } else {
16346            let soft_wrap = match self.soft_wrap_mode(cx) {
16347                SoftWrap::GitDiff => return,
16348                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16349                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16350                    language_settings::SoftWrap::None
16351                }
16352            };
16353            self.soft_wrap_mode_override = Some(soft_wrap);
16354        }
16355        cx.notify();
16356    }
16357
16358    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16359        let Some(workspace) = self.workspace() else {
16360            return;
16361        };
16362        let fs = workspace.read(cx).app_state().fs.clone();
16363        let current_show = TabBarSettings::get_global(cx).show;
16364        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16365            setting.show = Some(!current_show);
16366        });
16367    }
16368
16369    pub fn toggle_indent_guides(
16370        &mut self,
16371        _: &ToggleIndentGuides,
16372        _: &mut Window,
16373        cx: &mut Context<Self>,
16374    ) {
16375        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16376            self.buffer
16377                .read(cx)
16378                .language_settings(cx)
16379                .indent_guides
16380                .enabled
16381        });
16382        self.show_indent_guides = Some(!currently_enabled);
16383        cx.notify();
16384    }
16385
16386    fn should_show_indent_guides(&self) -> Option<bool> {
16387        self.show_indent_guides
16388    }
16389
16390    pub fn toggle_line_numbers(
16391        &mut self,
16392        _: &ToggleLineNumbers,
16393        _: &mut Window,
16394        cx: &mut Context<Self>,
16395    ) {
16396        let mut editor_settings = EditorSettings::get_global(cx).clone();
16397        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16398        EditorSettings::override_global(editor_settings, cx);
16399    }
16400
16401    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16402        if let Some(show_line_numbers) = self.show_line_numbers {
16403            return show_line_numbers;
16404        }
16405        EditorSettings::get_global(cx).gutter.line_numbers
16406    }
16407
16408    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16409        self.use_relative_line_numbers
16410            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16411    }
16412
16413    pub fn toggle_relative_line_numbers(
16414        &mut self,
16415        _: &ToggleRelativeLineNumbers,
16416        _: &mut Window,
16417        cx: &mut Context<Self>,
16418    ) {
16419        let is_relative = self.should_use_relative_line_numbers(cx);
16420        self.set_relative_line_number(Some(!is_relative), cx)
16421    }
16422
16423    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16424        self.use_relative_line_numbers = is_relative;
16425        cx.notify();
16426    }
16427
16428    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16429        self.show_gutter = show_gutter;
16430        cx.notify();
16431    }
16432
16433    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16434        self.show_scrollbars = show_scrollbars;
16435        cx.notify();
16436    }
16437
16438    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16439        self.show_line_numbers = Some(show_line_numbers);
16440        cx.notify();
16441    }
16442
16443    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16444        self.disable_expand_excerpt_buttons = true;
16445        cx.notify();
16446    }
16447
16448    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16449        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16450        cx.notify();
16451    }
16452
16453    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16454        self.show_code_actions = Some(show_code_actions);
16455        cx.notify();
16456    }
16457
16458    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16459        self.show_runnables = Some(show_runnables);
16460        cx.notify();
16461    }
16462
16463    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16464        self.show_breakpoints = Some(show_breakpoints);
16465        cx.notify();
16466    }
16467
16468    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16469        if self.display_map.read(cx).masked != masked {
16470            self.display_map.update(cx, |map, _| map.masked = masked);
16471        }
16472        cx.notify()
16473    }
16474
16475    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16476        self.show_wrap_guides = Some(show_wrap_guides);
16477        cx.notify();
16478    }
16479
16480    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16481        self.show_indent_guides = Some(show_indent_guides);
16482        cx.notify();
16483    }
16484
16485    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16486        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16487            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16488                if let Some(dir) = file.abs_path(cx).parent() {
16489                    return Some(dir.to_owned());
16490                }
16491            }
16492
16493            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16494                return Some(project_path.path.to_path_buf());
16495            }
16496        }
16497
16498        None
16499    }
16500
16501    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16502        self.active_excerpt(cx)?
16503            .1
16504            .read(cx)
16505            .file()
16506            .and_then(|f| f.as_local())
16507    }
16508
16509    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16510        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16511            let buffer = buffer.read(cx);
16512            if let Some(project_path) = buffer.project_path(cx) {
16513                let project = self.project.as_ref()?.read(cx);
16514                project.absolute_path(&project_path, cx)
16515            } else {
16516                buffer
16517                    .file()
16518                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16519            }
16520        })
16521    }
16522
16523    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16524        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16525            let project_path = buffer.read(cx).project_path(cx)?;
16526            let project = self.project.as_ref()?.read(cx);
16527            let entry = project.entry_for_path(&project_path, cx)?;
16528            let path = entry.path.to_path_buf();
16529            Some(path)
16530        })
16531    }
16532
16533    pub fn reveal_in_finder(
16534        &mut self,
16535        _: &RevealInFileManager,
16536        _window: &mut Window,
16537        cx: &mut Context<Self>,
16538    ) {
16539        if let Some(target) = self.target_file(cx) {
16540            cx.reveal_path(&target.abs_path(cx));
16541        }
16542    }
16543
16544    pub fn copy_path(
16545        &mut self,
16546        _: &zed_actions::workspace::CopyPath,
16547        _window: &mut Window,
16548        cx: &mut Context<Self>,
16549    ) {
16550        if let Some(path) = self.target_file_abs_path(cx) {
16551            if let Some(path) = path.to_str() {
16552                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16553            }
16554        }
16555    }
16556
16557    pub fn copy_relative_path(
16558        &mut self,
16559        _: &zed_actions::workspace::CopyRelativePath,
16560        _window: &mut Window,
16561        cx: &mut Context<Self>,
16562    ) {
16563        if let Some(path) = self.target_file_path(cx) {
16564            if let Some(path) = path.to_str() {
16565                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16566            }
16567        }
16568    }
16569
16570    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16571        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16572            buffer.read(cx).project_path(cx)
16573        } else {
16574            None
16575        }
16576    }
16577
16578    // Returns true if the editor handled a go-to-line request
16579    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16580        maybe!({
16581            let breakpoint_store = self.breakpoint_store.as_ref()?;
16582
16583            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16584            else {
16585                self.clear_row_highlights::<ActiveDebugLine>();
16586                return None;
16587            };
16588
16589            let position = active_stack_frame.position;
16590            let buffer_id = position.buffer_id?;
16591            let snapshot = self
16592                .project
16593                .as_ref()?
16594                .read(cx)
16595                .buffer_for_id(buffer_id, cx)?
16596                .read(cx)
16597                .snapshot();
16598
16599            let mut handled = false;
16600            for (id, ExcerptRange { context, .. }) in
16601                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16602            {
16603                if context.start.cmp(&position, &snapshot).is_ge()
16604                    || context.end.cmp(&position, &snapshot).is_lt()
16605                {
16606                    continue;
16607                }
16608                let snapshot = self.buffer.read(cx).snapshot(cx);
16609                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16610
16611                handled = true;
16612                self.clear_row_highlights::<ActiveDebugLine>();
16613                self.go_to_line::<ActiveDebugLine>(
16614                    multibuffer_anchor,
16615                    Some(cx.theme().colors().editor_debugger_active_line_background),
16616                    window,
16617                    cx,
16618                );
16619
16620                cx.notify();
16621            }
16622
16623            handled.then_some(())
16624        })
16625        .is_some()
16626    }
16627
16628    pub fn copy_file_name_without_extension(
16629        &mut self,
16630        _: &CopyFileNameWithoutExtension,
16631        _: &mut Window,
16632        cx: &mut Context<Self>,
16633    ) {
16634        if let Some(file) = self.target_file(cx) {
16635            if let Some(file_stem) = file.path().file_stem() {
16636                if let Some(name) = file_stem.to_str() {
16637                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16638                }
16639            }
16640        }
16641    }
16642
16643    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16644        if let Some(file) = self.target_file(cx) {
16645            if let Some(file_name) = file.path().file_name() {
16646                if let Some(name) = file_name.to_str() {
16647                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16648                }
16649            }
16650        }
16651    }
16652
16653    pub fn toggle_git_blame(
16654        &mut self,
16655        _: &::git::Blame,
16656        window: &mut Window,
16657        cx: &mut Context<Self>,
16658    ) {
16659        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16660
16661        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16662            self.start_git_blame(true, window, cx);
16663        }
16664
16665        cx.notify();
16666    }
16667
16668    pub fn toggle_git_blame_inline(
16669        &mut self,
16670        _: &ToggleGitBlameInline,
16671        window: &mut Window,
16672        cx: &mut Context<Self>,
16673    ) {
16674        self.toggle_git_blame_inline_internal(true, window, cx);
16675        cx.notify();
16676    }
16677
16678    pub fn open_git_blame_commit(
16679        &mut self,
16680        _: &OpenGitBlameCommit,
16681        window: &mut Window,
16682        cx: &mut Context<Self>,
16683    ) {
16684        self.open_git_blame_commit_internal(window, cx);
16685    }
16686
16687    fn open_git_blame_commit_internal(
16688        &mut self,
16689        window: &mut Window,
16690        cx: &mut Context<Self>,
16691    ) -> Option<()> {
16692        let blame = self.blame.as_ref()?;
16693        let snapshot = self.snapshot(window, cx);
16694        let cursor = self.selections.newest::<Point>(cx).head();
16695        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16696        let blame_entry = blame
16697            .update(cx, |blame, cx| {
16698                blame
16699                    .blame_for_rows(
16700                        &[RowInfo {
16701                            buffer_id: Some(buffer.remote_id()),
16702                            buffer_row: Some(point.row),
16703                            ..Default::default()
16704                        }],
16705                        cx,
16706                    )
16707                    .next()
16708            })
16709            .flatten()?;
16710        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16711        let repo = blame.read(cx).repository(cx)?;
16712        let workspace = self.workspace()?.downgrade();
16713        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16714        None
16715    }
16716
16717    pub fn git_blame_inline_enabled(&self) -> bool {
16718        self.git_blame_inline_enabled
16719    }
16720
16721    pub fn toggle_selection_menu(
16722        &mut self,
16723        _: &ToggleSelectionMenu,
16724        _: &mut Window,
16725        cx: &mut Context<Self>,
16726    ) {
16727        self.show_selection_menu = self
16728            .show_selection_menu
16729            .map(|show_selections_menu| !show_selections_menu)
16730            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16731
16732        cx.notify();
16733    }
16734
16735    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16736        self.show_selection_menu
16737            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16738    }
16739
16740    fn start_git_blame(
16741        &mut self,
16742        user_triggered: bool,
16743        window: &mut Window,
16744        cx: &mut Context<Self>,
16745    ) {
16746        if let Some(project) = self.project.as_ref() {
16747            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16748                return;
16749            };
16750
16751            if buffer.read(cx).file().is_none() {
16752                return;
16753            }
16754
16755            let focused = self.focus_handle(cx).contains_focused(window, cx);
16756
16757            let project = project.clone();
16758            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16759            self.blame_subscription =
16760                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16761            self.blame = Some(blame);
16762        }
16763    }
16764
16765    fn toggle_git_blame_inline_internal(
16766        &mut self,
16767        user_triggered: bool,
16768        window: &mut Window,
16769        cx: &mut Context<Self>,
16770    ) {
16771        if self.git_blame_inline_enabled {
16772            self.git_blame_inline_enabled = false;
16773            self.show_git_blame_inline = false;
16774            self.show_git_blame_inline_delay_task.take();
16775        } else {
16776            self.git_blame_inline_enabled = true;
16777            self.start_git_blame_inline(user_triggered, window, cx);
16778        }
16779
16780        cx.notify();
16781    }
16782
16783    fn start_git_blame_inline(
16784        &mut self,
16785        user_triggered: bool,
16786        window: &mut Window,
16787        cx: &mut Context<Self>,
16788    ) {
16789        self.start_git_blame(user_triggered, window, cx);
16790
16791        if ProjectSettings::get_global(cx)
16792            .git
16793            .inline_blame_delay()
16794            .is_some()
16795        {
16796            self.start_inline_blame_timer(window, cx);
16797        } else {
16798            self.show_git_blame_inline = true
16799        }
16800    }
16801
16802    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16803        self.blame.as_ref()
16804    }
16805
16806    pub fn show_git_blame_gutter(&self) -> bool {
16807        self.show_git_blame_gutter
16808    }
16809
16810    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16811        self.show_git_blame_gutter && self.has_blame_entries(cx)
16812    }
16813
16814    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16815        self.show_git_blame_inline
16816            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16817            && !self.newest_selection_head_on_empty_line(cx)
16818            && self.has_blame_entries(cx)
16819    }
16820
16821    fn has_blame_entries(&self, cx: &App) -> bool {
16822        self.blame()
16823            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16824    }
16825
16826    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16827        let cursor_anchor = self.selections.newest_anchor().head();
16828
16829        let snapshot = self.buffer.read(cx).snapshot(cx);
16830        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16831
16832        snapshot.line_len(buffer_row) == 0
16833    }
16834
16835    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16836        let buffer_and_selection = maybe!({
16837            let selection = self.selections.newest::<Point>(cx);
16838            let selection_range = selection.range();
16839
16840            let multi_buffer = self.buffer().read(cx);
16841            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16842            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16843
16844            let (buffer, range, _) = if selection.reversed {
16845                buffer_ranges.first()
16846            } else {
16847                buffer_ranges.last()
16848            }?;
16849
16850            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16851                ..text::ToPoint::to_point(&range.end, &buffer).row;
16852            Some((
16853                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16854                selection,
16855            ))
16856        });
16857
16858        let Some((buffer, selection)) = buffer_and_selection else {
16859            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16860        };
16861
16862        let Some(project) = self.project.as_ref() else {
16863            return Task::ready(Err(anyhow!("editor does not have project")));
16864        };
16865
16866        project.update(cx, |project, cx| {
16867            project.get_permalink_to_line(&buffer, selection, cx)
16868        })
16869    }
16870
16871    pub fn copy_permalink_to_line(
16872        &mut self,
16873        _: &CopyPermalinkToLine,
16874        window: &mut Window,
16875        cx: &mut Context<Self>,
16876    ) {
16877        let permalink_task = self.get_permalink_to_line(cx);
16878        let workspace = self.workspace();
16879
16880        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16881            Ok(permalink) => {
16882                cx.update(|_, cx| {
16883                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16884                })
16885                .ok();
16886            }
16887            Err(err) => {
16888                let message = format!("Failed to copy permalink: {err}");
16889
16890                Err::<(), anyhow::Error>(err).log_err();
16891
16892                if let Some(workspace) = workspace {
16893                    workspace
16894                        .update_in(cx, |workspace, _, cx| {
16895                            struct CopyPermalinkToLine;
16896
16897                            workspace.show_toast(
16898                                Toast::new(
16899                                    NotificationId::unique::<CopyPermalinkToLine>(),
16900                                    message,
16901                                ),
16902                                cx,
16903                            )
16904                        })
16905                        .ok();
16906                }
16907            }
16908        })
16909        .detach();
16910    }
16911
16912    pub fn copy_file_location(
16913        &mut self,
16914        _: &CopyFileLocation,
16915        _: &mut Window,
16916        cx: &mut Context<Self>,
16917    ) {
16918        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16919        if let Some(file) = self.target_file(cx) {
16920            if let Some(path) = file.path().to_str() {
16921                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16922            }
16923        }
16924    }
16925
16926    pub fn open_permalink_to_line(
16927        &mut self,
16928        _: &OpenPermalinkToLine,
16929        window: &mut Window,
16930        cx: &mut Context<Self>,
16931    ) {
16932        let permalink_task = self.get_permalink_to_line(cx);
16933        let workspace = self.workspace();
16934
16935        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16936            Ok(permalink) => {
16937                cx.update(|_, cx| {
16938                    cx.open_url(permalink.as_ref());
16939                })
16940                .ok();
16941            }
16942            Err(err) => {
16943                let message = format!("Failed to open permalink: {err}");
16944
16945                Err::<(), anyhow::Error>(err).log_err();
16946
16947                if let Some(workspace) = workspace {
16948                    workspace
16949                        .update(cx, |workspace, cx| {
16950                            struct OpenPermalinkToLine;
16951
16952                            workspace.show_toast(
16953                                Toast::new(
16954                                    NotificationId::unique::<OpenPermalinkToLine>(),
16955                                    message,
16956                                ),
16957                                cx,
16958                            )
16959                        })
16960                        .ok();
16961                }
16962            }
16963        })
16964        .detach();
16965    }
16966
16967    pub fn insert_uuid_v4(
16968        &mut self,
16969        _: &InsertUuidV4,
16970        window: &mut Window,
16971        cx: &mut Context<Self>,
16972    ) {
16973        self.insert_uuid(UuidVersion::V4, window, cx);
16974    }
16975
16976    pub fn insert_uuid_v7(
16977        &mut self,
16978        _: &InsertUuidV7,
16979        window: &mut Window,
16980        cx: &mut Context<Self>,
16981    ) {
16982        self.insert_uuid(UuidVersion::V7, window, cx);
16983    }
16984
16985    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16986        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16987        self.transact(window, cx, |this, window, cx| {
16988            let edits = this
16989                .selections
16990                .all::<Point>(cx)
16991                .into_iter()
16992                .map(|selection| {
16993                    let uuid = match version {
16994                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16995                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16996                    };
16997
16998                    (selection.range(), uuid.to_string())
16999                });
17000            this.edit(edits, cx);
17001            this.refresh_inline_completion(true, false, window, cx);
17002        });
17003    }
17004
17005    pub fn open_selections_in_multibuffer(
17006        &mut self,
17007        _: &OpenSelectionsInMultibuffer,
17008        window: &mut Window,
17009        cx: &mut Context<Self>,
17010    ) {
17011        let multibuffer = self.buffer.read(cx);
17012
17013        let Some(buffer) = multibuffer.as_singleton() else {
17014            return;
17015        };
17016
17017        let Some(workspace) = self.workspace() else {
17018            return;
17019        };
17020
17021        let locations = self
17022            .selections
17023            .disjoint_anchors()
17024            .iter()
17025            .map(|range| Location {
17026                buffer: buffer.clone(),
17027                range: range.start.text_anchor..range.end.text_anchor,
17028            })
17029            .collect::<Vec<_>>();
17030
17031        let title = multibuffer.title(cx).to_string();
17032
17033        cx.spawn_in(window, async move |_, cx| {
17034            workspace.update_in(cx, |workspace, window, cx| {
17035                Self::open_locations_in_multibuffer(
17036                    workspace,
17037                    locations,
17038                    format!("Selections for '{title}'"),
17039                    false,
17040                    MultibufferSelectionMode::All,
17041                    window,
17042                    cx,
17043                );
17044            })
17045        })
17046        .detach();
17047    }
17048
17049    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17050    /// last highlight added will be used.
17051    ///
17052    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17053    pub fn highlight_rows<T: 'static>(
17054        &mut self,
17055        range: Range<Anchor>,
17056        color: Hsla,
17057        options: RowHighlightOptions,
17058        cx: &mut Context<Self>,
17059    ) {
17060        let snapshot = self.buffer().read(cx).snapshot(cx);
17061        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17062        let ix = row_highlights.binary_search_by(|highlight| {
17063            Ordering::Equal
17064                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17065                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17066        });
17067
17068        if let Err(mut ix) = ix {
17069            let index = post_inc(&mut self.highlight_order);
17070
17071            // If this range intersects with the preceding highlight, then merge it with
17072            // the preceding highlight. Otherwise insert a new highlight.
17073            let mut merged = false;
17074            if ix > 0 {
17075                let prev_highlight = &mut row_highlights[ix - 1];
17076                if prev_highlight
17077                    .range
17078                    .end
17079                    .cmp(&range.start, &snapshot)
17080                    .is_ge()
17081                {
17082                    ix -= 1;
17083                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17084                        prev_highlight.range.end = range.end;
17085                    }
17086                    merged = true;
17087                    prev_highlight.index = index;
17088                    prev_highlight.color = color;
17089                    prev_highlight.options = options;
17090                }
17091            }
17092
17093            if !merged {
17094                row_highlights.insert(
17095                    ix,
17096                    RowHighlight {
17097                        range: range.clone(),
17098                        index,
17099                        color,
17100                        options,
17101                        type_id: TypeId::of::<T>(),
17102                    },
17103                );
17104            }
17105
17106            // If any of the following highlights intersect with this one, merge them.
17107            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17108                let highlight = &row_highlights[ix];
17109                if next_highlight
17110                    .range
17111                    .start
17112                    .cmp(&highlight.range.end, &snapshot)
17113                    .is_le()
17114                {
17115                    if next_highlight
17116                        .range
17117                        .end
17118                        .cmp(&highlight.range.end, &snapshot)
17119                        .is_gt()
17120                    {
17121                        row_highlights[ix].range.end = next_highlight.range.end;
17122                    }
17123                    row_highlights.remove(ix + 1);
17124                } else {
17125                    break;
17126                }
17127            }
17128        }
17129    }
17130
17131    /// Remove any highlighted row ranges of the given type that intersect the
17132    /// given ranges.
17133    pub fn remove_highlighted_rows<T: 'static>(
17134        &mut self,
17135        ranges_to_remove: Vec<Range<Anchor>>,
17136        cx: &mut Context<Self>,
17137    ) {
17138        let snapshot = self.buffer().read(cx).snapshot(cx);
17139        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17140        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17141        row_highlights.retain(|highlight| {
17142            while let Some(range_to_remove) = ranges_to_remove.peek() {
17143                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17144                    Ordering::Less | Ordering::Equal => {
17145                        ranges_to_remove.next();
17146                    }
17147                    Ordering::Greater => {
17148                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17149                            Ordering::Less | Ordering::Equal => {
17150                                return false;
17151                            }
17152                            Ordering::Greater => break,
17153                        }
17154                    }
17155                }
17156            }
17157
17158            true
17159        })
17160    }
17161
17162    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17163    pub fn clear_row_highlights<T: 'static>(&mut self) {
17164        self.highlighted_rows.remove(&TypeId::of::<T>());
17165    }
17166
17167    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17168    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17169        self.highlighted_rows
17170            .get(&TypeId::of::<T>())
17171            .map_or(&[] as &[_], |vec| vec.as_slice())
17172            .iter()
17173            .map(|highlight| (highlight.range.clone(), highlight.color))
17174    }
17175
17176    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17177    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17178    /// Allows to ignore certain kinds of highlights.
17179    pub fn highlighted_display_rows(
17180        &self,
17181        window: &mut Window,
17182        cx: &mut App,
17183    ) -> BTreeMap<DisplayRow, LineHighlight> {
17184        let snapshot = self.snapshot(window, cx);
17185        let mut used_highlight_orders = HashMap::default();
17186        self.highlighted_rows
17187            .iter()
17188            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17189            .fold(
17190                BTreeMap::<DisplayRow, LineHighlight>::new(),
17191                |mut unique_rows, highlight| {
17192                    let start = highlight.range.start.to_display_point(&snapshot);
17193                    let end = highlight.range.end.to_display_point(&snapshot);
17194                    let start_row = start.row().0;
17195                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17196                        && end.column() == 0
17197                    {
17198                        end.row().0.saturating_sub(1)
17199                    } else {
17200                        end.row().0
17201                    };
17202                    for row in start_row..=end_row {
17203                        let used_index =
17204                            used_highlight_orders.entry(row).or_insert(highlight.index);
17205                        if highlight.index >= *used_index {
17206                            *used_index = highlight.index;
17207                            unique_rows.insert(
17208                                DisplayRow(row),
17209                                LineHighlight {
17210                                    include_gutter: highlight.options.include_gutter,
17211                                    border: None,
17212                                    background: highlight.color.into(),
17213                                    type_id: Some(highlight.type_id),
17214                                },
17215                            );
17216                        }
17217                    }
17218                    unique_rows
17219                },
17220            )
17221    }
17222
17223    pub fn highlighted_display_row_for_autoscroll(
17224        &self,
17225        snapshot: &DisplaySnapshot,
17226    ) -> Option<DisplayRow> {
17227        self.highlighted_rows
17228            .values()
17229            .flat_map(|highlighted_rows| highlighted_rows.iter())
17230            .filter_map(|highlight| {
17231                if highlight.options.autoscroll {
17232                    Some(highlight.range.start.to_display_point(snapshot).row())
17233                } else {
17234                    None
17235                }
17236            })
17237            .min()
17238    }
17239
17240    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17241        self.highlight_background::<SearchWithinRange>(
17242            ranges,
17243            |colors| colors.editor_document_highlight_read_background,
17244            cx,
17245        )
17246    }
17247
17248    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17249        self.breadcrumb_header = Some(new_header);
17250    }
17251
17252    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17253        self.clear_background_highlights::<SearchWithinRange>(cx);
17254    }
17255
17256    pub fn highlight_background<T: 'static>(
17257        &mut self,
17258        ranges: &[Range<Anchor>],
17259        color_fetcher: fn(&ThemeColors) -> Hsla,
17260        cx: &mut Context<Self>,
17261    ) {
17262        self.background_highlights
17263            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17264        self.scrollbar_marker_state.dirty = true;
17265        cx.notify();
17266    }
17267
17268    pub fn clear_background_highlights<T: 'static>(
17269        &mut self,
17270        cx: &mut Context<Self>,
17271    ) -> Option<BackgroundHighlight> {
17272        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17273        if !text_highlights.1.is_empty() {
17274            self.scrollbar_marker_state.dirty = true;
17275            cx.notify();
17276        }
17277        Some(text_highlights)
17278    }
17279
17280    pub fn highlight_gutter<T: 'static>(
17281        &mut self,
17282        ranges: &[Range<Anchor>],
17283        color_fetcher: fn(&App) -> Hsla,
17284        cx: &mut Context<Self>,
17285    ) {
17286        self.gutter_highlights
17287            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17288        cx.notify();
17289    }
17290
17291    pub fn clear_gutter_highlights<T: 'static>(
17292        &mut self,
17293        cx: &mut Context<Self>,
17294    ) -> Option<GutterHighlight> {
17295        cx.notify();
17296        self.gutter_highlights.remove(&TypeId::of::<T>())
17297    }
17298
17299    #[cfg(feature = "test-support")]
17300    pub fn all_text_background_highlights(
17301        &self,
17302        window: &mut Window,
17303        cx: &mut Context<Self>,
17304    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17305        let snapshot = self.snapshot(window, cx);
17306        let buffer = &snapshot.buffer_snapshot;
17307        let start = buffer.anchor_before(0);
17308        let end = buffer.anchor_after(buffer.len());
17309        let theme = cx.theme().colors();
17310        self.background_highlights_in_range(start..end, &snapshot, theme)
17311    }
17312
17313    #[cfg(feature = "test-support")]
17314    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17315        let snapshot = self.buffer().read(cx).snapshot(cx);
17316
17317        let highlights = self
17318            .background_highlights
17319            .get(&TypeId::of::<items::BufferSearchHighlights>());
17320
17321        if let Some((_color, ranges)) = highlights {
17322            ranges
17323                .iter()
17324                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17325                .collect_vec()
17326        } else {
17327            vec![]
17328        }
17329    }
17330
17331    fn document_highlights_for_position<'a>(
17332        &'a self,
17333        position: Anchor,
17334        buffer: &'a MultiBufferSnapshot,
17335    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17336        let read_highlights = self
17337            .background_highlights
17338            .get(&TypeId::of::<DocumentHighlightRead>())
17339            .map(|h| &h.1);
17340        let write_highlights = self
17341            .background_highlights
17342            .get(&TypeId::of::<DocumentHighlightWrite>())
17343            .map(|h| &h.1);
17344        let left_position = position.bias_left(buffer);
17345        let right_position = position.bias_right(buffer);
17346        read_highlights
17347            .into_iter()
17348            .chain(write_highlights)
17349            .flat_map(move |ranges| {
17350                let start_ix = match ranges.binary_search_by(|probe| {
17351                    let cmp = probe.end.cmp(&left_position, buffer);
17352                    if cmp.is_ge() {
17353                        Ordering::Greater
17354                    } else {
17355                        Ordering::Less
17356                    }
17357                }) {
17358                    Ok(i) | Err(i) => i,
17359                };
17360
17361                ranges[start_ix..]
17362                    .iter()
17363                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17364            })
17365    }
17366
17367    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17368        self.background_highlights
17369            .get(&TypeId::of::<T>())
17370            .map_or(false, |(_, highlights)| !highlights.is_empty())
17371    }
17372
17373    pub fn background_highlights_in_range(
17374        &self,
17375        search_range: Range<Anchor>,
17376        display_snapshot: &DisplaySnapshot,
17377        theme: &ThemeColors,
17378    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17379        let mut results = Vec::new();
17380        for (color_fetcher, ranges) in self.background_highlights.values() {
17381            let color = color_fetcher(theme);
17382            let start_ix = match ranges.binary_search_by(|probe| {
17383                let cmp = probe
17384                    .end
17385                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17386                if cmp.is_gt() {
17387                    Ordering::Greater
17388                } else {
17389                    Ordering::Less
17390                }
17391            }) {
17392                Ok(i) | Err(i) => i,
17393            };
17394            for range in &ranges[start_ix..] {
17395                if range
17396                    .start
17397                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17398                    .is_ge()
17399                {
17400                    break;
17401                }
17402
17403                let start = range.start.to_display_point(display_snapshot);
17404                let end = range.end.to_display_point(display_snapshot);
17405                results.push((start..end, color))
17406            }
17407        }
17408        results
17409    }
17410
17411    pub fn background_highlight_row_ranges<T: 'static>(
17412        &self,
17413        search_range: Range<Anchor>,
17414        display_snapshot: &DisplaySnapshot,
17415        count: usize,
17416    ) -> Vec<RangeInclusive<DisplayPoint>> {
17417        let mut results = Vec::new();
17418        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17419            return vec![];
17420        };
17421
17422        let start_ix = match ranges.binary_search_by(|probe| {
17423            let cmp = probe
17424                .end
17425                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17426            if cmp.is_gt() {
17427                Ordering::Greater
17428            } else {
17429                Ordering::Less
17430            }
17431        }) {
17432            Ok(i) | Err(i) => i,
17433        };
17434        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17435            if let (Some(start_display), Some(end_display)) = (start, end) {
17436                results.push(
17437                    start_display.to_display_point(display_snapshot)
17438                        ..=end_display.to_display_point(display_snapshot),
17439                );
17440            }
17441        };
17442        let mut start_row: Option<Point> = None;
17443        let mut end_row: Option<Point> = None;
17444        if ranges.len() > count {
17445            return Vec::new();
17446        }
17447        for range in &ranges[start_ix..] {
17448            if range
17449                .start
17450                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17451                .is_ge()
17452            {
17453                break;
17454            }
17455            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17456            if let Some(current_row) = &end_row {
17457                if end.row == current_row.row {
17458                    continue;
17459                }
17460            }
17461            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17462            if start_row.is_none() {
17463                assert_eq!(end_row, None);
17464                start_row = Some(start);
17465                end_row = Some(end);
17466                continue;
17467            }
17468            if let Some(current_end) = end_row.as_mut() {
17469                if start.row > current_end.row + 1 {
17470                    push_region(start_row, end_row);
17471                    start_row = Some(start);
17472                    end_row = Some(end);
17473                } else {
17474                    // Merge two hunks.
17475                    *current_end = end;
17476                }
17477            } else {
17478                unreachable!();
17479            }
17480        }
17481        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17482        push_region(start_row, end_row);
17483        results
17484    }
17485
17486    pub fn gutter_highlights_in_range(
17487        &self,
17488        search_range: Range<Anchor>,
17489        display_snapshot: &DisplaySnapshot,
17490        cx: &App,
17491    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17492        let mut results = Vec::new();
17493        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17494            let color = color_fetcher(cx);
17495            let start_ix = match ranges.binary_search_by(|probe| {
17496                let cmp = probe
17497                    .end
17498                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17499                if cmp.is_gt() {
17500                    Ordering::Greater
17501                } else {
17502                    Ordering::Less
17503                }
17504            }) {
17505                Ok(i) | Err(i) => i,
17506            };
17507            for range in &ranges[start_ix..] {
17508                if range
17509                    .start
17510                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17511                    .is_ge()
17512                {
17513                    break;
17514                }
17515
17516                let start = range.start.to_display_point(display_snapshot);
17517                let end = range.end.to_display_point(display_snapshot);
17518                results.push((start..end, color))
17519            }
17520        }
17521        results
17522    }
17523
17524    /// Get the text ranges corresponding to the redaction query
17525    pub fn redacted_ranges(
17526        &self,
17527        search_range: Range<Anchor>,
17528        display_snapshot: &DisplaySnapshot,
17529        cx: &App,
17530    ) -> Vec<Range<DisplayPoint>> {
17531        display_snapshot
17532            .buffer_snapshot
17533            .redacted_ranges(search_range, |file| {
17534                if let Some(file) = file {
17535                    file.is_private()
17536                        && EditorSettings::get(
17537                            Some(SettingsLocation {
17538                                worktree_id: file.worktree_id(cx),
17539                                path: file.path().as_ref(),
17540                            }),
17541                            cx,
17542                        )
17543                        .redact_private_values
17544                } else {
17545                    false
17546                }
17547            })
17548            .map(|range| {
17549                range.start.to_display_point(display_snapshot)
17550                    ..range.end.to_display_point(display_snapshot)
17551            })
17552            .collect()
17553    }
17554
17555    pub fn highlight_text<T: 'static>(
17556        &mut self,
17557        ranges: Vec<Range<Anchor>>,
17558        style: HighlightStyle,
17559        cx: &mut Context<Self>,
17560    ) {
17561        self.display_map.update(cx, |map, _| {
17562            map.highlight_text(TypeId::of::<T>(), ranges, style)
17563        });
17564        cx.notify();
17565    }
17566
17567    pub(crate) fn highlight_inlays<T: 'static>(
17568        &mut self,
17569        highlights: Vec<InlayHighlight>,
17570        style: HighlightStyle,
17571        cx: &mut Context<Self>,
17572    ) {
17573        self.display_map.update(cx, |map, _| {
17574            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17575        });
17576        cx.notify();
17577    }
17578
17579    pub fn text_highlights<'a, T: 'static>(
17580        &'a self,
17581        cx: &'a App,
17582    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17583        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17584    }
17585
17586    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17587        let cleared = self
17588            .display_map
17589            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17590        if cleared {
17591            cx.notify();
17592        }
17593    }
17594
17595    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17596        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17597            && self.focus_handle.is_focused(window)
17598    }
17599
17600    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17601        self.show_cursor_when_unfocused = is_enabled;
17602        cx.notify();
17603    }
17604
17605    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17606        cx.notify();
17607    }
17608
17609    fn on_debug_session_event(
17610        &mut self,
17611        _session: Entity<Session>,
17612        event: &SessionEvent,
17613        cx: &mut Context<Self>,
17614    ) {
17615        match event {
17616            SessionEvent::InvalidateInlineValue => {
17617                self.refresh_inline_values(cx);
17618            }
17619            _ => {}
17620        }
17621    }
17622
17623    pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17624        let Some(project) = self.project.clone() else {
17625            return;
17626        };
17627        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17628            return;
17629        };
17630        if !self.inline_value_cache.enabled {
17631            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17632            self.splice_inlays(&inlays, Vec::new(), cx);
17633            return;
17634        }
17635
17636        let current_execution_position = self
17637            .highlighted_rows
17638            .get(&TypeId::of::<ActiveDebugLine>())
17639            .and_then(|lines| lines.last().map(|line| line.range.start));
17640
17641        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17642            let snapshot = editor
17643                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17644                .ok()?;
17645
17646            let inline_values = editor
17647                .update(cx, |_, cx| {
17648                    let Some(current_execution_position) = current_execution_position else {
17649                        return Some(Task::ready(Ok(Vec::new())));
17650                    };
17651
17652                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17653                    // anchor is in the same buffer
17654                    let range =
17655                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17656                    project.inline_values(buffer, range, cx)
17657                })
17658                .ok()
17659                .flatten()?
17660                .await
17661                .context("refreshing debugger inlays")
17662                .log_err()?;
17663
17664            let (excerpt_id, buffer_id) = snapshot
17665                .excerpts()
17666                .next()
17667                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17668            editor
17669                .update(cx, |editor, cx| {
17670                    let new_inlays = inline_values
17671                        .into_iter()
17672                        .map(|debugger_value| {
17673                            Inlay::debugger_hint(
17674                                post_inc(&mut editor.next_inlay_id),
17675                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17676                                debugger_value.text(),
17677                            )
17678                        })
17679                        .collect::<Vec<_>>();
17680                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17681                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17682
17683                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17684                })
17685                .ok()?;
17686            Some(())
17687        });
17688    }
17689
17690    fn on_buffer_event(
17691        &mut self,
17692        multibuffer: &Entity<MultiBuffer>,
17693        event: &multi_buffer::Event,
17694        window: &mut Window,
17695        cx: &mut Context<Self>,
17696    ) {
17697        match event {
17698            multi_buffer::Event::Edited {
17699                singleton_buffer_edited,
17700                edited_buffer: buffer_edited,
17701            } => {
17702                self.scrollbar_marker_state.dirty = true;
17703                self.active_indent_guides_state.dirty = true;
17704                self.refresh_active_diagnostics(cx);
17705                self.refresh_code_actions(window, cx);
17706                self.refresh_selected_text_highlights(true, window, cx);
17707                refresh_matching_bracket_highlights(self, window, cx);
17708                if self.has_active_inline_completion() {
17709                    self.update_visible_inline_completion(window, cx);
17710                }
17711                if let Some(buffer) = buffer_edited {
17712                    let buffer_id = buffer.read(cx).remote_id();
17713                    if !self.registered_buffers.contains_key(&buffer_id) {
17714                        if let Some(project) = self.project.as_ref() {
17715                            project.update(cx, |project, cx| {
17716                                self.registered_buffers.insert(
17717                                    buffer_id,
17718                                    project.register_buffer_with_language_servers(&buffer, cx),
17719                                );
17720                            })
17721                        }
17722                    }
17723                }
17724                cx.emit(EditorEvent::BufferEdited);
17725                cx.emit(SearchEvent::MatchesInvalidated);
17726                if *singleton_buffer_edited {
17727                    if let Some(project) = &self.project {
17728                        #[allow(clippy::mutable_key_type)]
17729                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17730                            multibuffer
17731                                .all_buffers()
17732                                .into_iter()
17733                                .filter_map(|buffer| {
17734                                    buffer.update(cx, |buffer, cx| {
17735                                        let language = buffer.language()?;
17736                                        let should_discard = project.update(cx, |project, cx| {
17737                                            project.is_local()
17738                                                && !project.has_language_servers_for(buffer, cx)
17739                                        });
17740                                        should_discard.not().then_some(language.clone())
17741                                    })
17742                                })
17743                                .collect::<HashSet<_>>()
17744                        });
17745                        if !languages_affected.is_empty() {
17746                            self.refresh_inlay_hints(
17747                                InlayHintRefreshReason::BufferEdited(languages_affected),
17748                                cx,
17749                            );
17750                        }
17751                    }
17752                }
17753
17754                let Some(project) = &self.project else { return };
17755                let (telemetry, is_via_ssh) = {
17756                    let project = project.read(cx);
17757                    let telemetry = project.client().telemetry().clone();
17758                    let is_via_ssh = project.is_via_ssh();
17759                    (telemetry, is_via_ssh)
17760                };
17761                refresh_linked_ranges(self, window, cx);
17762                telemetry.log_edit_event("editor", is_via_ssh);
17763            }
17764            multi_buffer::Event::ExcerptsAdded {
17765                buffer,
17766                predecessor,
17767                excerpts,
17768            } => {
17769                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17770                let buffer_id = buffer.read(cx).remote_id();
17771                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17772                    if let Some(project) = &self.project {
17773                        update_uncommitted_diff_for_buffer(
17774                            cx.entity(),
17775                            project,
17776                            [buffer.clone()],
17777                            self.buffer.clone(),
17778                            cx,
17779                        )
17780                        .detach();
17781                    }
17782                }
17783                cx.emit(EditorEvent::ExcerptsAdded {
17784                    buffer: buffer.clone(),
17785                    predecessor: *predecessor,
17786                    excerpts: excerpts.clone(),
17787                });
17788                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17789            }
17790            multi_buffer::Event::ExcerptsRemoved {
17791                ids,
17792                removed_buffer_ids,
17793            } => {
17794                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17795                let buffer = self.buffer.read(cx);
17796                self.registered_buffers
17797                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17798                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17799                cx.emit(EditorEvent::ExcerptsRemoved {
17800                    ids: ids.clone(),
17801                    removed_buffer_ids: removed_buffer_ids.clone(),
17802                })
17803            }
17804            multi_buffer::Event::ExcerptsEdited {
17805                excerpt_ids,
17806                buffer_ids,
17807            } => {
17808                self.display_map.update(cx, |map, cx| {
17809                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17810                });
17811                cx.emit(EditorEvent::ExcerptsEdited {
17812                    ids: excerpt_ids.clone(),
17813                })
17814            }
17815            multi_buffer::Event::ExcerptsExpanded { ids } => {
17816                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17817                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17818            }
17819            multi_buffer::Event::Reparsed(buffer_id) => {
17820                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17821                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17822
17823                cx.emit(EditorEvent::Reparsed(*buffer_id));
17824            }
17825            multi_buffer::Event::DiffHunksToggled => {
17826                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17827            }
17828            multi_buffer::Event::LanguageChanged(buffer_id) => {
17829                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17830                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17831                cx.emit(EditorEvent::Reparsed(*buffer_id));
17832                cx.notify();
17833            }
17834            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17835            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17836            multi_buffer::Event::FileHandleChanged
17837            | multi_buffer::Event::Reloaded
17838            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17839            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17840            multi_buffer::Event::DiagnosticsUpdated => {
17841                self.refresh_active_diagnostics(cx);
17842                self.refresh_inline_diagnostics(true, window, cx);
17843                self.scrollbar_marker_state.dirty = true;
17844                cx.notify();
17845            }
17846            _ => {}
17847        };
17848    }
17849
17850    pub fn start_temporary_diff_override(&mut self) {
17851        self.load_diff_task.take();
17852        self.temporary_diff_override = true;
17853    }
17854
17855    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17856        self.temporary_diff_override = false;
17857        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17858        self.buffer.update(cx, |buffer, cx| {
17859            buffer.set_all_diff_hunks_collapsed(cx);
17860        });
17861
17862        if let Some(project) = self.project.clone() {
17863            self.load_diff_task = Some(
17864                update_uncommitted_diff_for_buffer(
17865                    cx.entity(),
17866                    &project,
17867                    self.buffer.read(cx).all_buffers(),
17868                    self.buffer.clone(),
17869                    cx,
17870                )
17871                .shared(),
17872            );
17873        }
17874    }
17875
17876    fn on_display_map_changed(
17877        &mut self,
17878        _: Entity<DisplayMap>,
17879        _: &mut Window,
17880        cx: &mut Context<Self>,
17881    ) {
17882        cx.notify();
17883    }
17884
17885    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17886        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17887        self.update_edit_prediction_settings(cx);
17888        self.refresh_inline_completion(true, false, window, cx);
17889        self.refresh_inlay_hints(
17890            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17891                self.selections.newest_anchor().head(),
17892                &self.buffer.read(cx).snapshot(cx),
17893                cx,
17894            )),
17895            cx,
17896        );
17897
17898        let old_cursor_shape = self.cursor_shape;
17899
17900        {
17901            let editor_settings = EditorSettings::get_global(cx);
17902            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17903            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17904            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17905            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17906        }
17907
17908        if old_cursor_shape != self.cursor_shape {
17909            cx.emit(EditorEvent::CursorShapeChanged);
17910        }
17911
17912        let project_settings = ProjectSettings::get_global(cx);
17913        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17914
17915        if self.mode.is_full() {
17916            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17917            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17918            if self.show_inline_diagnostics != show_inline_diagnostics {
17919                self.show_inline_diagnostics = show_inline_diagnostics;
17920                self.refresh_inline_diagnostics(false, window, cx);
17921            }
17922
17923            if self.git_blame_inline_enabled != inline_blame_enabled {
17924                self.toggle_git_blame_inline_internal(false, window, cx);
17925            }
17926        }
17927
17928        cx.notify();
17929    }
17930
17931    pub fn set_searchable(&mut self, searchable: bool) {
17932        self.searchable = searchable;
17933    }
17934
17935    pub fn searchable(&self) -> bool {
17936        self.searchable
17937    }
17938
17939    fn open_proposed_changes_editor(
17940        &mut self,
17941        _: &OpenProposedChangesEditor,
17942        window: &mut Window,
17943        cx: &mut Context<Self>,
17944    ) {
17945        let Some(workspace) = self.workspace() else {
17946            cx.propagate();
17947            return;
17948        };
17949
17950        let selections = self.selections.all::<usize>(cx);
17951        let multi_buffer = self.buffer.read(cx);
17952        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17953        let mut new_selections_by_buffer = HashMap::default();
17954        for selection in selections {
17955            for (buffer, range, _) in
17956                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17957            {
17958                let mut range = range.to_point(buffer);
17959                range.start.column = 0;
17960                range.end.column = buffer.line_len(range.end.row);
17961                new_selections_by_buffer
17962                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17963                    .or_insert(Vec::new())
17964                    .push(range)
17965            }
17966        }
17967
17968        let proposed_changes_buffers = new_selections_by_buffer
17969            .into_iter()
17970            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17971            .collect::<Vec<_>>();
17972        let proposed_changes_editor = cx.new(|cx| {
17973            ProposedChangesEditor::new(
17974                "Proposed changes",
17975                proposed_changes_buffers,
17976                self.project.clone(),
17977                window,
17978                cx,
17979            )
17980        });
17981
17982        window.defer(cx, move |window, cx| {
17983            workspace.update(cx, |workspace, cx| {
17984                workspace.active_pane().update(cx, |pane, cx| {
17985                    pane.add_item(
17986                        Box::new(proposed_changes_editor),
17987                        true,
17988                        true,
17989                        None,
17990                        window,
17991                        cx,
17992                    );
17993                });
17994            });
17995        });
17996    }
17997
17998    pub fn open_excerpts_in_split(
17999        &mut self,
18000        _: &OpenExcerptsSplit,
18001        window: &mut Window,
18002        cx: &mut Context<Self>,
18003    ) {
18004        self.open_excerpts_common(None, true, window, cx)
18005    }
18006
18007    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18008        self.open_excerpts_common(None, false, window, cx)
18009    }
18010
18011    fn open_excerpts_common(
18012        &mut self,
18013        jump_data: Option<JumpData>,
18014        split: bool,
18015        window: &mut Window,
18016        cx: &mut Context<Self>,
18017    ) {
18018        let Some(workspace) = self.workspace() else {
18019            cx.propagate();
18020            return;
18021        };
18022
18023        if self.buffer.read(cx).is_singleton() {
18024            cx.propagate();
18025            return;
18026        }
18027
18028        let mut new_selections_by_buffer = HashMap::default();
18029        match &jump_data {
18030            Some(JumpData::MultiBufferPoint {
18031                excerpt_id,
18032                position,
18033                anchor,
18034                line_offset_from_top,
18035            }) => {
18036                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18037                if let Some(buffer) = multi_buffer_snapshot
18038                    .buffer_id_for_excerpt(*excerpt_id)
18039                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18040                {
18041                    let buffer_snapshot = buffer.read(cx).snapshot();
18042                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18043                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18044                    } else {
18045                        buffer_snapshot.clip_point(*position, Bias::Left)
18046                    };
18047                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18048                    new_selections_by_buffer.insert(
18049                        buffer,
18050                        (
18051                            vec![jump_to_offset..jump_to_offset],
18052                            Some(*line_offset_from_top),
18053                        ),
18054                    );
18055                }
18056            }
18057            Some(JumpData::MultiBufferRow {
18058                row,
18059                line_offset_from_top,
18060            }) => {
18061                let point = MultiBufferPoint::new(row.0, 0);
18062                if let Some((buffer, buffer_point, _)) =
18063                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18064                {
18065                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18066                    new_selections_by_buffer
18067                        .entry(buffer)
18068                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18069                        .0
18070                        .push(buffer_offset..buffer_offset)
18071                }
18072            }
18073            None => {
18074                let selections = self.selections.all::<usize>(cx);
18075                let multi_buffer = self.buffer.read(cx);
18076                for selection in selections {
18077                    for (snapshot, range, _, anchor) in multi_buffer
18078                        .snapshot(cx)
18079                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18080                    {
18081                        if let Some(anchor) = anchor {
18082                            // selection is in a deleted hunk
18083                            let Some(buffer_id) = anchor.buffer_id else {
18084                                continue;
18085                            };
18086                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18087                                continue;
18088                            };
18089                            let offset = text::ToOffset::to_offset(
18090                                &anchor.text_anchor,
18091                                &buffer_handle.read(cx).snapshot(),
18092                            );
18093                            let range = offset..offset;
18094                            new_selections_by_buffer
18095                                .entry(buffer_handle)
18096                                .or_insert((Vec::new(), None))
18097                                .0
18098                                .push(range)
18099                        } else {
18100                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18101                            else {
18102                                continue;
18103                            };
18104                            new_selections_by_buffer
18105                                .entry(buffer_handle)
18106                                .or_insert((Vec::new(), None))
18107                                .0
18108                                .push(range)
18109                        }
18110                    }
18111                }
18112            }
18113        }
18114
18115        new_selections_by_buffer
18116            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18117
18118        if new_selections_by_buffer.is_empty() {
18119            return;
18120        }
18121
18122        // We defer the pane interaction because we ourselves are a workspace item
18123        // and activating a new item causes the pane to call a method on us reentrantly,
18124        // which panics if we're on the stack.
18125        window.defer(cx, move |window, cx| {
18126            workspace.update(cx, |workspace, cx| {
18127                let pane = if split {
18128                    workspace.adjacent_pane(window, cx)
18129                } else {
18130                    workspace.active_pane().clone()
18131                };
18132
18133                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18134                    let editor = buffer
18135                        .read(cx)
18136                        .file()
18137                        .is_none()
18138                        .then(|| {
18139                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18140                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18141                            // Instead, we try to activate the existing editor in the pane first.
18142                            let (editor, pane_item_index) =
18143                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18144                                    let editor = item.downcast::<Editor>()?;
18145                                    let singleton_buffer =
18146                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18147                                    if singleton_buffer == buffer {
18148                                        Some((editor, i))
18149                                    } else {
18150                                        None
18151                                    }
18152                                })?;
18153                            pane.update(cx, |pane, cx| {
18154                                pane.activate_item(pane_item_index, true, true, window, cx)
18155                            });
18156                            Some(editor)
18157                        })
18158                        .flatten()
18159                        .unwrap_or_else(|| {
18160                            workspace.open_project_item::<Self>(
18161                                pane.clone(),
18162                                buffer,
18163                                true,
18164                                true,
18165                                window,
18166                                cx,
18167                            )
18168                        });
18169
18170                    editor.update(cx, |editor, cx| {
18171                        let autoscroll = match scroll_offset {
18172                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18173                            None => Autoscroll::newest(),
18174                        };
18175                        let nav_history = editor.nav_history.take();
18176                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18177                            s.select_ranges(ranges);
18178                        });
18179                        editor.nav_history = nav_history;
18180                    });
18181                }
18182            })
18183        });
18184    }
18185
18186    // For now, don't allow opening excerpts in buffers that aren't backed by
18187    // regular project files.
18188    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18189        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18190    }
18191
18192    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18193        let snapshot = self.buffer.read(cx).read(cx);
18194        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18195        Some(
18196            ranges
18197                .iter()
18198                .map(move |range| {
18199                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18200                })
18201                .collect(),
18202        )
18203    }
18204
18205    fn selection_replacement_ranges(
18206        &self,
18207        range: Range<OffsetUtf16>,
18208        cx: &mut App,
18209    ) -> Vec<Range<OffsetUtf16>> {
18210        let selections = self.selections.all::<OffsetUtf16>(cx);
18211        let newest_selection = selections
18212            .iter()
18213            .max_by_key(|selection| selection.id)
18214            .unwrap();
18215        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18216        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18217        let snapshot = self.buffer.read(cx).read(cx);
18218        selections
18219            .into_iter()
18220            .map(|mut selection| {
18221                selection.start.0 =
18222                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18223                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18224                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18225                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18226            })
18227            .collect()
18228    }
18229
18230    fn report_editor_event(
18231        &self,
18232        event_type: &'static str,
18233        file_extension: Option<String>,
18234        cx: &App,
18235    ) {
18236        if cfg!(any(test, feature = "test-support")) {
18237            return;
18238        }
18239
18240        let Some(project) = &self.project else { return };
18241
18242        // If None, we are in a file without an extension
18243        let file = self
18244            .buffer
18245            .read(cx)
18246            .as_singleton()
18247            .and_then(|b| b.read(cx).file());
18248        let file_extension = file_extension.or(file
18249            .as_ref()
18250            .and_then(|file| Path::new(file.file_name(cx)).extension())
18251            .and_then(|e| e.to_str())
18252            .map(|a| a.to_string()));
18253
18254        let vim_mode = vim_enabled(cx);
18255
18256        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18257        let copilot_enabled = edit_predictions_provider
18258            == language::language_settings::EditPredictionProvider::Copilot;
18259        let copilot_enabled_for_language = self
18260            .buffer
18261            .read(cx)
18262            .language_settings(cx)
18263            .show_edit_predictions;
18264
18265        let project = project.read(cx);
18266        telemetry::event!(
18267            event_type,
18268            file_extension,
18269            vim_mode,
18270            copilot_enabled,
18271            copilot_enabled_for_language,
18272            edit_predictions_provider,
18273            is_via_ssh = project.is_via_ssh(),
18274        );
18275    }
18276
18277    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18278    /// with each line being an array of {text, highlight} objects.
18279    fn copy_highlight_json(
18280        &mut self,
18281        _: &CopyHighlightJson,
18282        window: &mut Window,
18283        cx: &mut Context<Self>,
18284    ) {
18285        #[derive(Serialize)]
18286        struct Chunk<'a> {
18287            text: String,
18288            highlight: Option<&'a str>,
18289        }
18290
18291        let snapshot = self.buffer.read(cx).snapshot(cx);
18292        let range = self
18293            .selected_text_range(false, window, cx)
18294            .and_then(|selection| {
18295                if selection.range.is_empty() {
18296                    None
18297                } else {
18298                    Some(selection.range)
18299                }
18300            })
18301            .unwrap_or_else(|| 0..snapshot.len());
18302
18303        let chunks = snapshot.chunks(range, true);
18304        let mut lines = Vec::new();
18305        let mut line: VecDeque<Chunk> = VecDeque::new();
18306
18307        let Some(style) = self.style.as_ref() else {
18308            return;
18309        };
18310
18311        for chunk in chunks {
18312            let highlight = chunk
18313                .syntax_highlight_id
18314                .and_then(|id| id.name(&style.syntax));
18315            let mut chunk_lines = chunk.text.split('\n').peekable();
18316            while let Some(text) = chunk_lines.next() {
18317                let mut merged_with_last_token = false;
18318                if let Some(last_token) = line.back_mut() {
18319                    if last_token.highlight == highlight {
18320                        last_token.text.push_str(text);
18321                        merged_with_last_token = true;
18322                    }
18323                }
18324
18325                if !merged_with_last_token {
18326                    line.push_back(Chunk {
18327                        text: text.into(),
18328                        highlight,
18329                    });
18330                }
18331
18332                if chunk_lines.peek().is_some() {
18333                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18334                        line.pop_front();
18335                    }
18336                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18337                        line.pop_back();
18338                    }
18339
18340                    lines.push(mem::take(&mut line));
18341                }
18342            }
18343        }
18344
18345        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18346            return;
18347        };
18348        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18349    }
18350
18351    pub fn open_context_menu(
18352        &mut self,
18353        _: &OpenContextMenu,
18354        window: &mut Window,
18355        cx: &mut Context<Self>,
18356    ) {
18357        self.request_autoscroll(Autoscroll::newest(), cx);
18358        let position = self.selections.newest_display(cx).start;
18359        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18360    }
18361
18362    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18363        &self.inlay_hint_cache
18364    }
18365
18366    pub fn replay_insert_event(
18367        &mut self,
18368        text: &str,
18369        relative_utf16_range: Option<Range<isize>>,
18370        window: &mut Window,
18371        cx: &mut Context<Self>,
18372    ) {
18373        if !self.input_enabled {
18374            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18375            return;
18376        }
18377        if let Some(relative_utf16_range) = relative_utf16_range {
18378            let selections = self.selections.all::<OffsetUtf16>(cx);
18379            self.change_selections(None, window, cx, |s| {
18380                let new_ranges = selections.into_iter().map(|range| {
18381                    let start = OffsetUtf16(
18382                        range
18383                            .head()
18384                            .0
18385                            .saturating_add_signed(relative_utf16_range.start),
18386                    );
18387                    let end = OffsetUtf16(
18388                        range
18389                            .head()
18390                            .0
18391                            .saturating_add_signed(relative_utf16_range.end),
18392                    );
18393                    start..end
18394                });
18395                s.select_ranges(new_ranges);
18396            });
18397        }
18398
18399        self.handle_input(text, window, cx);
18400    }
18401
18402    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18403        let Some(provider) = self.semantics_provider.as_ref() else {
18404            return false;
18405        };
18406
18407        let mut supports = false;
18408        self.buffer().update(cx, |this, cx| {
18409            this.for_each_buffer(|buffer| {
18410                supports |= provider.supports_inlay_hints(buffer, cx);
18411            });
18412        });
18413
18414        supports
18415    }
18416
18417    pub fn is_focused(&self, window: &Window) -> bool {
18418        self.focus_handle.is_focused(window)
18419    }
18420
18421    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18422        cx.emit(EditorEvent::Focused);
18423
18424        if let Some(descendant) = self
18425            .last_focused_descendant
18426            .take()
18427            .and_then(|descendant| descendant.upgrade())
18428        {
18429            window.focus(&descendant);
18430        } else {
18431            if let Some(blame) = self.blame.as_ref() {
18432                blame.update(cx, GitBlame::focus)
18433            }
18434
18435            self.blink_manager.update(cx, BlinkManager::enable);
18436            self.show_cursor_names(window, cx);
18437            self.buffer.update(cx, |buffer, cx| {
18438                buffer.finalize_last_transaction(cx);
18439                if self.leader_id.is_none() {
18440                    buffer.set_active_selections(
18441                        &self.selections.disjoint_anchors(),
18442                        self.selections.line_mode,
18443                        self.cursor_shape,
18444                        cx,
18445                    );
18446                }
18447            });
18448        }
18449    }
18450
18451    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18452        cx.emit(EditorEvent::FocusedIn)
18453    }
18454
18455    fn handle_focus_out(
18456        &mut self,
18457        event: FocusOutEvent,
18458        _window: &mut Window,
18459        cx: &mut Context<Self>,
18460    ) {
18461        if event.blurred != self.focus_handle {
18462            self.last_focused_descendant = Some(event.blurred);
18463        }
18464        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18465    }
18466
18467    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18468        self.blink_manager.update(cx, BlinkManager::disable);
18469        self.buffer
18470            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18471
18472        if let Some(blame) = self.blame.as_ref() {
18473            blame.update(cx, GitBlame::blur)
18474        }
18475        if !self.hover_state.focused(window, cx) {
18476            hide_hover(self, cx);
18477        }
18478        if !self
18479            .context_menu
18480            .borrow()
18481            .as_ref()
18482            .is_some_and(|context_menu| context_menu.focused(window, cx))
18483        {
18484            self.hide_context_menu(window, cx);
18485        }
18486        self.discard_inline_completion(false, cx);
18487        cx.emit(EditorEvent::Blurred);
18488        cx.notify();
18489    }
18490
18491    pub fn register_action<A: Action>(
18492        &mut self,
18493        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18494    ) -> Subscription {
18495        let id = self.next_editor_action_id.post_inc();
18496        let listener = Arc::new(listener);
18497        self.editor_actions.borrow_mut().insert(
18498            id,
18499            Box::new(move |window, _| {
18500                let listener = listener.clone();
18501                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18502                    let action = action.downcast_ref().unwrap();
18503                    if phase == DispatchPhase::Bubble {
18504                        listener(action, window, cx)
18505                    }
18506                })
18507            }),
18508        );
18509
18510        let editor_actions = self.editor_actions.clone();
18511        Subscription::new(move || {
18512            editor_actions.borrow_mut().remove(&id);
18513        })
18514    }
18515
18516    pub fn file_header_size(&self) -> u32 {
18517        FILE_HEADER_HEIGHT
18518    }
18519
18520    pub fn restore(
18521        &mut self,
18522        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18523        window: &mut Window,
18524        cx: &mut Context<Self>,
18525    ) {
18526        let workspace = self.workspace();
18527        let project = self.project.as_ref();
18528        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18529            let mut tasks = Vec::new();
18530            for (buffer_id, changes) in revert_changes {
18531                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18532                    buffer.update(cx, |buffer, cx| {
18533                        buffer.edit(
18534                            changes
18535                                .into_iter()
18536                                .map(|(range, text)| (range, text.to_string())),
18537                            None,
18538                            cx,
18539                        );
18540                    });
18541
18542                    if let Some(project) =
18543                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18544                    {
18545                        project.update(cx, |project, cx| {
18546                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18547                        })
18548                    }
18549                }
18550            }
18551            tasks
18552        });
18553        cx.spawn_in(window, async move |_, cx| {
18554            for (buffer, task) in save_tasks {
18555                let result = task.await;
18556                if result.is_err() {
18557                    let Some(path) = buffer
18558                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18559                        .ok()
18560                    else {
18561                        continue;
18562                    };
18563                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18564                        let Some(task) = cx
18565                            .update_window_entity(&workspace, |workspace, window, cx| {
18566                                workspace
18567                                    .open_path_preview(path, None, false, false, false, window, cx)
18568                            })
18569                            .ok()
18570                        else {
18571                            continue;
18572                        };
18573                        task.await.log_err();
18574                    }
18575                }
18576            }
18577        })
18578        .detach();
18579        self.change_selections(None, window, cx, |selections| selections.refresh());
18580    }
18581
18582    pub fn to_pixel_point(
18583        &self,
18584        source: multi_buffer::Anchor,
18585        editor_snapshot: &EditorSnapshot,
18586        window: &mut Window,
18587    ) -> Option<gpui::Point<Pixels>> {
18588        let source_point = source.to_display_point(editor_snapshot);
18589        self.display_to_pixel_point(source_point, editor_snapshot, window)
18590    }
18591
18592    pub fn display_to_pixel_point(
18593        &self,
18594        source: DisplayPoint,
18595        editor_snapshot: &EditorSnapshot,
18596        window: &mut Window,
18597    ) -> Option<gpui::Point<Pixels>> {
18598        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18599        let text_layout_details = self.text_layout_details(window);
18600        let scroll_top = text_layout_details
18601            .scroll_anchor
18602            .scroll_position(editor_snapshot)
18603            .y;
18604
18605        if source.row().as_f32() < scroll_top.floor() {
18606            return None;
18607        }
18608        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18609        let source_y = line_height * (source.row().as_f32() - scroll_top);
18610        Some(gpui::Point::new(source_x, source_y))
18611    }
18612
18613    pub fn has_visible_completions_menu(&self) -> bool {
18614        !self.edit_prediction_preview_is_active()
18615            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18616                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18617            })
18618    }
18619
18620    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18621        self.addons
18622            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18623    }
18624
18625    pub fn unregister_addon<T: Addon>(&mut self) {
18626        self.addons.remove(&std::any::TypeId::of::<T>());
18627    }
18628
18629    pub fn addon<T: Addon>(&self) -> Option<&T> {
18630        let type_id = std::any::TypeId::of::<T>();
18631        self.addons
18632            .get(&type_id)
18633            .and_then(|item| item.to_any().downcast_ref::<T>())
18634    }
18635
18636    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18637        let type_id = std::any::TypeId::of::<T>();
18638        self.addons
18639            .get_mut(&type_id)
18640            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18641    }
18642
18643    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18644        let text_layout_details = self.text_layout_details(window);
18645        let style = &text_layout_details.editor_style;
18646        let font_id = window.text_system().resolve_font(&style.text.font());
18647        let font_size = style.text.font_size.to_pixels(window.rem_size());
18648        let line_height = style.text.line_height_in_pixels(window.rem_size());
18649        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18650
18651        gpui::Size::new(em_width, line_height)
18652    }
18653
18654    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18655        self.load_diff_task.clone()
18656    }
18657
18658    fn read_metadata_from_db(
18659        &mut self,
18660        item_id: u64,
18661        workspace_id: WorkspaceId,
18662        window: &mut Window,
18663        cx: &mut Context<Editor>,
18664    ) {
18665        if self.is_singleton(cx)
18666            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18667        {
18668            let buffer_snapshot = OnceCell::new();
18669
18670            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18671                if !folds.is_empty() {
18672                    let snapshot =
18673                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18674                    self.fold_ranges(
18675                        folds
18676                            .into_iter()
18677                            .map(|(start, end)| {
18678                                snapshot.clip_offset(start, Bias::Left)
18679                                    ..snapshot.clip_offset(end, Bias::Right)
18680                            })
18681                            .collect(),
18682                        false,
18683                        window,
18684                        cx,
18685                    );
18686                }
18687            }
18688
18689            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18690                if !selections.is_empty() {
18691                    let snapshot =
18692                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18693                    self.change_selections(None, window, cx, |s| {
18694                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18695                            snapshot.clip_offset(start, Bias::Left)
18696                                ..snapshot.clip_offset(end, Bias::Right)
18697                        }));
18698                    });
18699                }
18700            };
18701        }
18702
18703        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18704    }
18705}
18706
18707fn vim_enabled(cx: &App) -> bool {
18708    cx.global::<SettingsStore>()
18709        .raw_user_settings()
18710        .get("vim_mode")
18711        == Some(&serde_json::Value::Bool(true))
18712}
18713
18714// Consider user intent and default settings
18715fn choose_completion_range(
18716    completion: &Completion,
18717    intent: CompletionIntent,
18718    buffer: &Entity<Buffer>,
18719    cx: &mut Context<Editor>,
18720) -> Range<usize> {
18721    fn should_replace(
18722        completion: &Completion,
18723        insert_range: &Range<text::Anchor>,
18724        intent: CompletionIntent,
18725        completion_mode_setting: LspInsertMode,
18726        buffer: &Buffer,
18727    ) -> bool {
18728        // specific actions take precedence over settings
18729        match intent {
18730            CompletionIntent::CompleteWithInsert => return false,
18731            CompletionIntent::CompleteWithReplace => return true,
18732            CompletionIntent::Complete | CompletionIntent::Compose => {}
18733        }
18734
18735        match completion_mode_setting {
18736            LspInsertMode::Insert => false,
18737            LspInsertMode::Replace => true,
18738            LspInsertMode::ReplaceSubsequence => {
18739                let mut text_to_replace = buffer.chars_for_range(
18740                    buffer.anchor_before(completion.replace_range.start)
18741                        ..buffer.anchor_after(completion.replace_range.end),
18742                );
18743                let mut completion_text = completion.new_text.chars();
18744
18745                // is `text_to_replace` a subsequence of `completion_text`
18746                text_to_replace
18747                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18748            }
18749            LspInsertMode::ReplaceSuffix => {
18750                let range_after_cursor = insert_range.end..completion.replace_range.end;
18751
18752                let text_after_cursor = buffer
18753                    .text_for_range(
18754                        buffer.anchor_before(range_after_cursor.start)
18755                            ..buffer.anchor_after(range_after_cursor.end),
18756                    )
18757                    .collect::<String>();
18758                completion.new_text.ends_with(&text_after_cursor)
18759            }
18760        }
18761    }
18762
18763    let buffer = buffer.read(cx);
18764
18765    if let CompletionSource::Lsp {
18766        insert_range: Some(insert_range),
18767        ..
18768    } = &completion.source
18769    {
18770        let completion_mode_setting =
18771            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18772                .completions
18773                .lsp_insert_mode;
18774
18775        if !should_replace(
18776            completion,
18777            &insert_range,
18778            intent,
18779            completion_mode_setting,
18780            buffer,
18781        ) {
18782            return insert_range.to_offset(buffer);
18783        }
18784    }
18785
18786    completion.replace_range.to_offset(buffer)
18787}
18788
18789fn insert_extra_newline_brackets(
18790    buffer: &MultiBufferSnapshot,
18791    range: Range<usize>,
18792    language: &language::LanguageScope,
18793) -> bool {
18794    let leading_whitespace_len = buffer
18795        .reversed_chars_at(range.start)
18796        .take_while(|c| c.is_whitespace() && *c != '\n')
18797        .map(|c| c.len_utf8())
18798        .sum::<usize>();
18799    let trailing_whitespace_len = buffer
18800        .chars_at(range.end)
18801        .take_while(|c| c.is_whitespace() && *c != '\n')
18802        .map(|c| c.len_utf8())
18803        .sum::<usize>();
18804    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18805
18806    language.brackets().any(|(pair, enabled)| {
18807        let pair_start = pair.start.trim_end();
18808        let pair_end = pair.end.trim_start();
18809
18810        enabled
18811            && pair.newline
18812            && buffer.contains_str_at(range.end, pair_end)
18813            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18814    })
18815}
18816
18817fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18818    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18819        [(buffer, range, _)] => (*buffer, range.clone()),
18820        _ => return false,
18821    };
18822    let pair = {
18823        let mut result: Option<BracketMatch> = None;
18824
18825        for pair in buffer
18826            .all_bracket_ranges(range.clone())
18827            .filter(move |pair| {
18828                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18829            })
18830        {
18831            let len = pair.close_range.end - pair.open_range.start;
18832
18833            if let Some(existing) = &result {
18834                let existing_len = existing.close_range.end - existing.open_range.start;
18835                if len > existing_len {
18836                    continue;
18837                }
18838            }
18839
18840            result = Some(pair);
18841        }
18842
18843        result
18844    };
18845    let Some(pair) = pair else {
18846        return false;
18847    };
18848    pair.newline_only
18849        && buffer
18850            .chars_for_range(pair.open_range.end..range.start)
18851            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18852            .all(|c| c.is_whitespace() && c != '\n')
18853}
18854
18855fn update_uncommitted_diff_for_buffer(
18856    editor: Entity<Editor>,
18857    project: &Entity<Project>,
18858    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18859    buffer: Entity<MultiBuffer>,
18860    cx: &mut App,
18861) -> Task<()> {
18862    let mut tasks = Vec::new();
18863    project.update(cx, |project, cx| {
18864        for buffer in buffers {
18865            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18866                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18867            }
18868        }
18869    });
18870    cx.spawn(async move |cx| {
18871        let diffs = future::join_all(tasks).await;
18872        if editor
18873            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18874            .unwrap_or(false)
18875        {
18876            return;
18877        }
18878
18879        buffer
18880            .update(cx, |buffer, cx| {
18881                for diff in diffs.into_iter().flatten() {
18882                    buffer.add_diff(diff, cx);
18883                }
18884            })
18885            .ok();
18886    })
18887}
18888
18889fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18890    let tab_size = tab_size.get() as usize;
18891    let mut width = offset;
18892
18893    for ch in text.chars() {
18894        width += if ch == '\t' {
18895            tab_size - (width % tab_size)
18896        } else {
18897            1
18898        };
18899    }
18900
18901    width - offset
18902}
18903
18904#[cfg(test)]
18905mod tests {
18906    use super::*;
18907
18908    #[test]
18909    fn test_string_size_with_expanded_tabs() {
18910        let nz = |val| NonZeroU32::new(val).unwrap();
18911        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18912        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18913        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18914        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18915        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18916        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18917        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18918        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18919    }
18920}
18921
18922/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18923struct WordBreakingTokenizer<'a> {
18924    input: &'a str,
18925}
18926
18927impl<'a> WordBreakingTokenizer<'a> {
18928    fn new(input: &'a str) -> Self {
18929        Self { input }
18930    }
18931}
18932
18933fn is_char_ideographic(ch: char) -> bool {
18934    use unicode_script::Script::*;
18935    use unicode_script::UnicodeScript;
18936    matches!(ch.script(), Han | Tangut | Yi)
18937}
18938
18939fn is_grapheme_ideographic(text: &str) -> bool {
18940    text.chars().any(is_char_ideographic)
18941}
18942
18943fn is_grapheme_whitespace(text: &str) -> bool {
18944    text.chars().any(|x| x.is_whitespace())
18945}
18946
18947fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18948    text.chars().next().map_or(false, |ch| {
18949        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18950    })
18951}
18952
18953#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18954enum WordBreakToken<'a> {
18955    Word { token: &'a str, grapheme_len: usize },
18956    InlineWhitespace { token: &'a str, grapheme_len: usize },
18957    Newline,
18958}
18959
18960impl<'a> Iterator for WordBreakingTokenizer<'a> {
18961    /// Yields a span, the count of graphemes in the token, and whether it was
18962    /// whitespace. Note that it also breaks at word boundaries.
18963    type Item = WordBreakToken<'a>;
18964
18965    fn next(&mut self) -> Option<Self::Item> {
18966        use unicode_segmentation::UnicodeSegmentation;
18967        if self.input.is_empty() {
18968            return None;
18969        }
18970
18971        let mut iter = self.input.graphemes(true).peekable();
18972        let mut offset = 0;
18973        let mut grapheme_len = 0;
18974        if let Some(first_grapheme) = iter.next() {
18975            let is_newline = first_grapheme == "\n";
18976            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18977            offset += first_grapheme.len();
18978            grapheme_len += 1;
18979            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18980                if let Some(grapheme) = iter.peek().copied() {
18981                    if should_stay_with_preceding_ideograph(grapheme) {
18982                        offset += grapheme.len();
18983                        grapheme_len += 1;
18984                    }
18985                }
18986            } else {
18987                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18988                let mut next_word_bound = words.peek().copied();
18989                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18990                    next_word_bound = words.next();
18991                }
18992                while let Some(grapheme) = iter.peek().copied() {
18993                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18994                        break;
18995                    };
18996                    if is_grapheme_whitespace(grapheme) != is_whitespace
18997                        || (grapheme == "\n") != is_newline
18998                    {
18999                        break;
19000                    };
19001                    offset += grapheme.len();
19002                    grapheme_len += 1;
19003                    iter.next();
19004                }
19005            }
19006            let token = &self.input[..offset];
19007            self.input = &self.input[offset..];
19008            if token == "\n" {
19009                Some(WordBreakToken::Newline)
19010            } else if is_whitespace {
19011                Some(WordBreakToken::InlineWhitespace {
19012                    token,
19013                    grapheme_len,
19014                })
19015            } else {
19016                Some(WordBreakToken::Word {
19017                    token,
19018                    grapheme_len,
19019                })
19020            }
19021        } else {
19022            None
19023        }
19024    }
19025}
19026
19027#[test]
19028fn test_word_breaking_tokenizer() {
19029    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19030        ("", &[]),
19031        ("  ", &[whitespace("  ", 2)]),
19032        ("Ʒ", &[word("Ʒ", 1)]),
19033        ("Ǽ", &[word("Ǽ", 1)]),
19034        ("", &[word("", 1)]),
19035        ("⋑⋑", &[word("⋑⋑", 2)]),
19036        (
19037            "原理,进而",
19038            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19039        ),
19040        (
19041            "hello world",
19042            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19043        ),
19044        (
19045            "hello, world",
19046            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19047        ),
19048        (
19049            "  hello world",
19050            &[
19051                whitespace("  ", 2),
19052                word("hello", 5),
19053                whitespace(" ", 1),
19054                word("world", 5),
19055            ],
19056        ),
19057        (
19058            "这是什么 \n 钢笔",
19059            &[
19060                word("", 1),
19061                word("", 1),
19062                word("", 1),
19063                word("", 1),
19064                whitespace(" ", 1),
19065                newline(),
19066                whitespace(" ", 1),
19067                word("", 1),
19068                word("", 1),
19069            ],
19070        ),
19071        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19072    ];
19073
19074    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19075        WordBreakToken::Word {
19076            token,
19077            grapheme_len,
19078        }
19079    }
19080
19081    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19082        WordBreakToken::InlineWhitespace {
19083            token,
19084            grapheme_len,
19085        }
19086    }
19087
19088    fn newline() -> WordBreakToken<'static> {
19089        WordBreakToken::Newline
19090    }
19091
19092    for (input, result) in tests {
19093        assert_eq!(
19094            WordBreakingTokenizer::new(input)
19095                .collect::<Vec<_>>()
19096                .as_slice(),
19097            *result,
19098        );
19099    }
19100}
19101
19102fn wrap_with_prefix(
19103    line_prefix: String,
19104    unwrapped_text: String,
19105    wrap_column: usize,
19106    tab_size: NonZeroU32,
19107    preserve_existing_whitespace: bool,
19108) -> String {
19109    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19110    let mut wrapped_text = String::new();
19111    let mut current_line = line_prefix.clone();
19112
19113    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19114    let mut current_line_len = line_prefix_len;
19115    let mut in_whitespace = false;
19116    for token in tokenizer {
19117        let have_preceding_whitespace = in_whitespace;
19118        match token {
19119            WordBreakToken::Word {
19120                token,
19121                grapheme_len,
19122            } => {
19123                in_whitespace = false;
19124                if current_line_len + grapheme_len > wrap_column
19125                    && current_line_len != line_prefix_len
19126                {
19127                    wrapped_text.push_str(current_line.trim_end());
19128                    wrapped_text.push('\n');
19129                    current_line.truncate(line_prefix.len());
19130                    current_line_len = line_prefix_len;
19131                }
19132                current_line.push_str(token);
19133                current_line_len += grapheme_len;
19134            }
19135            WordBreakToken::InlineWhitespace {
19136                mut token,
19137                mut grapheme_len,
19138            } => {
19139                in_whitespace = true;
19140                if have_preceding_whitespace && !preserve_existing_whitespace {
19141                    continue;
19142                }
19143                if !preserve_existing_whitespace {
19144                    token = " ";
19145                    grapheme_len = 1;
19146                }
19147                if current_line_len + grapheme_len > wrap_column {
19148                    wrapped_text.push_str(current_line.trim_end());
19149                    wrapped_text.push('\n');
19150                    current_line.truncate(line_prefix.len());
19151                    current_line_len = line_prefix_len;
19152                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19153                    current_line.push_str(token);
19154                    current_line_len += grapheme_len;
19155                }
19156            }
19157            WordBreakToken::Newline => {
19158                in_whitespace = true;
19159                if preserve_existing_whitespace {
19160                    wrapped_text.push_str(current_line.trim_end());
19161                    wrapped_text.push('\n');
19162                    current_line.truncate(line_prefix.len());
19163                    current_line_len = line_prefix_len;
19164                } else if have_preceding_whitespace {
19165                    continue;
19166                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19167                {
19168                    wrapped_text.push_str(current_line.trim_end());
19169                    wrapped_text.push('\n');
19170                    current_line.truncate(line_prefix.len());
19171                    current_line_len = line_prefix_len;
19172                } else if current_line_len != line_prefix_len {
19173                    current_line.push(' ');
19174                    current_line_len += 1;
19175                }
19176            }
19177        }
19178    }
19179
19180    if !current_line.is_empty() {
19181        wrapped_text.push_str(&current_line);
19182    }
19183    wrapped_text
19184}
19185
19186#[test]
19187fn test_wrap_with_prefix() {
19188    assert_eq!(
19189        wrap_with_prefix(
19190            "# ".to_string(),
19191            "abcdefg".to_string(),
19192            4,
19193            NonZeroU32::new(4).unwrap(),
19194            false,
19195        ),
19196        "# abcdefg"
19197    );
19198    assert_eq!(
19199        wrap_with_prefix(
19200            "".to_string(),
19201            "\thello world".to_string(),
19202            8,
19203            NonZeroU32::new(4).unwrap(),
19204            false,
19205        ),
19206        "hello\nworld"
19207    );
19208    assert_eq!(
19209        wrap_with_prefix(
19210            "// ".to_string(),
19211            "xx \nyy zz aa bb cc".to_string(),
19212            12,
19213            NonZeroU32::new(4).unwrap(),
19214            false,
19215        ),
19216        "// xx yy zz\n// aa bb cc"
19217    );
19218    assert_eq!(
19219        wrap_with_prefix(
19220            String::new(),
19221            "这是什么 \n 钢笔".to_string(),
19222            3,
19223            NonZeroU32::new(4).unwrap(),
19224            false,
19225        ),
19226        "这是什\n么 钢\n"
19227    );
19228}
19229
19230pub trait CollaborationHub {
19231    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19232    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19233    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19234}
19235
19236impl CollaborationHub for Entity<Project> {
19237    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19238        self.read(cx).collaborators()
19239    }
19240
19241    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19242        self.read(cx).user_store().read(cx).participant_indices()
19243    }
19244
19245    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19246        let this = self.read(cx);
19247        let user_ids = this.collaborators().values().map(|c| c.user_id);
19248        this.user_store().read_with(cx, |user_store, cx| {
19249            user_store.participant_names(user_ids, cx)
19250        })
19251    }
19252}
19253
19254pub trait SemanticsProvider {
19255    fn hover(
19256        &self,
19257        buffer: &Entity<Buffer>,
19258        position: text::Anchor,
19259        cx: &mut App,
19260    ) -> Option<Task<Vec<project::Hover>>>;
19261
19262    fn inline_values(
19263        &self,
19264        buffer_handle: Entity<Buffer>,
19265        range: Range<text::Anchor>,
19266        cx: &mut App,
19267    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19268
19269    fn inlay_hints(
19270        &self,
19271        buffer_handle: Entity<Buffer>,
19272        range: Range<text::Anchor>,
19273        cx: &mut App,
19274    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19275
19276    fn resolve_inlay_hint(
19277        &self,
19278        hint: InlayHint,
19279        buffer_handle: Entity<Buffer>,
19280        server_id: LanguageServerId,
19281        cx: &mut App,
19282    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19283
19284    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19285
19286    fn document_highlights(
19287        &self,
19288        buffer: &Entity<Buffer>,
19289        position: text::Anchor,
19290        cx: &mut App,
19291    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19292
19293    fn definitions(
19294        &self,
19295        buffer: &Entity<Buffer>,
19296        position: text::Anchor,
19297        kind: GotoDefinitionKind,
19298        cx: &mut App,
19299    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19300
19301    fn range_for_rename(
19302        &self,
19303        buffer: &Entity<Buffer>,
19304        position: text::Anchor,
19305        cx: &mut App,
19306    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19307
19308    fn perform_rename(
19309        &self,
19310        buffer: &Entity<Buffer>,
19311        position: text::Anchor,
19312        new_name: String,
19313        cx: &mut App,
19314    ) -> Option<Task<Result<ProjectTransaction>>>;
19315}
19316
19317pub trait CompletionProvider {
19318    fn completions(
19319        &self,
19320        excerpt_id: ExcerptId,
19321        buffer: &Entity<Buffer>,
19322        buffer_position: text::Anchor,
19323        trigger: CompletionContext,
19324        window: &mut Window,
19325        cx: &mut Context<Editor>,
19326    ) -> Task<Result<Option<Vec<Completion>>>>;
19327
19328    fn resolve_completions(
19329        &self,
19330        buffer: Entity<Buffer>,
19331        completion_indices: Vec<usize>,
19332        completions: Rc<RefCell<Box<[Completion]>>>,
19333        cx: &mut Context<Editor>,
19334    ) -> Task<Result<bool>>;
19335
19336    fn apply_additional_edits_for_completion(
19337        &self,
19338        _buffer: Entity<Buffer>,
19339        _completions: Rc<RefCell<Box<[Completion]>>>,
19340        _completion_index: usize,
19341        _push_to_history: bool,
19342        _cx: &mut Context<Editor>,
19343    ) -> Task<Result<Option<language::Transaction>>> {
19344        Task::ready(Ok(None))
19345    }
19346
19347    fn is_completion_trigger(
19348        &self,
19349        buffer: &Entity<Buffer>,
19350        position: language::Anchor,
19351        text: &str,
19352        trigger_in_words: bool,
19353        cx: &mut Context<Editor>,
19354    ) -> bool;
19355
19356    fn sort_completions(&self) -> bool {
19357        true
19358    }
19359
19360    fn filter_completions(&self) -> bool {
19361        true
19362    }
19363}
19364
19365pub trait CodeActionProvider {
19366    fn id(&self) -> Arc<str>;
19367
19368    fn code_actions(
19369        &self,
19370        buffer: &Entity<Buffer>,
19371        range: Range<text::Anchor>,
19372        window: &mut Window,
19373        cx: &mut App,
19374    ) -> Task<Result<Vec<CodeAction>>>;
19375
19376    fn apply_code_action(
19377        &self,
19378        buffer_handle: Entity<Buffer>,
19379        action: CodeAction,
19380        excerpt_id: ExcerptId,
19381        push_to_history: bool,
19382        window: &mut Window,
19383        cx: &mut App,
19384    ) -> Task<Result<ProjectTransaction>>;
19385}
19386
19387impl CodeActionProvider for Entity<Project> {
19388    fn id(&self) -> Arc<str> {
19389        "project".into()
19390    }
19391
19392    fn code_actions(
19393        &self,
19394        buffer: &Entity<Buffer>,
19395        range: Range<text::Anchor>,
19396        _window: &mut Window,
19397        cx: &mut App,
19398    ) -> Task<Result<Vec<CodeAction>>> {
19399        self.update(cx, |project, cx| {
19400            let code_lens = project.code_lens(buffer, range.clone(), cx);
19401            let code_actions = project.code_actions(buffer, range, None, cx);
19402            cx.background_spawn(async move {
19403                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19404                Ok(code_lens
19405                    .context("code lens fetch")?
19406                    .into_iter()
19407                    .chain(code_actions.context("code action fetch")?)
19408                    .collect())
19409            })
19410        })
19411    }
19412
19413    fn apply_code_action(
19414        &self,
19415        buffer_handle: Entity<Buffer>,
19416        action: CodeAction,
19417        _excerpt_id: ExcerptId,
19418        push_to_history: bool,
19419        _window: &mut Window,
19420        cx: &mut App,
19421    ) -> Task<Result<ProjectTransaction>> {
19422        self.update(cx, |project, cx| {
19423            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19424        })
19425    }
19426}
19427
19428fn snippet_completions(
19429    project: &Project,
19430    buffer: &Entity<Buffer>,
19431    buffer_position: text::Anchor,
19432    cx: &mut App,
19433) -> Task<Result<Vec<Completion>>> {
19434    let languages = buffer.read(cx).languages_at(buffer_position);
19435    let snippet_store = project.snippets().read(cx);
19436
19437    let scopes: Vec<_> = languages
19438        .iter()
19439        .filter_map(|language| {
19440            let language_name = language.lsp_id();
19441            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19442
19443            if snippets.is_empty() {
19444                None
19445            } else {
19446                Some((language.default_scope(), snippets))
19447            }
19448        })
19449        .collect();
19450
19451    if scopes.is_empty() {
19452        return Task::ready(Ok(vec![]));
19453    }
19454
19455    let snapshot = buffer.read(cx).text_snapshot();
19456    let chars: String = snapshot
19457        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19458        .collect();
19459    let executor = cx.background_executor().clone();
19460
19461    cx.background_spawn(async move {
19462        let mut all_results: Vec<Completion> = Vec::new();
19463        for (scope, snippets) in scopes.into_iter() {
19464            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19465            let mut last_word = chars
19466                .chars()
19467                .take_while(|c| classifier.is_word(*c))
19468                .collect::<String>();
19469            last_word = last_word.chars().rev().collect();
19470
19471            if last_word.is_empty() {
19472                return Ok(vec![]);
19473            }
19474
19475            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19476            let to_lsp = |point: &text::Anchor| {
19477                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19478                point_to_lsp(end)
19479            };
19480            let lsp_end = to_lsp(&buffer_position);
19481
19482            let candidates = snippets
19483                .iter()
19484                .enumerate()
19485                .flat_map(|(ix, snippet)| {
19486                    snippet
19487                        .prefix
19488                        .iter()
19489                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19490                })
19491                .collect::<Vec<StringMatchCandidate>>();
19492
19493            let mut matches = fuzzy::match_strings(
19494                &candidates,
19495                &last_word,
19496                last_word.chars().any(|c| c.is_uppercase()),
19497                100,
19498                &Default::default(),
19499                executor.clone(),
19500            )
19501            .await;
19502
19503            // Remove all candidates where the query's start does not match the start of any word in the candidate
19504            if let Some(query_start) = last_word.chars().next() {
19505                matches.retain(|string_match| {
19506                    split_words(&string_match.string).any(|word| {
19507                        // Check that the first codepoint of the word as lowercase matches the first
19508                        // codepoint of the query as lowercase
19509                        word.chars()
19510                            .flat_map(|codepoint| codepoint.to_lowercase())
19511                            .zip(query_start.to_lowercase())
19512                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19513                    })
19514                });
19515            }
19516
19517            let matched_strings = matches
19518                .into_iter()
19519                .map(|m| m.string)
19520                .collect::<HashSet<_>>();
19521
19522            let mut result: Vec<Completion> = snippets
19523                .iter()
19524                .filter_map(|snippet| {
19525                    let matching_prefix = snippet
19526                        .prefix
19527                        .iter()
19528                        .find(|prefix| matched_strings.contains(*prefix))?;
19529                    let start = as_offset - last_word.len();
19530                    let start = snapshot.anchor_before(start);
19531                    let range = start..buffer_position;
19532                    let lsp_start = to_lsp(&start);
19533                    let lsp_range = lsp::Range {
19534                        start: lsp_start,
19535                        end: lsp_end,
19536                    };
19537                    Some(Completion {
19538                        replace_range: range,
19539                        new_text: snippet.body.clone(),
19540                        source: CompletionSource::Lsp {
19541                            insert_range: None,
19542                            server_id: LanguageServerId(usize::MAX),
19543                            resolved: true,
19544                            lsp_completion: Box::new(lsp::CompletionItem {
19545                                label: snippet.prefix.first().unwrap().clone(),
19546                                kind: Some(CompletionItemKind::SNIPPET),
19547                                label_details: snippet.description.as_ref().map(|description| {
19548                                    lsp::CompletionItemLabelDetails {
19549                                        detail: Some(description.clone()),
19550                                        description: None,
19551                                    }
19552                                }),
19553                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19554                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19555                                    lsp::InsertReplaceEdit {
19556                                        new_text: snippet.body.clone(),
19557                                        insert: lsp_range,
19558                                        replace: lsp_range,
19559                                    },
19560                                )),
19561                                filter_text: Some(snippet.body.clone()),
19562                                sort_text: Some(char::MAX.to_string()),
19563                                ..lsp::CompletionItem::default()
19564                            }),
19565                            lsp_defaults: None,
19566                        },
19567                        label: CodeLabel {
19568                            text: matching_prefix.clone(),
19569                            runs: Vec::new(),
19570                            filter_range: 0..matching_prefix.len(),
19571                        },
19572                        icon_path: None,
19573                        documentation: snippet.description.clone().map(|description| {
19574                            CompletionDocumentation::SingleLine(description.into())
19575                        }),
19576                        insert_text_mode: None,
19577                        confirm: None,
19578                    })
19579                })
19580                .collect();
19581
19582            all_results.append(&mut result);
19583        }
19584
19585        Ok(all_results)
19586    })
19587}
19588
19589impl CompletionProvider for Entity<Project> {
19590    fn completions(
19591        &self,
19592        _excerpt_id: ExcerptId,
19593        buffer: &Entity<Buffer>,
19594        buffer_position: text::Anchor,
19595        options: CompletionContext,
19596        _window: &mut Window,
19597        cx: &mut Context<Editor>,
19598    ) -> Task<Result<Option<Vec<Completion>>>> {
19599        self.update(cx, |project, cx| {
19600            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19601            let project_completions = project.completions(buffer, buffer_position, options, cx);
19602            cx.background_spawn(async move {
19603                let snippets_completions = snippets.await?;
19604                match project_completions.await? {
19605                    Some(mut completions) => {
19606                        completions.extend(snippets_completions);
19607                        Ok(Some(completions))
19608                    }
19609                    None => {
19610                        if snippets_completions.is_empty() {
19611                            Ok(None)
19612                        } else {
19613                            Ok(Some(snippets_completions))
19614                        }
19615                    }
19616                }
19617            })
19618        })
19619    }
19620
19621    fn resolve_completions(
19622        &self,
19623        buffer: Entity<Buffer>,
19624        completion_indices: Vec<usize>,
19625        completions: Rc<RefCell<Box<[Completion]>>>,
19626        cx: &mut Context<Editor>,
19627    ) -> Task<Result<bool>> {
19628        self.update(cx, |project, cx| {
19629            project.lsp_store().update(cx, |lsp_store, cx| {
19630                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19631            })
19632        })
19633    }
19634
19635    fn apply_additional_edits_for_completion(
19636        &self,
19637        buffer: Entity<Buffer>,
19638        completions: Rc<RefCell<Box<[Completion]>>>,
19639        completion_index: usize,
19640        push_to_history: bool,
19641        cx: &mut Context<Editor>,
19642    ) -> Task<Result<Option<language::Transaction>>> {
19643        self.update(cx, |project, cx| {
19644            project.lsp_store().update(cx, |lsp_store, cx| {
19645                lsp_store.apply_additional_edits_for_completion(
19646                    buffer,
19647                    completions,
19648                    completion_index,
19649                    push_to_history,
19650                    cx,
19651                )
19652            })
19653        })
19654    }
19655
19656    fn is_completion_trigger(
19657        &self,
19658        buffer: &Entity<Buffer>,
19659        position: language::Anchor,
19660        text: &str,
19661        trigger_in_words: bool,
19662        cx: &mut Context<Editor>,
19663    ) -> bool {
19664        let mut chars = text.chars();
19665        let char = if let Some(char) = chars.next() {
19666            char
19667        } else {
19668            return false;
19669        };
19670        if chars.next().is_some() {
19671            return false;
19672        }
19673
19674        let buffer = buffer.read(cx);
19675        let snapshot = buffer.snapshot();
19676        if !snapshot.settings_at(position, cx).show_completions_on_input {
19677            return false;
19678        }
19679        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19680        if trigger_in_words && classifier.is_word(char) {
19681            return true;
19682        }
19683
19684        buffer.completion_triggers().contains(text)
19685    }
19686}
19687
19688impl SemanticsProvider for Entity<Project> {
19689    fn hover(
19690        &self,
19691        buffer: &Entity<Buffer>,
19692        position: text::Anchor,
19693        cx: &mut App,
19694    ) -> Option<Task<Vec<project::Hover>>> {
19695        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19696    }
19697
19698    fn document_highlights(
19699        &self,
19700        buffer: &Entity<Buffer>,
19701        position: text::Anchor,
19702        cx: &mut App,
19703    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19704        Some(self.update(cx, |project, cx| {
19705            project.document_highlights(buffer, position, cx)
19706        }))
19707    }
19708
19709    fn definitions(
19710        &self,
19711        buffer: &Entity<Buffer>,
19712        position: text::Anchor,
19713        kind: GotoDefinitionKind,
19714        cx: &mut App,
19715    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19716        Some(self.update(cx, |project, cx| match kind {
19717            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19718            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19719            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19720            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19721        }))
19722    }
19723
19724    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19725        // TODO: make this work for remote projects
19726        self.update(cx, |project, cx| {
19727            if project
19728                .active_debug_session(cx)
19729                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19730            {
19731                return true;
19732            }
19733
19734            buffer.update(cx, |buffer, cx| {
19735                project.any_language_server_supports_inlay_hints(buffer, cx)
19736            })
19737        })
19738    }
19739
19740    fn inline_values(
19741        &self,
19742        buffer_handle: Entity<Buffer>,
19743        range: Range<text::Anchor>,
19744        cx: &mut App,
19745    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19746        self.update(cx, |project, cx| {
19747            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19748
19749            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19750        })
19751    }
19752
19753    fn inlay_hints(
19754        &self,
19755        buffer_handle: Entity<Buffer>,
19756        range: Range<text::Anchor>,
19757        cx: &mut App,
19758    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19759        Some(self.update(cx, |project, cx| {
19760            project.inlay_hints(buffer_handle, range, cx)
19761        }))
19762    }
19763
19764    fn resolve_inlay_hint(
19765        &self,
19766        hint: InlayHint,
19767        buffer_handle: Entity<Buffer>,
19768        server_id: LanguageServerId,
19769        cx: &mut App,
19770    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19771        Some(self.update(cx, |project, cx| {
19772            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19773        }))
19774    }
19775
19776    fn range_for_rename(
19777        &self,
19778        buffer: &Entity<Buffer>,
19779        position: text::Anchor,
19780        cx: &mut App,
19781    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19782        Some(self.update(cx, |project, cx| {
19783            let buffer = buffer.clone();
19784            let task = project.prepare_rename(buffer.clone(), position, cx);
19785            cx.spawn(async move |_, cx| {
19786                Ok(match task.await? {
19787                    PrepareRenameResponse::Success(range) => Some(range),
19788                    PrepareRenameResponse::InvalidPosition => None,
19789                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19790                        // Fallback on using TreeSitter info to determine identifier range
19791                        buffer.update(cx, |buffer, _| {
19792                            let snapshot = buffer.snapshot();
19793                            let (range, kind) = snapshot.surrounding_word(position);
19794                            if kind != Some(CharKind::Word) {
19795                                return None;
19796                            }
19797                            Some(
19798                                snapshot.anchor_before(range.start)
19799                                    ..snapshot.anchor_after(range.end),
19800                            )
19801                        })?
19802                    }
19803                })
19804            })
19805        }))
19806    }
19807
19808    fn perform_rename(
19809        &self,
19810        buffer: &Entity<Buffer>,
19811        position: text::Anchor,
19812        new_name: String,
19813        cx: &mut App,
19814    ) -> Option<Task<Result<ProjectTransaction>>> {
19815        Some(self.update(cx, |project, cx| {
19816            project.perform_rename(buffer.clone(), position, new_name, cx)
19817        }))
19818    }
19819}
19820
19821fn inlay_hint_settings(
19822    location: Anchor,
19823    snapshot: &MultiBufferSnapshot,
19824    cx: &mut Context<Editor>,
19825) -> InlayHintSettings {
19826    let file = snapshot.file_at(location);
19827    let language = snapshot.language_at(location).map(|l| l.name());
19828    language_settings(language, file, cx).inlay_hints
19829}
19830
19831fn consume_contiguous_rows(
19832    contiguous_row_selections: &mut Vec<Selection<Point>>,
19833    selection: &Selection<Point>,
19834    display_map: &DisplaySnapshot,
19835    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19836) -> (MultiBufferRow, MultiBufferRow) {
19837    contiguous_row_selections.push(selection.clone());
19838    let start_row = MultiBufferRow(selection.start.row);
19839    let mut end_row = ending_row(selection, display_map);
19840
19841    while let Some(next_selection) = selections.peek() {
19842        if next_selection.start.row <= end_row.0 {
19843            end_row = ending_row(next_selection, display_map);
19844            contiguous_row_selections.push(selections.next().unwrap().clone());
19845        } else {
19846            break;
19847        }
19848    }
19849    (start_row, end_row)
19850}
19851
19852fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19853    if next_selection.end.column > 0 || next_selection.is_empty() {
19854        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19855    } else {
19856        MultiBufferRow(next_selection.end.row)
19857    }
19858}
19859
19860impl EditorSnapshot {
19861    pub fn remote_selections_in_range<'a>(
19862        &'a self,
19863        range: &'a Range<Anchor>,
19864        collaboration_hub: &dyn CollaborationHub,
19865        cx: &'a App,
19866    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19867        let participant_names = collaboration_hub.user_names(cx);
19868        let participant_indices = collaboration_hub.user_participant_indices(cx);
19869        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19870        let collaborators_by_replica_id = collaborators_by_peer_id
19871            .iter()
19872            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19873            .collect::<HashMap<_, _>>();
19874        self.buffer_snapshot
19875            .selections_in_range(range, false)
19876            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19877                if replica_id == AGENT_REPLICA_ID {
19878                    Some(RemoteSelection {
19879                        replica_id,
19880                        selection,
19881                        cursor_shape,
19882                        line_mode,
19883                        collaborator_id: CollaboratorId::Agent,
19884                        user_name: Some("Agent".into()),
19885                        color: cx.theme().players().agent(),
19886                    })
19887                } else {
19888                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19889                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19890                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19891                    Some(RemoteSelection {
19892                        replica_id,
19893                        selection,
19894                        cursor_shape,
19895                        line_mode,
19896                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19897                        user_name,
19898                        color: if let Some(index) = participant_index {
19899                            cx.theme().players().color_for_participant(index.0)
19900                        } else {
19901                            cx.theme().players().absent()
19902                        },
19903                    })
19904                }
19905            })
19906    }
19907
19908    pub fn hunks_for_ranges(
19909        &self,
19910        ranges: impl IntoIterator<Item = Range<Point>>,
19911    ) -> Vec<MultiBufferDiffHunk> {
19912        let mut hunks = Vec::new();
19913        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19914            HashMap::default();
19915        for query_range in ranges {
19916            let query_rows =
19917                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19918            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19919                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19920            ) {
19921                // Include deleted hunks that are adjacent to the query range, because
19922                // otherwise they would be missed.
19923                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19924                if hunk.status().is_deleted() {
19925                    intersects_range |= hunk.row_range.start == query_rows.end;
19926                    intersects_range |= hunk.row_range.end == query_rows.start;
19927                }
19928                if intersects_range {
19929                    if !processed_buffer_rows
19930                        .entry(hunk.buffer_id)
19931                        .or_default()
19932                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19933                    {
19934                        continue;
19935                    }
19936                    hunks.push(hunk);
19937                }
19938            }
19939        }
19940
19941        hunks
19942    }
19943
19944    fn display_diff_hunks_for_rows<'a>(
19945        &'a self,
19946        display_rows: Range<DisplayRow>,
19947        folded_buffers: &'a HashSet<BufferId>,
19948    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19949        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19950        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19951
19952        self.buffer_snapshot
19953            .diff_hunks_in_range(buffer_start..buffer_end)
19954            .filter_map(|hunk| {
19955                if folded_buffers.contains(&hunk.buffer_id) {
19956                    return None;
19957                }
19958
19959                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19960                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19961
19962                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19963                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19964
19965                let display_hunk = if hunk_display_start.column() != 0 {
19966                    DisplayDiffHunk::Folded {
19967                        display_row: hunk_display_start.row(),
19968                    }
19969                } else {
19970                    let mut end_row = hunk_display_end.row();
19971                    if hunk_display_end.column() > 0 {
19972                        end_row.0 += 1;
19973                    }
19974                    let is_created_file = hunk.is_created_file();
19975                    DisplayDiffHunk::Unfolded {
19976                        status: hunk.status(),
19977                        diff_base_byte_range: hunk.diff_base_byte_range,
19978                        display_row_range: hunk_display_start.row()..end_row,
19979                        multi_buffer_range: Anchor::range_in_buffer(
19980                            hunk.excerpt_id,
19981                            hunk.buffer_id,
19982                            hunk.buffer_range,
19983                        ),
19984                        is_created_file,
19985                    }
19986                };
19987
19988                Some(display_hunk)
19989            })
19990    }
19991
19992    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19993        self.display_snapshot.buffer_snapshot.language_at(position)
19994    }
19995
19996    pub fn is_focused(&self) -> bool {
19997        self.is_focused
19998    }
19999
20000    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20001        self.placeholder_text.as_ref()
20002    }
20003
20004    pub fn scroll_position(&self) -> gpui::Point<f32> {
20005        self.scroll_anchor.scroll_position(&self.display_snapshot)
20006    }
20007
20008    fn gutter_dimensions(
20009        &self,
20010        font_id: FontId,
20011        font_size: Pixels,
20012        max_line_number_width: Pixels,
20013        cx: &App,
20014    ) -> Option<GutterDimensions> {
20015        if !self.show_gutter {
20016            return None;
20017        }
20018
20019        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20020        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20021
20022        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20023            matches!(
20024                ProjectSettings::get_global(cx).git.git_gutter,
20025                Some(GitGutterSetting::TrackedFiles)
20026            )
20027        });
20028        let gutter_settings = EditorSettings::get_global(cx).gutter;
20029        let show_line_numbers = self
20030            .show_line_numbers
20031            .unwrap_or(gutter_settings.line_numbers);
20032        let line_gutter_width = if show_line_numbers {
20033            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20034            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20035            max_line_number_width.max(min_width_for_number_on_gutter)
20036        } else {
20037            0.0.into()
20038        };
20039
20040        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20041        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20042
20043        let git_blame_entries_width =
20044            self.git_blame_gutter_max_author_length
20045                .map(|max_author_length| {
20046                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20047                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20048
20049                    /// The number of characters to dedicate to gaps and margins.
20050                    const SPACING_WIDTH: usize = 4;
20051
20052                    let max_char_count = max_author_length.min(renderer.max_author_length())
20053                        + ::git::SHORT_SHA_LENGTH
20054                        + MAX_RELATIVE_TIMESTAMP.len()
20055                        + SPACING_WIDTH;
20056
20057                    em_advance * max_char_count
20058                });
20059
20060        let is_singleton = self.buffer_snapshot.is_singleton();
20061
20062        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20063        left_padding += if !is_singleton {
20064            em_width * 4.0
20065        } else if show_runnables || show_breakpoints {
20066            em_width * 3.0
20067        } else if show_git_gutter && show_line_numbers {
20068            em_width * 2.0
20069        } else if show_git_gutter || show_line_numbers {
20070            em_width
20071        } else {
20072            px(0.)
20073        };
20074
20075        let shows_folds = is_singleton && gutter_settings.folds;
20076
20077        let right_padding = if shows_folds && show_line_numbers {
20078            em_width * 4.0
20079        } else if shows_folds || (!is_singleton && show_line_numbers) {
20080            em_width * 3.0
20081        } else if show_line_numbers {
20082            em_width
20083        } else {
20084            px(0.)
20085        };
20086
20087        Some(GutterDimensions {
20088            left_padding,
20089            right_padding,
20090            width: line_gutter_width + left_padding + right_padding,
20091            margin: GutterDimensions::default_gutter_margin(font_id, font_size, cx),
20092            git_blame_entries_width,
20093        })
20094    }
20095
20096    pub fn render_crease_toggle(
20097        &self,
20098        buffer_row: MultiBufferRow,
20099        row_contains_cursor: bool,
20100        editor: Entity<Editor>,
20101        window: &mut Window,
20102        cx: &mut App,
20103    ) -> Option<AnyElement> {
20104        let folded = self.is_line_folded(buffer_row);
20105        let mut is_foldable = false;
20106
20107        if let Some(crease) = self
20108            .crease_snapshot
20109            .query_row(buffer_row, &self.buffer_snapshot)
20110        {
20111            is_foldable = true;
20112            match crease {
20113                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20114                    if let Some(render_toggle) = render_toggle {
20115                        let toggle_callback =
20116                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20117                                if folded {
20118                                    editor.update(cx, |editor, cx| {
20119                                        editor.fold_at(buffer_row, window, cx)
20120                                    });
20121                                } else {
20122                                    editor.update(cx, |editor, cx| {
20123                                        editor.unfold_at(buffer_row, window, cx)
20124                                    });
20125                                }
20126                            });
20127                        return Some((render_toggle)(
20128                            buffer_row,
20129                            folded,
20130                            toggle_callback,
20131                            window,
20132                            cx,
20133                        ));
20134                    }
20135                }
20136            }
20137        }
20138
20139        is_foldable |= self.starts_indent(buffer_row);
20140
20141        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20142            Some(
20143                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20144                    .toggle_state(folded)
20145                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20146                        if folded {
20147                            this.unfold_at(buffer_row, window, cx);
20148                        } else {
20149                            this.fold_at(buffer_row, window, cx);
20150                        }
20151                    }))
20152                    .into_any_element(),
20153            )
20154        } else {
20155            None
20156        }
20157    }
20158
20159    pub fn render_crease_trailer(
20160        &self,
20161        buffer_row: MultiBufferRow,
20162        window: &mut Window,
20163        cx: &mut App,
20164    ) -> Option<AnyElement> {
20165        let folded = self.is_line_folded(buffer_row);
20166        if let Crease::Inline { render_trailer, .. } = self
20167            .crease_snapshot
20168            .query_row(buffer_row, &self.buffer_snapshot)?
20169        {
20170            let render_trailer = render_trailer.as_ref()?;
20171            Some(render_trailer(buffer_row, folded, window, cx))
20172        } else {
20173            None
20174        }
20175    }
20176}
20177
20178impl Deref for EditorSnapshot {
20179    type Target = DisplaySnapshot;
20180
20181    fn deref(&self) -> &Self::Target {
20182        &self.display_snapshot
20183    }
20184}
20185
20186#[derive(Clone, Debug, PartialEq, Eq)]
20187pub enum EditorEvent {
20188    InputIgnored {
20189        text: Arc<str>,
20190    },
20191    InputHandled {
20192        utf16_range_to_replace: Option<Range<isize>>,
20193        text: Arc<str>,
20194    },
20195    ExcerptsAdded {
20196        buffer: Entity<Buffer>,
20197        predecessor: ExcerptId,
20198        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20199    },
20200    ExcerptsRemoved {
20201        ids: Vec<ExcerptId>,
20202        removed_buffer_ids: Vec<BufferId>,
20203    },
20204    BufferFoldToggled {
20205        ids: Vec<ExcerptId>,
20206        folded: bool,
20207    },
20208    ExcerptsEdited {
20209        ids: Vec<ExcerptId>,
20210    },
20211    ExcerptsExpanded {
20212        ids: Vec<ExcerptId>,
20213    },
20214    BufferEdited,
20215    Edited {
20216        transaction_id: clock::Lamport,
20217    },
20218    Reparsed(BufferId),
20219    Focused,
20220    FocusedIn,
20221    Blurred,
20222    DirtyChanged,
20223    Saved,
20224    TitleChanged,
20225    DiffBaseChanged,
20226    SelectionsChanged {
20227        local: bool,
20228    },
20229    ScrollPositionChanged {
20230        local: bool,
20231        autoscroll: bool,
20232    },
20233    Closed,
20234    TransactionUndone {
20235        transaction_id: clock::Lamport,
20236    },
20237    TransactionBegun {
20238        transaction_id: clock::Lamport,
20239    },
20240    Reloaded,
20241    CursorShapeChanged,
20242    PushedToNavHistory {
20243        anchor: Anchor,
20244        is_deactivate: bool,
20245    },
20246}
20247
20248impl EventEmitter<EditorEvent> for Editor {}
20249
20250impl Focusable for Editor {
20251    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20252        self.focus_handle.clone()
20253    }
20254}
20255
20256impl Render for Editor {
20257    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20258        let settings = ThemeSettings::get_global(cx);
20259
20260        let mut text_style = match self.mode {
20261            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20262                color: cx.theme().colors().editor_foreground,
20263                font_family: settings.ui_font.family.clone(),
20264                font_features: settings.ui_font.features.clone(),
20265                font_fallbacks: settings.ui_font.fallbacks.clone(),
20266                font_size: rems(0.875).into(),
20267                font_weight: settings.ui_font.weight,
20268                line_height: relative(settings.buffer_line_height.value()),
20269                ..Default::default()
20270            },
20271            EditorMode::Full { .. } => TextStyle {
20272                color: cx.theme().colors().editor_foreground,
20273                font_family: settings.buffer_font.family.clone(),
20274                font_features: settings.buffer_font.features.clone(),
20275                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20276                font_size: settings.buffer_font_size(cx).into(),
20277                font_weight: settings.buffer_font.weight,
20278                line_height: relative(settings.buffer_line_height.value()),
20279                ..Default::default()
20280            },
20281        };
20282        if let Some(text_style_refinement) = &self.text_style_refinement {
20283            text_style.refine(text_style_refinement)
20284        }
20285
20286        let background = match self.mode {
20287            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20288            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20289            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20290        };
20291
20292        EditorElement::new(
20293            &cx.entity(),
20294            EditorStyle {
20295                background,
20296                local_player: cx.theme().players().local(),
20297                text: text_style,
20298                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20299                syntax: cx.theme().syntax().clone(),
20300                status: cx.theme().status().clone(),
20301                inlay_hints_style: make_inlay_hints_style(cx),
20302                inline_completion_styles: make_suggestion_styles(cx),
20303                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20304            },
20305        )
20306    }
20307}
20308
20309impl EntityInputHandler for Editor {
20310    fn text_for_range(
20311        &mut self,
20312        range_utf16: Range<usize>,
20313        adjusted_range: &mut Option<Range<usize>>,
20314        _: &mut Window,
20315        cx: &mut Context<Self>,
20316    ) -> Option<String> {
20317        let snapshot = self.buffer.read(cx).read(cx);
20318        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20319        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20320        if (start.0..end.0) != range_utf16 {
20321            adjusted_range.replace(start.0..end.0);
20322        }
20323        Some(snapshot.text_for_range(start..end).collect())
20324    }
20325
20326    fn selected_text_range(
20327        &mut self,
20328        ignore_disabled_input: bool,
20329        _: &mut Window,
20330        cx: &mut Context<Self>,
20331    ) -> Option<UTF16Selection> {
20332        // Prevent the IME menu from appearing when holding down an alphabetic key
20333        // while input is disabled.
20334        if !ignore_disabled_input && !self.input_enabled {
20335            return None;
20336        }
20337
20338        let selection = self.selections.newest::<OffsetUtf16>(cx);
20339        let range = selection.range();
20340
20341        Some(UTF16Selection {
20342            range: range.start.0..range.end.0,
20343            reversed: selection.reversed,
20344        })
20345    }
20346
20347    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20348        let snapshot = self.buffer.read(cx).read(cx);
20349        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20350        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20351    }
20352
20353    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20354        self.clear_highlights::<InputComposition>(cx);
20355        self.ime_transaction.take();
20356    }
20357
20358    fn replace_text_in_range(
20359        &mut self,
20360        range_utf16: Option<Range<usize>>,
20361        text: &str,
20362        window: &mut Window,
20363        cx: &mut Context<Self>,
20364    ) {
20365        if !self.input_enabled {
20366            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20367            return;
20368        }
20369
20370        self.transact(window, cx, |this, window, cx| {
20371            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20372                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20373                Some(this.selection_replacement_ranges(range_utf16, cx))
20374            } else {
20375                this.marked_text_ranges(cx)
20376            };
20377
20378            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20379                let newest_selection_id = this.selections.newest_anchor().id;
20380                this.selections
20381                    .all::<OffsetUtf16>(cx)
20382                    .iter()
20383                    .zip(ranges_to_replace.iter())
20384                    .find_map(|(selection, range)| {
20385                        if selection.id == newest_selection_id {
20386                            Some(
20387                                (range.start.0 as isize - selection.head().0 as isize)
20388                                    ..(range.end.0 as isize - selection.head().0 as isize),
20389                            )
20390                        } else {
20391                            None
20392                        }
20393                    })
20394            });
20395
20396            cx.emit(EditorEvent::InputHandled {
20397                utf16_range_to_replace: range_to_replace,
20398                text: text.into(),
20399            });
20400
20401            if let Some(new_selected_ranges) = new_selected_ranges {
20402                this.change_selections(None, window, cx, |selections| {
20403                    selections.select_ranges(new_selected_ranges)
20404                });
20405                this.backspace(&Default::default(), window, cx);
20406            }
20407
20408            this.handle_input(text, window, cx);
20409        });
20410
20411        if let Some(transaction) = self.ime_transaction {
20412            self.buffer.update(cx, |buffer, cx| {
20413                buffer.group_until_transaction(transaction, cx);
20414            });
20415        }
20416
20417        self.unmark_text(window, cx);
20418    }
20419
20420    fn replace_and_mark_text_in_range(
20421        &mut self,
20422        range_utf16: Option<Range<usize>>,
20423        text: &str,
20424        new_selected_range_utf16: Option<Range<usize>>,
20425        window: &mut Window,
20426        cx: &mut Context<Self>,
20427    ) {
20428        if !self.input_enabled {
20429            return;
20430        }
20431
20432        let transaction = self.transact(window, cx, |this, window, cx| {
20433            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20434                let snapshot = this.buffer.read(cx).read(cx);
20435                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20436                    for marked_range in &mut marked_ranges {
20437                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20438                        marked_range.start.0 += relative_range_utf16.start;
20439                        marked_range.start =
20440                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20441                        marked_range.end =
20442                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20443                    }
20444                }
20445                Some(marked_ranges)
20446            } else if let Some(range_utf16) = range_utf16 {
20447                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20448                Some(this.selection_replacement_ranges(range_utf16, cx))
20449            } else {
20450                None
20451            };
20452
20453            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20454                let newest_selection_id = this.selections.newest_anchor().id;
20455                this.selections
20456                    .all::<OffsetUtf16>(cx)
20457                    .iter()
20458                    .zip(ranges_to_replace.iter())
20459                    .find_map(|(selection, range)| {
20460                        if selection.id == newest_selection_id {
20461                            Some(
20462                                (range.start.0 as isize - selection.head().0 as isize)
20463                                    ..(range.end.0 as isize - selection.head().0 as isize),
20464                            )
20465                        } else {
20466                            None
20467                        }
20468                    })
20469            });
20470
20471            cx.emit(EditorEvent::InputHandled {
20472                utf16_range_to_replace: range_to_replace,
20473                text: text.into(),
20474            });
20475
20476            if let Some(ranges) = ranges_to_replace {
20477                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20478            }
20479
20480            let marked_ranges = {
20481                let snapshot = this.buffer.read(cx).read(cx);
20482                this.selections
20483                    .disjoint_anchors()
20484                    .iter()
20485                    .map(|selection| {
20486                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20487                    })
20488                    .collect::<Vec<_>>()
20489            };
20490
20491            if text.is_empty() {
20492                this.unmark_text(window, cx);
20493            } else {
20494                this.highlight_text::<InputComposition>(
20495                    marked_ranges.clone(),
20496                    HighlightStyle {
20497                        underline: Some(UnderlineStyle {
20498                            thickness: px(1.),
20499                            color: None,
20500                            wavy: false,
20501                        }),
20502                        ..Default::default()
20503                    },
20504                    cx,
20505                );
20506            }
20507
20508            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20509            let use_autoclose = this.use_autoclose;
20510            let use_auto_surround = this.use_auto_surround;
20511            this.set_use_autoclose(false);
20512            this.set_use_auto_surround(false);
20513            this.handle_input(text, window, cx);
20514            this.set_use_autoclose(use_autoclose);
20515            this.set_use_auto_surround(use_auto_surround);
20516
20517            if let Some(new_selected_range) = new_selected_range_utf16 {
20518                let snapshot = this.buffer.read(cx).read(cx);
20519                let new_selected_ranges = marked_ranges
20520                    .into_iter()
20521                    .map(|marked_range| {
20522                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20523                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20524                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20525                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20526                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20527                    })
20528                    .collect::<Vec<_>>();
20529
20530                drop(snapshot);
20531                this.change_selections(None, window, cx, |selections| {
20532                    selections.select_ranges(new_selected_ranges)
20533                });
20534            }
20535        });
20536
20537        self.ime_transaction = self.ime_transaction.or(transaction);
20538        if let Some(transaction) = self.ime_transaction {
20539            self.buffer.update(cx, |buffer, cx| {
20540                buffer.group_until_transaction(transaction, cx);
20541            });
20542        }
20543
20544        if self.text_highlights::<InputComposition>(cx).is_none() {
20545            self.ime_transaction.take();
20546        }
20547    }
20548
20549    fn bounds_for_range(
20550        &mut self,
20551        range_utf16: Range<usize>,
20552        element_bounds: gpui::Bounds<Pixels>,
20553        window: &mut Window,
20554        cx: &mut Context<Self>,
20555    ) -> Option<gpui::Bounds<Pixels>> {
20556        let text_layout_details = self.text_layout_details(window);
20557        let gpui::Size {
20558            width: em_width,
20559            height: line_height,
20560        } = self.character_size(window);
20561
20562        let snapshot = self.snapshot(window, cx);
20563        let scroll_position = snapshot.scroll_position();
20564        let scroll_left = scroll_position.x * em_width;
20565
20566        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20567        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20568            + self.gutter_dimensions.width
20569            + self.gutter_dimensions.margin;
20570        let y = line_height * (start.row().as_f32() - scroll_position.y);
20571
20572        Some(Bounds {
20573            origin: element_bounds.origin + point(x, y),
20574            size: size(em_width, line_height),
20575        })
20576    }
20577
20578    fn character_index_for_point(
20579        &mut self,
20580        point: gpui::Point<Pixels>,
20581        _window: &mut Window,
20582        _cx: &mut Context<Self>,
20583    ) -> Option<usize> {
20584        let position_map = self.last_position_map.as_ref()?;
20585        if !position_map.text_hitbox.contains(&point) {
20586            return None;
20587        }
20588        let display_point = position_map.point_for_position(point).previous_valid;
20589        let anchor = position_map
20590            .snapshot
20591            .display_point_to_anchor(display_point, Bias::Left);
20592        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20593        Some(utf16_offset.0)
20594    }
20595}
20596
20597trait SelectionExt {
20598    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20599    fn spanned_rows(
20600        &self,
20601        include_end_if_at_line_start: bool,
20602        map: &DisplaySnapshot,
20603    ) -> Range<MultiBufferRow>;
20604}
20605
20606impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20607    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20608        let start = self
20609            .start
20610            .to_point(&map.buffer_snapshot)
20611            .to_display_point(map);
20612        let end = self
20613            .end
20614            .to_point(&map.buffer_snapshot)
20615            .to_display_point(map);
20616        if self.reversed {
20617            end..start
20618        } else {
20619            start..end
20620        }
20621    }
20622
20623    fn spanned_rows(
20624        &self,
20625        include_end_if_at_line_start: bool,
20626        map: &DisplaySnapshot,
20627    ) -> Range<MultiBufferRow> {
20628        let start = self.start.to_point(&map.buffer_snapshot);
20629        let mut end = self.end.to_point(&map.buffer_snapshot);
20630        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20631            end.row -= 1;
20632        }
20633
20634        let buffer_start = map.prev_line_boundary(start).0;
20635        let buffer_end = map.next_line_boundary(end).0;
20636        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20637    }
20638}
20639
20640impl<T: InvalidationRegion> InvalidationStack<T> {
20641    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20642    where
20643        S: Clone + ToOffset,
20644    {
20645        while let Some(region) = self.last() {
20646            let all_selections_inside_invalidation_ranges =
20647                if selections.len() == region.ranges().len() {
20648                    selections
20649                        .iter()
20650                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20651                        .all(|(selection, invalidation_range)| {
20652                            let head = selection.head().to_offset(buffer);
20653                            invalidation_range.start <= head && invalidation_range.end >= head
20654                        })
20655                } else {
20656                    false
20657                };
20658
20659            if all_selections_inside_invalidation_ranges {
20660                break;
20661            } else {
20662                self.pop();
20663            }
20664        }
20665    }
20666}
20667
20668impl<T> Default for InvalidationStack<T> {
20669    fn default() -> Self {
20670        Self(Default::default())
20671    }
20672}
20673
20674impl<T> Deref for InvalidationStack<T> {
20675    type Target = Vec<T>;
20676
20677    fn deref(&self) -> &Self::Target {
20678        &self.0
20679    }
20680}
20681
20682impl<T> DerefMut for InvalidationStack<T> {
20683    fn deref_mut(&mut self) -> &mut Self::Target {
20684        &mut self.0
20685    }
20686}
20687
20688impl InvalidationRegion for SnippetState {
20689    fn ranges(&self) -> &[Range<Anchor>] {
20690        &self.ranges[self.active_index]
20691    }
20692}
20693
20694fn inline_completion_edit_text(
20695    current_snapshot: &BufferSnapshot,
20696    edits: &[(Range<Anchor>, String)],
20697    edit_preview: &EditPreview,
20698    include_deletions: bool,
20699    cx: &App,
20700) -> HighlightedText {
20701    let edits = edits
20702        .iter()
20703        .map(|(anchor, text)| {
20704            (
20705                anchor.start.text_anchor..anchor.end.text_anchor,
20706                text.clone(),
20707            )
20708        })
20709        .collect::<Vec<_>>();
20710
20711    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20712}
20713
20714pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20715    match severity {
20716        DiagnosticSeverity::ERROR => colors.error,
20717        DiagnosticSeverity::WARNING => colors.warning,
20718        DiagnosticSeverity::INFORMATION => colors.info,
20719        DiagnosticSeverity::HINT => colors.info,
20720        _ => colors.ignored,
20721    }
20722}
20723
20724pub fn styled_runs_for_code_label<'a>(
20725    label: &'a CodeLabel,
20726    syntax_theme: &'a theme::SyntaxTheme,
20727) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20728    let fade_out = HighlightStyle {
20729        fade_out: Some(0.35),
20730        ..Default::default()
20731    };
20732
20733    let mut prev_end = label.filter_range.end;
20734    label
20735        .runs
20736        .iter()
20737        .enumerate()
20738        .flat_map(move |(ix, (range, highlight_id))| {
20739            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20740                style
20741            } else {
20742                return Default::default();
20743            };
20744            let mut muted_style = style;
20745            muted_style.highlight(fade_out);
20746
20747            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20748            if range.start >= label.filter_range.end {
20749                if range.start > prev_end {
20750                    runs.push((prev_end..range.start, fade_out));
20751                }
20752                runs.push((range.clone(), muted_style));
20753            } else if range.end <= label.filter_range.end {
20754                runs.push((range.clone(), style));
20755            } else {
20756                runs.push((range.start..label.filter_range.end, style));
20757                runs.push((label.filter_range.end..range.end, muted_style));
20758            }
20759            prev_end = cmp::max(prev_end, range.end);
20760
20761            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20762                runs.push((prev_end..label.text.len(), fade_out));
20763            }
20764
20765            runs
20766        })
20767}
20768
20769pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20770    let mut prev_index = 0;
20771    let mut prev_codepoint: Option<char> = None;
20772    text.char_indices()
20773        .chain([(text.len(), '\0')])
20774        .filter_map(move |(index, codepoint)| {
20775            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20776            let is_boundary = index == text.len()
20777                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20778                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20779            if is_boundary {
20780                let chunk = &text[prev_index..index];
20781                prev_index = index;
20782                Some(chunk)
20783            } else {
20784                None
20785            }
20786        })
20787}
20788
20789pub trait RangeToAnchorExt: Sized {
20790    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20791
20792    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20793        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20794        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20795    }
20796}
20797
20798impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20799    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20800        let start_offset = self.start.to_offset(snapshot);
20801        let end_offset = self.end.to_offset(snapshot);
20802        if start_offset == end_offset {
20803            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20804        } else {
20805            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20806        }
20807    }
20808}
20809
20810pub trait RowExt {
20811    fn as_f32(&self) -> f32;
20812
20813    fn next_row(&self) -> Self;
20814
20815    fn previous_row(&self) -> Self;
20816
20817    fn minus(&self, other: Self) -> u32;
20818}
20819
20820impl RowExt for DisplayRow {
20821    fn as_f32(&self) -> f32 {
20822        self.0 as f32
20823    }
20824
20825    fn next_row(&self) -> Self {
20826        Self(self.0 + 1)
20827    }
20828
20829    fn previous_row(&self) -> Self {
20830        Self(self.0.saturating_sub(1))
20831    }
20832
20833    fn minus(&self, other: Self) -> u32 {
20834        self.0 - other.0
20835    }
20836}
20837
20838impl RowExt for MultiBufferRow {
20839    fn as_f32(&self) -> f32 {
20840        self.0 as f32
20841    }
20842
20843    fn next_row(&self) -> Self {
20844        Self(self.0 + 1)
20845    }
20846
20847    fn previous_row(&self) -> Self {
20848        Self(self.0.saturating_sub(1))
20849    }
20850
20851    fn minus(&self, other: Self) -> u32 {
20852        self.0 - other.0
20853    }
20854}
20855
20856trait RowRangeExt {
20857    type Row;
20858
20859    fn len(&self) -> usize;
20860
20861    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20862}
20863
20864impl RowRangeExt for Range<MultiBufferRow> {
20865    type Row = MultiBufferRow;
20866
20867    fn len(&self) -> usize {
20868        (self.end.0 - self.start.0) as usize
20869    }
20870
20871    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20872        (self.start.0..self.end.0).map(MultiBufferRow)
20873    }
20874}
20875
20876impl RowRangeExt for Range<DisplayRow> {
20877    type Row = DisplayRow;
20878
20879    fn len(&self) -> usize {
20880        (self.end.0 - self.start.0) as usize
20881    }
20882
20883    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20884        (self.start.0..self.end.0).map(DisplayRow)
20885    }
20886}
20887
20888/// If select range has more than one line, we
20889/// just point the cursor to range.start.
20890fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20891    if range.start.row == range.end.row {
20892        range
20893    } else {
20894        range.start..range.start
20895    }
20896}
20897pub struct KillRing(ClipboardItem);
20898impl Global for KillRing {}
20899
20900const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20901
20902enum BreakpointPromptEditAction {
20903    Log,
20904    Condition,
20905    HitCondition,
20906}
20907
20908struct BreakpointPromptEditor {
20909    pub(crate) prompt: Entity<Editor>,
20910    editor: WeakEntity<Editor>,
20911    breakpoint_anchor: Anchor,
20912    breakpoint: Breakpoint,
20913    edit_action: BreakpointPromptEditAction,
20914    block_ids: HashSet<CustomBlockId>,
20915    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20916    _subscriptions: Vec<Subscription>,
20917}
20918
20919impl BreakpointPromptEditor {
20920    const MAX_LINES: u8 = 4;
20921
20922    fn new(
20923        editor: WeakEntity<Editor>,
20924        breakpoint_anchor: Anchor,
20925        breakpoint: Breakpoint,
20926        edit_action: BreakpointPromptEditAction,
20927        window: &mut Window,
20928        cx: &mut Context<Self>,
20929    ) -> Self {
20930        let base_text = match edit_action {
20931            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20932            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20933            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20934        }
20935        .map(|msg| msg.to_string())
20936        .unwrap_or_default();
20937
20938        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20939        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20940
20941        let prompt = cx.new(|cx| {
20942            let mut prompt = Editor::new(
20943                EditorMode::AutoHeight {
20944                    max_lines: Self::MAX_LINES as usize,
20945                },
20946                buffer,
20947                None,
20948                window,
20949                cx,
20950            );
20951            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20952            prompt.set_show_cursor_when_unfocused(false, cx);
20953            prompt.set_placeholder_text(
20954                match edit_action {
20955                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20956                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20957                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20958                },
20959                cx,
20960            );
20961
20962            prompt
20963        });
20964
20965        Self {
20966            prompt,
20967            editor,
20968            breakpoint_anchor,
20969            breakpoint,
20970            edit_action,
20971            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20972            block_ids: Default::default(),
20973            _subscriptions: vec![],
20974        }
20975    }
20976
20977    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20978        self.block_ids.extend(block_ids)
20979    }
20980
20981    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20982        if let Some(editor) = self.editor.upgrade() {
20983            let message = self
20984                .prompt
20985                .read(cx)
20986                .buffer
20987                .read(cx)
20988                .as_singleton()
20989                .expect("A multi buffer in breakpoint prompt isn't possible")
20990                .read(cx)
20991                .as_rope()
20992                .to_string();
20993
20994            editor.update(cx, |editor, cx| {
20995                editor.edit_breakpoint_at_anchor(
20996                    self.breakpoint_anchor,
20997                    self.breakpoint.clone(),
20998                    match self.edit_action {
20999                        BreakpointPromptEditAction::Log => {
21000                            BreakpointEditAction::EditLogMessage(message.into())
21001                        }
21002                        BreakpointPromptEditAction::Condition => {
21003                            BreakpointEditAction::EditCondition(message.into())
21004                        }
21005                        BreakpointPromptEditAction::HitCondition => {
21006                            BreakpointEditAction::EditHitCondition(message.into())
21007                        }
21008                    },
21009                    cx,
21010                );
21011
21012                editor.remove_blocks(self.block_ids.clone(), None, cx);
21013                cx.focus_self(window);
21014            });
21015        }
21016    }
21017
21018    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21019        self.editor
21020            .update(cx, |editor, cx| {
21021                editor.remove_blocks(self.block_ids.clone(), None, cx);
21022                window.focus(&editor.focus_handle);
21023            })
21024            .log_err();
21025    }
21026
21027    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21028        let settings = ThemeSettings::get_global(cx);
21029        let text_style = TextStyle {
21030            color: if self.prompt.read(cx).read_only(cx) {
21031                cx.theme().colors().text_disabled
21032            } else {
21033                cx.theme().colors().text
21034            },
21035            font_family: settings.buffer_font.family.clone(),
21036            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21037            font_size: settings.buffer_font_size(cx).into(),
21038            font_weight: settings.buffer_font.weight,
21039            line_height: relative(settings.buffer_line_height.value()),
21040            ..Default::default()
21041        };
21042        EditorElement::new(
21043            &self.prompt,
21044            EditorStyle {
21045                background: cx.theme().colors().editor_background,
21046                local_player: cx.theme().players().local(),
21047                text: text_style,
21048                ..Default::default()
21049            },
21050        )
21051    }
21052}
21053
21054impl Render for BreakpointPromptEditor {
21055    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21056        let gutter_dimensions = *self.gutter_dimensions.lock();
21057        h_flex()
21058            .key_context("Editor")
21059            .bg(cx.theme().colors().editor_background)
21060            .border_y_1()
21061            .border_color(cx.theme().status().info_border)
21062            .size_full()
21063            .py(window.line_height() / 2.5)
21064            .on_action(cx.listener(Self::confirm))
21065            .on_action(cx.listener(Self::cancel))
21066            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21067            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21068    }
21069}
21070
21071impl Focusable for BreakpointPromptEditor {
21072    fn focus_handle(&self, cx: &App) -> FocusHandle {
21073        self.prompt.focus_handle(cx)
21074    }
21075}
21076
21077fn all_edits_insertions_or_deletions(
21078    edits: &Vec<(Range<Anchor>, String)>,
21079    snapshot: &MultiBufferSnapshot,
21080) -> bool {
21081    let mut all_insertions = true;
21082    let mut all_deletions = true;
21083
21084    for (range, new_text) in edits.iter() {
21085        let range_is_empty = range.to_offset(&snapshot).is_empty();
21086        let text_is_empty = new_text.is_empty();
21087
21088        if range_is_empty != text_is_empty {
21089            if range_is_empty {
21090                all_deletions = false;
21091            } else {
21092                all_insertions = false;
21093            }
21094        } else {
21095            return false;
21096        }
21097
21098        if !all_insertions && !all_deletions {
21099            return false;
21100        }
21101    }
21102    all_insertions || all_deletions
21103}
21104
21105struct MissingEditPredictionKeybindingTooltip;
21106
21107impl Render for MissingEditPredictionKeybindingTooltip {
21108    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21109        ui::tooltip_container(window, cx, |container, _, cx| {
21110            container
21111                .flex_shrink_0()
21112                .max_w_80()
21113                .min_h(rems_from_px(124.))
21114                .justify_between()
21115                .child(
21116                    v_flex()
21117                        .flex_1()
21118                        .text_ui_sm(cx)
21119                        .child(Label::new("Conflict with Accept Keybinding"))
21120                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21121                )
21122                .child(
21123                    h_flex()
21124                        .pb_1()
21125                        .gap_1()
21126                        .items_end()
21127                        .w_full()
21128                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21129                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21130                        }))
21131                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21132                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21133                        })),
21134                )
21135        })
21136    }
21137}
21138
21139#[derive(Debug, Clone, Copy, PartialEq)]
21140pub struct LineHighlight {
21141    pub background: Background,
21142    pub border: Option<gpui::Hsla>,
21143    pub include_gutter: bool,
21144    pub type_id: Option<TypeId>,
21145}
21146
21147fn render_diff_hunk_controls(
21148    row: u32,
21149    status: &DiffHunkStatus,
21150    hunk_range: Range<Anchor>,
21151    is_created_file: bool,
21152    line_height: Pixels,
21153    editor: &Entity<Editor>,
21154    _window: &mut Window,
21155    cx: &mut App,
21156) -> AnyElement {
21157    h_flex()
21158        .h(line_height)
21159        .mr_1()
21160        .gap_1()
21161        .px_0p5()
21162        .pb_1()
21163        .border_x_1()
21164        .border_b_1()
21165        .border_color(cx.theme().colors().border_variant)
21166        .rounded_b_lg()
21167        .bg(cx.theme().colors().editor_background)
21168        .gap_1()
21169        .occlude()
21170        .shadow_md()
21171        .child(if status.has_secondary_hunk() {
21172            Button::new(("stage", row as u64), "Stage")
21173                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21174                .tooltip({
21175                    let focus_handle = editor.focus_handle(cx);
21176                    move |window, cx| {
21177                        Tooltip::for_action_in(
21178                            "Stage Hunk",
21179                            &::git::ToggleStaged,
21180                            &focus_handle,
21181                            window,
21182                            cx,
21183                        )
21184                    }
21185                })
21186                .on_click({
21187                    let editor = editor.clone();
21188                    move |_event, _window, cx| {
21189                        editor.update(cx, |editor, cx| {
21190                            editor.stage_or_unstage_diff_hunks(
21191                                true,
21192                                vec![hunk_range.start..hunk_range.start],
21193                                cx,
21194                            );
21195                        });
21196                    }
21197                })
21198        } else {
21199            Button::new(("unstage", row as u64), "Unstage")
21200                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21201                .tooltip({
21202                    let focus_handle = editor.focus_handle(cx);
21203                    move |window, cx| {
21204                        Tooltip::for_action_in(
21205                            "Unstage Hunk",
21206                            &::git::ToggleStaged,
21207                            &focus_handle,
21208                            window,
21209                            cx,
21210                        )
21211                    }
21212                })
21213                .on_click({
21214                    let editor = editor.clone();
21215                    move |_event, _window, cx| {
21216                        editor.update(cx, |editor, cx| {
21217                            editor.stage_or_unstage_diff_hunks(
21218                                false,
21219                                vec![hunk_range.start..hunk_range.start],
21220                                cx,
21221                            );
21222                        });
21223                    }
21224                })
21225        })
21226        .child(
21227            Button::new(("restore", row as u64), "Restore")
21228                .tooltip({
21229                    let focus_handle = editor.focus_handle(cx);
21230                    move |window, cx| {
21231                        Tooltip::for_action_in(
21232                            "Restore Hunk",
21233                            &::git::Restore,
21234                            &focus_handle,
21235                            window,
21236                            cx,
21237                        )
21238                    }
21239                })
21240                .on_click({
21241                    let editor = editor.clone();
21242                    move |_event, window, cx| {
21243                        editor.update(cx, |editor, cx| {
21244                            let snapshot = editor.snapshot(window, cx);
21245                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21246                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21247                        });
21248                    }
21249                })
21250                .disabled(is_created_file),
21251        )
21252        .when(
21253            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21254            |el| {
21255                el.child(
21256                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21257                        .shape(IconButtonShape::Square)
21258                        .icon_size(IconSize::Small)
21259                        // .disabled(!has_multiple_hunks)
21260                        .tooltip({
21261                            let focus_handle = editor.focus_handle(cx);
21262                            move |window, cx| {
21263                                Tooltip::for_action_in(
21264                                    "Next Hunk",
21265                                    &GoToHunk,
21266                                    &focus_handle,
21267                                    window,
21268                                    cx,
21269                                )
21270                            }
21271                        })
21272                        .on_click({
21273                            let editor = editor.clone();
21274                            move |_event, window, cx| {
21275                                editor.update(cx, |editor, cx| {
21276                                    let snapshot = editor.snapshot(window, cx);
21277                                    let position =
21278                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21279                                    editor.go_to_hunk_before_or_after_position(
21280                                        &snapshot,
21281                                        position,
21282                                        Direction::Next,
21283                                        window,
21284                                        cx,
21285                                    );
21286                                    editor.expand_selected_diff_hunks(cx);
21287                                });
21288                            }
21289                        }),
21290                )
21291                .child(
21292                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21293                        .shape(IconButtonShape::Square)
21294                        .icon_size(IconSize::Small)
21295                        // .disabled(!has_multiple_hunks)
21296                        .tooltip({
21297                            let focus_handle = editor.focus_handle(cx);
21298                            move |window, cx| {
21299                                Tooltip::for_action_in(
21300                                    "Previous Hunk",
21301                                    &GoToPreviousHunk,
21302                                    &focus_handle,
21303                                    window,
21304                                    cx,
21305                                )
21306                            }
21307                        })
21308                        .on_click({
21309                            let editor = editor.clone();
21310                            move |_event, window, cx| {
21311                                editor.update(cx, |editor, cx| {
21312                                    let snapshot = editor.snapshot(window, cx);
21313                                    let point =
21314                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21315                                    editor.go_to_hunk_before_or_after_position(
21316                                        &snapshot,
21317                                        point,
21318                                        Direction::Prev,
21319                                        window,
21320                                        cx,
21321                                    );
21322                                    editor.expand_selected_diff_hunks(cx);
21323                                });
21324                            }
21325                        }),
21326                )
21327            },
21328        )
21329        .into_any_element()
21330}