editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132};
  133
  134pub use git::blame::BlameRenderer;
  135pub use proposed_changes_editor::{
  136    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  137};
  138use smallvec::smallvec;
  139use std::{cell::OnceCell, iter::Peekable};
  140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  141
  142pub use lsp::CompletionContext;
  143use lsp::{
  144    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  145    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  146};
  147
  148use language::BufferSnapshot;
  149pub use lsp_ext::lsp_tasks;
  150use movement::TextLayoutDetails;
  151pub use multi_buffer::{
  152    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  153    RowInfo, ToOffset, ToPoint,
  154};
  155use multi_buffer::{
  156    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  157    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  158};
  159use parking_lot::Mutex;
  160use project::{
  161    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  162    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  163    TaskSourceKind,
  164    debugger::breakpoint_store::Breakpoint,
  165    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  166    project_settings::{GitGutterSetting, ProjectSettings},
  167};
  168use rand::prelude::*;
  169use rpc::{ErrorExt, proto::*};
  170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  171use selections_collection::{
  172    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  173};
  174use serde::{Deserialize, Serialize};
  175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  176use smallvec::SmallVec;
  177use snippet::Snippet;
  178use std::sync::Arc;
  179use std::{
  180    any::TypeId,
  181    borrow::Cow,
  182    cell::RefCell,
  183    cmp::{self, Ordering, Reverse},
  184    mem,
  185    num::NonZeroU32,
  186    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  187    path::{Path, PathBuf},
  188    rc::Rc,
  189    time::{Duration, Instant},
  190};
  191pub use sum_tree::Bias;
  192use sum_tree::TreeMap;
  193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  194use theme::{
  195    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  196    observe_buffer_font_size_adjustment,
  197};
  198use ui::{
  199    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  200    IconSize, Key, Tooltip, h_flex, prelude::*,
  201};
  202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  203use workspace::{
  204    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  205    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  206    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  207    item::{ItemHandle, PreviewTabsSettings},
  208    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  209    searchable::SearchEvent,
  210};
  211
  212use crate::hover_links::{find_url, find_url_from_range};
  213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  214
  215pub const FILE_HEADER_HEIGHT: u32 = 2;
  216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  219const MAX_LINE_LEN: usize = 1024;
  220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  223#[doc(hidden)]
  224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  226
  227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  230
  231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  234
  235pub type RenderDiffHunkControlsFn = Arc<
  236    dyn Fn(
  237        u32,
  238        &DiffHunkStatus,
  239        Range<Anchor>,
  240        bool,
  241        Pixels,
  242        &Entity<Editor>,
  243        &mut Window,
  244        &mut App,
  245    ) -> AnyElement,
  246>;
  247
  248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  249    alt: true,
  250    shift: true,
  251    control: false,
  252    platform: false,
  253    function: false,
  254};
  255
  256struct InlineValueCache {
  257    enabled: bool,
  258    inlays: Vec<InlayId>,
  259    refresh_task: Task<Option<()>>,
  260}
  261
  262impl InlineValueCache {
  263    fn new(enabled: bool) -> Self {
  264        Self {
  265            enabled,
  266            inlays: Vec::new(),
  267            refresh_task: Task::ready(None),
  268        }
  269    }
  270}
  271
  272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  273pub enum InlayId {
  274    InlineCompletion(usize),
  275    Hint(usize),
  276    DebuggerValue(usize),
  277}
  278
  279impl InlayId {
  280    fn id(&self) -> usize {
  281        match self {
  282            Self::InlineCompletion(id) => *id,
  283            Self::Hint(id) => *id,
  284            Self::DebuggerValue(id) => *id,
  285        }
  286    }
  287}
  288
  289pub enum ActiveDebugLine {}
  290enum DocumentHighlightRead {}
  291enum DocumentHighlightWrite {}
  292enum InputComposition {}
  293enum SelectedTextHighlight {}
  294
  295pub enum ConflictsOuter {}
  296pub enum ConflictsOurs {}
  297pub enum ConflictsTheirs {}
  298pub enum ConflictsOursMarker {}
  299pub enum ConflictsTheirsMarker {}
  300
  301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  302pub enum Navigated {
  303    Yes,
  304    No,
  305}
  306
  307impl Navigated {
  308    pub fn from_bool(yes: bool) -> Navigated {
  309        if yes { Navigated::Yes } else { Navigated::No }
  310    }
  311}
  312
  313#[derive(Debug, Clone, PartialEq, Eq)]
  314enum DisplayDiffHunk {
  315    Folded {
  316        display_row: DisplayRow,
  317    },
  318    Unfolded {
  319        is_created_file: bool,
  320        diff_base_byte_range: Range<usize>,
  321        display_row_range: Range<DisplayRow>,
  322        multi_buffer_range: Range<Anchor>,
  323        status: DiffHunkStatus,
  324    },
  325}
  326
  327pub enum HideMouseCursorOrigin {
  328    TypingAction,
  329    MovementAction,
  330}
  331
  332pub fn init_settings(cx: &mut App) {
  333    EditorSettings::register(cx);
  334}
  335
  336pub fn init(cx: &mut App) {
  337    init_settings(cx);
  338
  339    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  340
  341    workspace::register_project_item::<Editor>(cx);
  342    workspace::FollowableViewRegistry::register::<Editor>(cx);
  343    workspace::register_serializable_item::<Editor>(cx);
  344
  345    cx.observe_new(
  346        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  347            workspace.register_action(Editor::new_file);
  348            workspace.register_action(Editor::new_file_vertical);
  349            workspace.register_action(Editor::new_file_horizontal);
  350            workspace.register_action(Editor::cancel_language_server_work);
  351        },
  352    )
  353    .detach();
  354
  355    cx.on_action(move |_: &workspace::NewFile, cx| {
  356        let app_state = workspace::AppState::global(cx);
  357        if let Some(app_state) = app_state.upgrade() {
  358            workspace::open_new(
  359                Default::default(),
  360                app_state,
  361                cx,
  362                |workspace, window, cx| {
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369    cx.on_action(move |_: &workspace::NewWindow, cx| {
  370        let app_state = workspace::AppState::global(cx);
  371        if let Some(app_state) = app_state.upgrade() {
  372            workspace::open_new(
  373                Default::default(),
  374                app_state,
  375                cx,
  376                |workspace, window, cx| {
  377                    cx.activate(true);
  378                    Editor::new_file(workspace, &Default::default(), window, cx)
  379                },
  380            )
  381            .detach();
  382        }
  383    });
  384}
  385
  386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  387    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  388}
  389
  390pub trait DiagnosticRenderer {
  391    fn render_group(
  392        &self,
  393        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  394        buffer_id: BufferId,
  395        snapshot: EditorSnapshot,
  396        editor: WeakEntity<Editor>,
  397        cx: &mut App,
  398    ) -> Vec<BlockProperties<Anchor>>;
  399
  400    fn render_hover(
  401        &self,
  402        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  403        range: Range<Point>,
  404        buffer_id: BufferId,
  405        cx: &mut App,
  406    ) -> Option<Entity<markdown::Markdown>>;
  407
  408    fn open_link(
  409        &self,
  410        editor: &mut Editor,
  411        link: SharedString,
  412        window: &mut Window,
  413        cx: &mut Context<Editor>,
  414    );
  415}
  416
  417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  418
  419impl GlobalDiagnosticRenderer {
  420    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  421        cx.try_global::<Self>().map(|g| g.0.clone())
  422    }
  423}
  424
  425impl gpui::Global for GlobalDiagnosticRenderer {}
  426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  427    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  428}
  429
  430pub struct SearchWithinRange;
  431
  432trait InvalidationRegion {
  433    fn ranges(&self) -> &[Range<Anchor>];
  434}
  435
  436#[derive(Clone, Debug, PartialEq)]
  437pub enum SelectPhase {
  438    Begin {
  439        position: DisplayPoint,
  440        add: bool,
  441        click_count: usize,
  442    },
  443    BeginColumnar {
  444        position: DisplayPoint,
  445        reset: bool,
  446        goal_column: u32,
  447    },
  448    Extend {
  449        position: DisplayPoint,
  450        click_count: usize,
  451    },
  452    Update {
  453        position: DisplayPoint,
  454        goal_column: u32,
  455        scroll_delta: gpui::Point<f32>,
  456    },
  457    End,
  458}
  459
  460#[derive(Clone, Debug)]
  461pub enum SelectMode {
  462    Character,
  463    Word(Range<Anchor>),
  464    Line(Range<Anchor>),
  465    All,
  466}
  467
  468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  469pub enum EditorMode {
  470    SingleLine {
  471        auto_width: bool,
  472    },
  473    AutoHeight {
  474        max_lines: usize,
  475    },
  476    Full {
  477        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  478        scale_ui_elements_with_buffer_font_size: bool,
  479        /// When set to `true`, the editor will render a background for the active line.
  480        show_active_line_background: bool,
  481        /// When set to `true`, the editor's height will be determined by its content.
  482        sized_by_content: bool,
  483    },
  484}
  485
  486impl EditorMode {
  487    pub fn full() -> Self {
  488        Self::Full {
  489            scale_ui_elements_with_buffer_font_size: true,
  490            show_active_line_background: true,
  491            sized_by_content: false,
  492        }
  493    }
  494
  495    pub fn is_full(&self) -> bool {
  496        matches!(self, Self::Full { .. })
  497    }
  498}
  499
  500#[derive(Copy, Clone, Debug)]
  501pub enum SoftWrap {
  502    /// Prefer not to wrap at all.
  503    ///
  504    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  505    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  506    GitDiff,
  507    /// Prefer a single line generally, unless an overly long line is encountered.
  508    None,
  509    /// Soft wrap lines that exceed the editor width.
  510    EditorWidth,
  511    /// Soft wrap lines at the preferred line length.
  512    Column(u32),
  513    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  514    Bounded(u32),
  515}
  516
  517#[derive(Clone)]
  518pub struct EditorStyle {
  519    pub background: Hsla,
  520    pub horizontal_padding: Pixels,
  521    pub local_player: PlayerColor,
  522    pub text: TextStyle,
  523    pub scrollbar_width: Pixels,
  524    pub syntax: Arc<SyntaxTheme>,
  525    pub status: StatusColors,
  526    pub inlay_hints_style: HighlightStyle,
  527    pub inline_completion_styles: InlineCompletionStyles,
  528    pub unnecessary_code_fade: f32,
  529}
  530
  531impl Default for EditorStyle {
  532    fn default() -> Self {
  533        Self {
  534            background: Hsla::default(),
  535            horizontal_padding: Pixels::default(),
  536            local_player: PlayerColor::default(),
  537            text: TextStyle::default(),
  538            scrollbar_width: Pixels::default(),
  539            syntax: Default::default(),
  540            // HACK: Status colors don't have a real default.
  541            // We should look into removing the status colors from the editor
  542            // style and retrieve them directly from the theme.
  543            status: StatusColors::dark(),
  544            inlay_hints_style: HighlightStyle::default(),
  545            inline_completion_styles: InlineCompletionStyles {
  546                insertion: HighlightStyle::default(),
  547                whitespace: HighlightStyle::default(),
  548            },
  549            unnecessary_code_fade: Default::default(),
  550        }
  551    }
  552}
  553
  554pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  555    let show_background = language_settings::language_settings(None, None, cx)
  556        .inlay_hints
  557        .show_background;
  558
  559    HighlightStyle {
  560        color: Some(cx.theme().status().hint),
  561        background_color: show_background.then(|| cx.theme().status().hint_background),
  562        ..HighlightStyle::default()
  563    }
  564}
  565
  566pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  567    InlineCompletionStyles {
  568        insertion: HighlightStyle {
  569            color: Some(cx.theme().status().predictive),
  570            ..HighlightStyle::default()
  571        },
  572        whitespace: HighlightStyle {
  573            background_color: Some(cx.theme().status().created_background),
  574            ..HighlightStyle::default()
  575        },
  576    }
  577}
  578
  579type CompletionId = usize;
  580
  581pub(crate) enum EditDisplayMode {
  582    TabAccept,
  583    DiffPopover,
  584    Inline,
  585}
  586
  587enum InlineCompletion {
  588    Edit {
  589        edits: Vec<(Range<Anchor>, String)>,
  590        edit_preview: Option<EditPreview>,
  591        display_mode: EditDisplayMode,
  592        snapshot: BufferSnapshot,
  593    },
  594    Move {
  595        target: Anchor,
  596        snapshot: BufferSnapshot,
  597    },
  598}
  599
  600struct InlineCompletionState {
  601    inlay_ids: Vec<InlayId>,
  602    completion: InlineCompletion,
  603    completion_id: Option<SharedString>,
  604    invalidation_range: Range<Anchor>,
  605}
  606
  607enum EditPredictionSettings {
  608    Disabled,
  609    Enabled {
  610        show_in_menu: bool,
  611        preview_requires_modifier: bool,
  612    },
  613}
  614
  615enum InlineCompletionHighlight {}
  616
  617#[derive(Debug, Clone)]
  618struct InlineDiagnostic {
  619    message: SharedString,
  620    group_id: usize,
  621    is_primary: bool,
  622    start: Point,
  623    severity: DiagnosticSeverity,
  624}
  625
  626pub enum MenuInlineCompletionsPolicy {
  627    Never,
  628    ByProvider,
  629}
  630
  631pub enum EditPredictionPreview {
  632    /// Modifier is not pressed
  633    Inactive { released_too_fast: bool },
  634    /// Modifier pressed
  635    Active {
  636        since: Instant,
  637        previous_scroll_position: Option<ScrollAnchor>,
  638    },
  639}
  640
  641impl EditPredictionPreview {
  642    pub fn released_too_fast(&self) -> bool {
  643        match self {
  644            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  645            EditPredictionPreview::Active { .. } => false,
  646        }
  647    }
  648
  649    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  650        if let EditPredictionPreview::Active {
  651            previous_scroll_position,
  652            ..
  653        } = self
  654        {
  655            *previous_scroll_position = scroll_position;
  656        }
  657    }
  658}
  659
  660pub struct ContextMenuOptions {
  661    pub min_entries_visible: usize,
  662    pub max_entries_visible: usize,
  663    pub placement: Option<ContextMenuPlacement>,
  664}
  665
  666#[derive(Debug, Clone, PartialEq, Eq)]
  667pub enum ContextMenuPlacement {
  668    Above,
  669    Below,
  670}
  671
  672#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  673struct EditorActionId(usize);
  674
  675impl EditorActionId {
  676    pub fn post_inc(&mut self) -> Self {
  677        let answer = self.0;
  678
  679        *self = Self(answer + 1);
  680
  681        Self(answer)
  682    }
  683}
  684
  685// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  686// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  687
  688type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  689type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  690
  691#[derive(Default)]
  692struct ScrollbarMarkerState {
  693    scrollbar_size: Size<Pixels>,
  694    dirty: bool,
  695    markers: Arc<[PaintQuad]>,
  696    pending_refresh: Option<Task<Result<()>>>,
  697}
  698
  699impl ScrollbarMarkerState {
  700    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  701        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  702    }
  703}
  704
  705#[derive(Clone, Debug)]
  706struct RunnableTasks {
  707    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  708    offset: multi_buffer::Anchor,
  709    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  710    column: u32,
  711    // Values of all named captures, including those starting with '_'
  712    extra_variables: HashMap<String, String>,
  713    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  714    context_range: Range<BufferOffset>,
  715}
  716
  717impl RunnableTasks {
  718    fn resolve<'a>(
  719        &'a self,
  720        cx: &'a task::TaskContext,
  721    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  722        self.templates.iter().filter_map(|(kind, template)| {
  723            template
  724                .resolve_task(&kind.to_id_base(), cx)
  725                .map(|task| (kind.clone(), task))
  726        })
  727    }
  728}
  729
  730#[derive(Clone)]
  731struct ResolvedTasks {
  732    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  733    position: Anchor,
  734}
  735
  736#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  737struct BufferOffset(usize);
  738
  739// Addons allow storing per-editor state in other crates (e.g. Vim)
  740pub trait Addon: 'static {
  741    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  742
  743    fn render_buffer_header_controls(
  744        &self,
  745        _: &ExcerptInfo,
  746        _: &Window,
  747        _: &App,
  748    ) -> Option<AnyElement> {
  749        None
  750    }
  751
  752    fn to_any(&self) -> &dyn std::any::Any;
  753
  754    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  755        None
  756    }
  757}
  758
  759/// A set of caret positions, registered when the editor was edited.
  760pub struct ChangeList {
  761    changes: Vec<Vec<Anchor>>,
  762    /// Currently "selected" change.
  763    position: Option<usize>,
  764}
  765
  766impl ChangeList {
  767    pub fn new() -> Self {
  768        Self {
  769            changes: Vec::new(),
  770            position: None,
  771        }
  772    }
  773
  774    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  775    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  776    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  777        if self.changes.is_empty() {
  778            return None;
  779        }
  780
  781        let prev = self.position.unwrap_or(self.changes.len());
  782        let next = if direction == Direction::Prev {
  783            prev.saturating_sub(count)
  784        } else {
  785            (prev + count).min(self.changes.len() - 1)
  786        };
  787        self.position = Some(next);
  788        self.changes.get(next).map(|anchors| anchors.as_slice())
  789    }
  790
  791    /// Adds a new change to the list, resetting the change list position.
  792    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  793        self.position.take();
  794        if pop_state {
  795            self.changes.pop();
  796        }
  797        self.changes.push(new_positions.clone());
  798    }
  799
  800    pub fn last(&self) -> Option<&[Anchor]> {
  801        self.changes.last().map(|anchors| anchors.as_slice())
  802    }
  803}
  804
  805#[derive(Clone)]
  806struct InlineBlamePopoverState {
  807    scroll_handle: ScrollHandle,
  808    commit_message: Option<ParsedCommitMessage>,
  809    markdown: Entity<Markdown>,
  810}
  811
  812struct InlineBlamePopover {
  813    position: gpui::Point<Pixels>,
  814    show_task: Option<Task<()>>,
  815    hide_task: Option<Task<()>>,
  816    popover_bounds: Option<Bounds<Pixels>>,
  817    popover_state: InlineBlamePopoverState,
  818}
  819
  820/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  821/// a breakpoint on them.
  822#[derive(Clone, Copy, Debug)]
  823struct PhantomBreakpointIndicator {
  824    display_row: DisplayRow,
  825    /// There's a small debounce between hovering over the line and showing the indicator.
  826    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  827    is_active: bool,
  828    collides_with_existing_breakpoint: bool,
  829}
  830/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  831///
  832/// See the [module level documentation](self) for more information.
  833pub struct Editor {
  834    focus_handle: FocusHandle,
  835    last_focused_descendant: Option<WeakFocusHandle>,
  836    /// The text buffer being edited
  837    buffer: Entity<MultiBuffer>,
  838    /// Map of how text in the buffer should be displayed.
  839    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  840    pub display_map: Entity<DisplayMap>,
  841    pub selections: SelectionsCollection,
  842    pub scroll_manager: ScrollManager,
  843    /// When inline assist editors are linked, they all render cursors because
  844    /// typing enters text into each of them, even the ones that aren't focused.
  845    pub(crate) show_cursor_when_unfocused: bool,
  846    columnar_selection_tail: Option<Anchor>,
  847    add_selections_state: Option<AddSelectionsState>,
  848    select_next_state: Option<SelectNextState>,
  849    select_prev_state: Option<SelectNextState>,
  850    selection_history: SelectionHistory,
  851    autoclose_regions: Vec<AutocloseRegion>,
  852    snippet_stack: InvalidationStack<SnippetState>,
  853    select_syntax_node_history: SelectSyntaxNodeHistory,
  854    ime_transaction: Option<TransactionId>,
  855    active_diagnostics: ActiveDiagnostic,
  856    show_inline_diagnostics: bool,
  857    inline_diagnostics_update: Task<()>,
  858    inline_diagnostics_enabled: bool,
  859    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  860    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  861    hard_wrap: Option<usize>,
  862
  863    // TODO: make this a access method
  864    pub project: Option<Entity<Project>>,
  865    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  866    completion_provider: Option<Box<dyn CompletionProvider>>,
  867    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  868    blink_manager: Entity<BlinkManager>,
  869    show_cursor_names: bool,
  870    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  871    pub show_local_selections: bool,
  872    mode: EditorMode,
  873    show_breadcrumbs: bool,
  874    show_gutter: bool,
  875    show_scrollbars: bool,
  876    disable_expand_excerpt_buttons: bool,
  877    show_line_numbers: Option<bool>,
  878    use_relative_line_numbers: Option<bool>,
  879    show_git_diff_gutter: Option<bool>,
  880    show_code_actions: Option<bool>,
  881    show_runnables: Option<bool>,
  882    show_breakpoints: Option<bool>,
  883    show_wrap_guides: Option<bool>,
  884    show_indent_guides: Option<bool>,
  885    placeholder_text: Option<Arc<str>>,
  886    highlight_order: usize,
  887    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  888    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  889    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  890    scrollbar_marker_state: ScrollbarMarkerState,
  891    active_indent_guides_state: ActiveIndentGuidesState,
  892    nav_history: Option<ItemNavHistory>,
  893    context_menu: RefCell<Option<CodeContextMenu>>,
  894    context_menu_options: Option<ContextMenuOptions>,
  895    mouse_context_menu: Option<MouseContextMenu>,
  896    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  897    inline_blame_popover: Option<InlineBlamePopover>,
  898    signature_help_state: SignatureHelpState,
  899    auto_signature_help: Option<bool>,
  900    find_all_references_task_sources: Vec<Anchor>,
  901    next_completion_id: CompletionId,
  902    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  903    code_actions_task: Option<Task<Result<()>>>,
  904    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  905    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  906    document_highlights_task: Option<Task<()>>,
  907    linked_editing_range_task: Option<Task<Option<()>>>,
  908    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  909    pending_rename: Option<RenameState>,
  910    searchable: bool,
  911    cursor_shape: CursorShape,
  912    current_line_highlight: Option<CurrentLineHighlight>,
  913    collapse_matches: bool,
  914    autoindent_mode: Option<AutoindentMode>,
  915    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  916    input_enabled: bool,
  917    use_modal_editing: bool,
  918    read_only: bool,
  919    leader_id: Option<CollaboratorId>,
  920    remote_id: Option<ViewId>,
  921    pub hover_state: HoverState,
  922    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  923    gutter_hovered: bool,
  924    hovered_link_state: Option<HoveredLinkState>,
  925    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  926    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  927    active_inline_completion: Option<InlineCompletionState>,
  928    /// Used to prevent flickering as the user types while the menu is open
  929    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  930    edit_prediction_settings: EditPredictionSettings,
  931    inline_completions_hidden_for_vim_mode: bool,
  932    show_inline_completions_override: Option<bool>,
  933    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  934    edit_prediction_preview: EditPredictionPreview,
  935    edit_prediction_indent_conflict: bool,
  936    edit_prediction_requires_modifier_in_indent_conflict: bool,
  937    inlay_hint_cache: InlayHintCache,
  938    next_inlay_id: usize,
  939    _subscriptions: Vec<Subscription>,
  940    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  941    gutter_dimensions: GutterDimensions,
  942    style: Option<EditorStyle>,
  943    text_style_refinement: Option<TextStyleRefinement>,
  944    next_editor_action_id: EditorActionId,
  945    editor_actions:
  946        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  947    use_autoclose: bool,
  948    use_auto_surround: bool,
  949    auto_replace_emoji_shortcode: bool,
  950    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  951    show_git_blame_gutter: bool,
  952    show_git_blame_inline: bool,
  953    show_git_blame_inline_delay_task: Option<Task<()>>,
  954    git_blame_inline_enabled: bool,
  955    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  956    serialize_dirty_buffers: bool,
  957    show_selection_menu: Option<bool>,
  958    blame: Option<Entity<GitBlame>>,
  959    blame_subscription: Option<Subscription>,
  960    custom_context_menu: Option<
  961        Box<
  962            dyn 'static
  963                + Fn(
  964                    &mut Self,
  965                    DisplayPoint,
  966                    &mut Window,
  967                    &mut Context<Self>,
  968                ) -> Option<Entity<ui::ContextMenu>>,
  969        >,
  970    >,
  971    last_bounds: Option<Bounds<Pixels>>,
  972    last_position_map: Option<Rc<PositionMap>>,
  973    expect_bounds_change: Option<Bounds<Pixels>>,
  974    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  975    tasks_update_task: Option<Task<()>>,
  976    breakpoint_store: Option<Entity<BreakpointStore>>,
  977    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
  978    in_project_search: bool,
  979    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  980    breadcrumb_header: Option<String>,
  981    focused_block: Option<FocusedBlock>,
  982    next_scroll_position: NextScrollCursorCenterTopBottom,
  983    addons: HashMap<TypeId, Box<dyn Addon>>,
  984    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  985    load_diff_task: Option<Shared<Task<()>>>,
  986    /// Whether we are temporarily displaying a diff other than git's
  987    temporary_diff_override: bool,
  988    selection_mark_mode: bool,
  989    toggle_fold_multiple_buffers: Task<()>,
  990    _scroll_cursor_center_top_bottom_task: Task<()>,
  991    serialize_selections: Task<()>,
  992    serialize_folds: Task<()>,
  993    mouse_cursor_hidden: bool,
  994    hide_mouse_mode: HideMouseMode,
  995    pub change_list: ChangeList,
  996    inline_value_cache: InlineValueCache,
  997}
  998
  999#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
 1000enum NextScrollCursorCenterTopBottom {
 1001    #[default]
 1002    Center,
 1003    Top,
 1004    Bottom,
 1005}
 1006
 1007impl NextScrollCursorCenterTopBottom {
 1008    fn next(&self) -> Self {
 1009        match self {
 1010            Self::Center => Self::Top,
 1011            Self::Top => Self::Bottom,
 1012            Self::Bottom => Self::Center,
 1013        }
 1014    }
 1015}
 1016
 1017#[derive(Clone)]
 1018pub struct EditorSnapshot {
 1019    pub mode: EditorMode,
 1020    show_gutter: bool,
 1021    show_line_numbers: Option<bool>,
 1022    show_git_diff_gutter: Option<bool>,
 1023    show_code_actions: Option<bool>,
 1024    show_runnables: Option<bool>,
 1025    show_breakpoints: Option<bool>,
 1026    git_blame_gutter_max_author_length: Option<usize>,
 1027    pub display_snapshot: DisplaySnapshot,
 1028    pub placeholder_text: Option<Arc<str>>,
 1029    is_focused: bool,
 1030    scroll_anchor: ScrollAnchor,
 1031    ongoing_scroll: OngoingScroll,
 1032    current_line_highlight: CurrentLineHighlight,
 1033    gutter_hovered: bool,
 1034}
 1035
 1036#[derive(Default, Debug, Clone, Copy)]
 1037pub struct GutterDimensions {
 1038    pub left_padding: Pixels,
 1039    pub right_padding: Pixels,
 1040    pub width: Pixels,
 1041    pub margin: Pixels,
 1042    pub git_blame_entries_width: Option<Pixels>,
 1043}
 1044
 1045impl GutterDimensions {
 1046    /// The full width of the space taken up by the gutter.
 1047    pub fn full_width(&self) -> Pixels {
 1048        self.margin + self.width
 1049    }
 1050
 1051    /// The width of the space reserved for the fold indicators,
 1052    /// use alongside 'justify_end' and `gutter_width` to
 1053    /// right align content with the line numbers
 1054    pub fn fold_area_width(&self) -> Pixels {
 1055        self.margin + self.right_padding
 1056    }
 1057}
 1058
 1059#[derive(Debug)]
 1060pub struct RemoteSelection {
 1061    pub replica_id: ReplicaId,
 1062    pub selection: Selection<Anchor>,
 1063    pub cursor_shape: CursorShape,
 1064    pub collaborator_id: CollaboratorId,
 1065    pub line_mode: bool,
 1066    pub user_name: Option<SharedString>,
 1067    pub color: PlayerColor,
 1068}
 1069
 1070#[derive(Clone, Debug)]
 1071struct SelectionHistoryEntry {
 1072    selections: Arc<[Selection<Anchor>]>,
 1073    select_next_state: Option<SelectNextState>,
 1074    select_prev_state: Option<SelectNextState>,
 1075    add_selections_state: Option<AddSelectionsState>,
 1076}
 1077
 1078enum SelectionHistoryMode {
 1079    Normal,
 1080    Undoing,
 1081    Redoing,
 1082}
 1083
 1084#[derive(Clone, PartialEq, Eq, Hash)]
 1085struct HoveredCursor {
 1086    replica_id: u16,
 1087    selection_id: usize,
 1088}
 1089
 1090impl Default for SelectionHistoryMode {
 1091    fn default() -> Self {
 1092        Self::Normal
 1093    }
 1094}
 1095
 1096#[derive(Default)]
 1097struct SelectionHistory {
 1098    #[allow(clippy::type_complexity)]
 1099    selections_by_transaction:
 1100        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1101    mode: SelectionHistoryMode,
 1102    undo_stack: VecDeque<SelectionHistoryEntry>,
 1103    redo_stack: VecDeque<SelectionHistoryEntry>,
 1104}
 1105
 1106impl SelectionHistory {
 1107    fn insert_transaction(
 1108        &mut self,
 1109        transaction_id: TransactionId,
 1110        selections: Arc<[Selection<Anchor>]>,
 1111    ) {
 1112        self.selections_by_transaction
 1113            .insert(transaction_id, (selections, None));
 1114    }
 1115
 1116    #[allow(clippy::type_complexity)]
 1117    fn transaction(
 1118        &self,
 1119        transaction_id: TransactionId,
 1120    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1121        self.selections_by_transaction.get(&transaction_id)
 1122    }
 1123
 1124    #[allow(clippy::type_complexity)]
 1125    fn transaction_mut(
 1126        &mut self,
 1127        transaction_id: TransactionId,
 1128    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1129        self.selections_by_transaction.get_mut(&transaction_id)
 1130    }
 1131
 1132    fn push(&mut self, entry: SelectionHistoryEntry) {
 1133        if !entry.selections.is_empty() {
 1134            match self.mode {
 1135                SelectionHistoryMode::Normal => {
 1136                    self.push_undo(entry);
 1137                    self.redo_stack.clear();
 1138                }
 1139                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1140                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1141            }
 1142        }
 1143    }
 1144
 1145    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1146        if self
 1147            .undo_stack
 1148            .back()
 1149            .map_or(true, |e| e.selections != entry.selections)
 1150        {
 1151            self.undo_stack.push_back(entry);
 1152            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1153                self.undo_stack.pop_front();
 1154            }
 1155        }
 1156    }
 1157
 1158    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1159        if self
 1160            .redo_stack
 1161            .back()
 1162            .map_or(true, |e| e.selections != entry.selections)
 1163        {
 1164            self.redo_stack.push_back(entry);
 1165            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1166                self.redo_stack.pop_front();
 1167            }
 1168        }
 1169    }
 1170}
 1171
 1172#[derive(Clone, Copy)]
 1173pub struct RowHighlightOptions {
 1174    pub autoscroll: bool,
 1175    pub include_gutter: bool,
 1176}
 1177
 1178impl Default for RowHighlightOptions {
 1179    fn default() -> Self {
 1180        Self {
 1181            autoscroll: Default::default(),
 1182            include_gutter: true,
 1183        }
 1184    }
 1185}
 1186
 1187struct RowHighlight {
 1188    index: usize,
 1189    range: Range<Anchor>,
 1190    color: Hsla,
 1191    options: RowHighlightOptions,
 1192    type_id: TypeId,
 1193}
 1194
 1195#[derive(Clone, Debug)]
 1196struct AddSelectionsState {
 1197    above: bool,
 1198    stack: Vec<usize>,
 1199}
 1200
 1201#[derive(Clone)]
 1202struct SelectNextState {
 1203    query: AhoCorasick,
 1204    wordwise: bool,
 1205    done: bool,
 1206}
 1207
 1208impl std::fmt::Debug for SelectNextState {
 1209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1210        f.debug_struct(std::any::type_name::<Self>())
 1211            .field("wordwise", &self.wordwise)
 1212            .field("done", &self.done)
 1213            .finish()
 1214    }
 1215}
 1216
 1217#[derive(Debug)]
 1218struct AutocloseRegion {
 1219    selection_id: usize,
 1220    range: Range<Anchor>,
 1221    pair: BracketPair,
 1222}
 1223
 1224#[derive(Debug)]
 1225struct SnippetState {
 1226    ranges: Vec<Vec<Range<Anchor>>>,
 1227    active_index: usize,
 1228    choices: Vec<Option<Vec<String>>>,
 1229}
 1230
 1231#[doc(hidden)]
 1232pub struct RenameState {
 1233    pub range: Range<Anchor>,
 1234    pub old_name: Arc<str>,
 1235    pub editor: Entity<Editor>,
 1236    block_id: CustomBlockId,
 1237}
 1238
 1239struct InvalidationStack<T>(Vec<T>);
 1240
 1241struct RegisteredInlineCompletionProvider {
 1242    provider: Arc<dyn InlineCompletionProviderHandle>,
 1243    _subscription: Subscription,
 1244}
 1245
 1246#[derive(Debug, PartialEq, Eq)]
 1247pub struct ActiveDiagnosticGroup {
 1248    pub active_range: Range<Anchor>,
 1249    pub active_message: String,
 1250    pub group_id: usize,
 1251    pub blocks: HashSet<CustomBlockId>,
 1252}
 1253
 1254#[derive(Debug, PartialEq, Eq)]
 1255#[allow(clippy::large_enum_variant)]
 1256pub(crate) enum ActiveDiagnostic {
 1257    None,
 1258    All,
 1259    Group(ActiveDiagnosticGroup),
 1260}
 1261
 1262#[derive(Serialize, Deserialize, Clone, Debug)]
 1263pub struct ClipboardSelection {
 1264    /// The number of bytes in this selection.
 1265    pub len: usize,
 1266    /// Whether this was a full-line selection.
 1267    pub is_entire_line: bool,
 1268    /// The indentation of the first line when this content was originally copied.
 1269    pub first_line_indent: u32,
 1270}
 1271
 1272// selections, scroll behavior, was newest selection reversed
 1273type SelectSyntaxNodeHistoryState = (
 1274    Box<[Selection<usize>]>,
 1275    SelectSyntaxNodeScrollBehavior,
 1276    bool,
 1277);
 1278
 1279#[derive(Default)]
 1280struct SelectSyntaxNodeHistory {
 1281    stack: Vec<SelectSyntaxNodeHistoryState>,
 1282    // disable temporarily to allow changing selections without losing the stack
 1283    pub disable_clearing: bool,
 1284}
 1285
 1286impl SelectSyntaxNodeHistory {
 1287    pub fn try_clear(&mut self) {
 1288        if !self.disable_clearing {
 1289            self.stack.clear();
 1290        }
 1291    }
 1292
 1293    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1294        self.stack.push(selection);
 1295    }
 1296
 1297    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1298        self.stack.pop()
 1299    }
 1300}
 1301
 1302enum SelectSyntaxNodeScrollBehavior {
 1303    CursorTop,
 1304    FitSelection,
 1305    CursorBottom,
 1306}
 1307
 1308#[derive(Debug)]
 1309pub(crate) struct NavigationData {
 1310    cursor_anchor: Anchor,
 1311    cursor_position: Point,
 1312    scroll_anchor: ScrollAnchor,
 1313    scroll_top_row: u32,
 1314}
 1315
 1316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1317pub enum GotoDefinitionKind {
 1318    Symbol,
 1319    Declaration,
 1320    Type,
 1321    Implementation,
 1322}
 1323
 1324#[derive(Debug, Clone)]
 1325enum InlayHintRefreshReason {
 1326    ModifiersChanged(bool),
 1327    Toggle(bool),
 1328    SettingsChange(InlayHintSettings),
 1329    NewLinesShown,
 1330    BufferEdited(HashSet<Arc<Language>>),
 1331    RefreshRequested,
 1332    ExcerptsRemoved(Vec<ExcerptId>),
 1333}
 1334
 1335impl InlayHintRefreshReason {
 1336    fn description(&self) -> &'static str {
 1337        match self {
 1338            Self::ModifiersChanged(_) => "modifiers changed",
 1339            Self::Toggle(_) => "toggle",
 1340            Self::SettingsChange(_) => "settings change",
 1341            Self::NewLinesShown => "new lines shown",
 1342            Self::BufferEdited(_) => "buffer edited",
 1343            Self::RefreshRequested => "refresh requested",
 1344            Self::ExcerptsRemoved(_) => "excerpts removed",
 1345        }
 1346    }
 1347}
 1348
 1349pub enum FormatTarget {
 1350    Buffers,
 1351    Ranges(Vec<Range<MultiBufferPoint>>),
 1352}
 1353
 1354pub(crate) struct FocusedBlock {
 1355    id: BlockId,
 1356    focus_handle: WeakFocusHandle,
 1357}
 1358
 1359#[derive(Clone)]
 1360enum JumpData {
 1361    MultiBufferRow {
 1362        row: MultiBufferRow,
 1363        line_offset_from_top: u32,
 1364    },
 1365    MultiBufferPoint {
 1366        excerpt_id: ExcerptId,
 1367        position: Point,
 1368        anchor: text::Anchor,
 1369        line_offset_from_top: u32,
 1370    },
 1371}
 1372
 1373pub enum MultibufferSelectionMode {
 1374    First,
 1375    All,
 1376}
 1377
 1378#[derive(Clone, Copy, Debug, Default)]
 1379pub struct RewrapOptions {
 1380    pub override_language_settings: bool,
 1381    pub preserve_existing_whitespace: bool,
 1382}
 1383
 1384impl Editor {
 1385    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1386        let buffer = cx.new(|cx| Buffer::local("", cx));
 1387        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1388        Self::new(
 1389            EditorMode::SingleLine { auto_width: false },
 1390            buffer,
 1391            None,
 1392            window,
 1393            cx,
 1394        )
 1395    }
 1396
 1397    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1398        let buffer = cx.new(|cx| Buffer::local("", cx));
 1399        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1400        Self::new(EditorMode::full(), buffer, None, window, cx)
 1401    }
 1402
 1403    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1404        let buffer = cx.new(|cx| Buffer::local("", cx));
 1405        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1406        Self::new(
 1407            EditorMode::SingleLine { auto_width: true },
 1408            buffer,
 1409            None,
 1410            window,
 1411            cx,
 1412        )
 1413    }
 1414
 1415    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1416        let buffer = cx.new(|cx| Buffer::local("", cx));
 1417        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1418        Self::new(
 1419            EditorMode::AutoHeight { max_lines },
 1420            buffer,
 1421            None,
 1422            window,
 1423            cx,
 1424        )
 1425    }
 1426
 1427    pub fn for_buffer(
 1428        buffer: Entity<Buffer>,
 1429        project: Option<Entity<Project>>,
 1430        window: &mut Window,
 1431        cx: &mut Context<Self>,
 1432    ) -> Self {
 1433        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1434        Self::new(EditorMode::full(), buffer, project, window, cx)
 1435    }
 1436
 1437    pub fn for_multibuffer(
 1438        buffer: Entity<MultiBuffer>,
 1439        project: Option<Entity<Project>>,
 1440        window: &mut Window,
 1441        cx: &mut Context<Self>,
 1442    ) -> Self {
 1443        Self::new(EditorMode::full(), buffer, project, window, cx)
 1444    }
 1445
 1446    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1447        let mut clone = Self::new(
 1448            self.mode,
 1449            self.buffer.clone(),
 1450            self.project.clone(),
 1451            window,
 1452            cx,
 1453        );
 1454        self.display_map.update(cx, |display_map, cx| {
 1455            let snapshot = display_map.snapshot(cx);
 1456            clone.display_map.update(cx, |display_map, cx| {
 1457                display_map.set_state(&snapshot, cx);
 1458            });
 1459        });
 1460        clone.folds_did_change(cx);
 1461        clone.selections.clone_state(&self.selections);
 1462        clone.scroll_manager.clone_state(&self.scroll_manager);
 1463        clone.searchable = self.searchable;
 1464        clone.read_only = self.read_only;
 1465        clone
 1466    }
 1467
 1468    pub fn new(
 1469        mode: EditorMode,
 1470        buffer: Entity<MultiBuffer>,
 1471        project: Option<Entity<Project>>,
 1472        window: &mut Window,
 1473        cx: &mut Context<Self>,
 1474    ) -> Self {
 1475        let style = window.text_style();
 1476        let font_size = style.font_size.to_pixels(window.rem_size());
 1477        let editor = cx.entity().downgrade();
 1478        let fold_placeholder = FoldPlaceholder {
 1479            constrain_width: true,
 1480            render: Arc::new(move |fold_id, fold_range, cx| {
 1481                let editor = editor.clone();
 1482                div()
 1483                    .id(fold_id)
 1484                    .bg(cx.theme().colors().ghost_element_background)
 1485                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1486                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1487                    .rounded_xs()
 1488                    .size_full()
 1489                    .cursor_pointer()
 1490                    .child("")
 1491                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1492                    .on_click(move |_, _window, cx| {
 1493                        editor
 1494                            .update(cx, |editor, cx| {
 1495                                editor.unfold_ranges(
 1496                                    &[fold_range.start..fold_range.end],
 1497                                    true,
 1498                                    false,
 1499                                    cx,
 1500                                );
 1501                                cx.stop_propagation();
 1502                            })
 1503                            .ok();
 1504                    })
 1505                    .into_any()
 1506            }),
 1507            merge_adjacent: true,
 1508            ..Default::default()
 1509        };
 1510        let display_map = cx.new(|cx| {
 1511            DisplayMap::new(
 1512                buffer.clone(),
 1513                style.font(),
 1514                font_size,
 1515                None,
 1516                FILE_HEADER_HEIGHT,
 1517                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1518                fold_placeholder,
 1519                cx,
 1520            )
 1521        });
 1522
 1523        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1524
 1525        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1526
 1527        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1528            .then(|| language_settings::SoftWrap::None);
 1529
 1530        let mut project_subscriptions = Vec::new();
 1531        if mode.is_full() {
 1532            if let Some(project) = project.as_ref() {
 1533                project_subscriptions.push(cx.subscribe_in(
 1534                    project,
 1535                    window,
 1536                    |editor, _, event, window, cx| match event {
 1537                        project::Event::RefreshCodeLens => {
 1538                            // we always query lens with actions, without storing them, always refreshing them
 1539                        }
 1540                        project::Event::RefreshInlayHints => {
 1541                            editor
 1542                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1543                        }
 1544                        project::Event::SnippetEdit(id, snippet_edits) => {
 1545                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1546                                let focus_handle = editor.focus_handle(cx);
 1547                                if focus_handle.is_focused(window) {
 1548                                    let snapshot = buffer.read(cx).snapshot();
 1549                                    for (range, snippet) in snippet_edits {
 1550                                        let editor_range =
 1551                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1552                                        editor
 1553                                            .insert_snippet(
 1554                                                &[editor_range],
 1555                                                snippet.clone(),
 1556                                                window,
 1557                                                cx,
 1558                                            )
 1559                                            .ok();
 1560                                    }
 1561                                }
 1562                            }
 1563                        }
 1564                        _ => {}
 1565                    },
 1566                ));
 1567                if let Some(task_inventory) = project
 1568                    .read(cx)
 1569                    .task_store()
 1570                    .read(cx)
 1571                    .task_inventory()
 1572                    .cloned()
 1573                {
 1574                    project_subscriptions.push(cx.observe_in(
 1575                        &task_inventory,
 1576                        window,
 1577                        |editor, _, window, cx| {
 1578                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1579                        },
 1580                    ));
 1581                };
 1582
 1583                project_subscriptions.push(cx.subscribe_in(
 1584                    &project.read(cx).breakpoint_store(),
 1585                    window,
 1586                    |editor, _, event, window, cx| match event {
 1587                        BreakpointStoreEvent::ClearDebugLines => {
 1588                            editor.clear_row_highlights::<ActiveDebugLine>();
 1589                            editor.refresh_inline_values(cx);
 1590                        }
 1591                        BreakpointStoreEvent::SetDebugLine => {
 1592                            if editor.go_to_active_debug_line(window, cx) {
 1593                                cx.stop_propagation();
 1594                            }
 1595
 1596                            editor.refresh_inline_values(cx);
 1597                        }
 1598                        _ => {}
 1599                    },
 1600                ));
 1601            }
 1602        }
 1603
 1604        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1605
 1606        let inlay_hint_settings =
 1607            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1608        let focus_handle = cx.focus_handle();
 1609        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1610            .detach();
 1611        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1612            .detach();
 1613        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1614            .detach();
 1615        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1616            .detach();
 1617
 1618        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1619            Some(false)
 1620        } else {
 1621            None
 1622        };
 1623
 1624        let breakpoint_store = match (mode, project.as_ref()) {
 1625            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1626            _ => None,
 1627        };
 1628
 1629        let mut code_action_providers = Vec::new();
 1630        let mut load_uncommitted_diff = None;
 1631        if let Some(project) = project.clone() {
 1632            load_uncommitted_diff = Some(
 1633                update_uncommitted_diff_for_buffer(
 1634                    cx.entity(),
 1635                    &project,
 1636                    buffer.read(cx).all_buffers(),
 1637                    buffer.clone(),
 1638                    cx,
 1639                )
 1640                .shared(),
 1641            );
 1642            code_action_providers.push(Rc::new(project) as Rc<_>);
 1643        }
 1644
 1645        let mut this = Self {
 1646            focus_handle,
 1647            show_cursor_when_unfocused: false,
 1648            last_focused_descendant: None,
 1649            buffer: buffer.clone(),
 1650            display_map: display_map.clone(),
 1651            selections,
 1652            scroll_manager: ScrollManager::new(cx),
 1653            columnar_selection_tail: None,
 1654            add_selections_state: None,
 1655            select_next_state: None,
 1656            select_prev_state: None,
 1657            selection_history: Default::default(),
 1658            autoclose_regions: Default::default(),
 1659            snippet_stack: Default::default(),
 1660            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1661            ime_transaction: Default::default(),
 1662            active_diagnostics: ActiveDiagnostic::None,
 1663            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1664            inline_diagnostics_update: Task::ready(()),
 1665            inline_diagnostics: Vec::new(),
 1666            soft_wrap_mode_override,
 1667            hard_wrap: None,
 1668            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1669            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1670            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1671            project,
 1672            blink_manager: blink_manager.clone(),
 1673            show_local_selections: true,
 1674            show_scrollbars: true,
 1675            mode,
 1676            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1677            show_gutter: mode.is_full(),
 1678            show_line_numbers: None,
 1679            use_relative_line_numbers: None,
 1680            disable_expand_excerpt_buttons: false,
 1681            show_git_diff_gutter: None,
 1682            show_code_actions: None,
 1683            show_runnables: None,
 1684            show_breakpoints: None,
 1685            show_wrap_guides: None,
 1686            show_indent_guides,
 1687            placeholder_text: None,
 1688            highlight_order: 0,
 1689            highlighted_rows: HashMap::default(),
 1690            background_highlights: Default::default(),
 1691            gutter_highlights: TreeMap::default(),
 1692            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1693            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1694            nav_history: None,
 1695            context_menu: RefCell::new(None),
 1696            context_menu_options: None,
 1697            mouse_context_menu: None,
 1698            completion_tasks: Default::default(),
 1699            inline_blame_popover: Default::default(),
 1700            signature_help_state: SignatureHelpState::default(),
 1701            auto_signature_help: None,
 1702            find_all_references_task_sources: Vec::new(),
 1703            next_completion_id: 0,
 1704            next_inlay_id: 0,
 1705            code_action_providers,
 1706            available_code_actions: Default::default(),
 1707            code_actions_task: Default::default(),
 1708            quick_selection_highlight_task: Default::default(),
 1709            debounced_selection_highlight_task: Default::default(),
 1710            document_highlights_task: Default::default(),
 1711            linked_editing_range_task: Default::default(),
 1712            pending_rename: Default::default(),
 1713            searchable: true,
 1714            cursor_shape: EditorSettings::get_global(cx)
 1715                .cursor_shape
 1716                .unwrap_or_default(),
 1717            current_line_highlight: None,
 1718            autoindent_mode: Some(AutoindentMode::EachLine),
 1719            collapse_matches: false,
 1720            workspace: None,
 1721            input_enabled: true,
 1722            use_modal_editing: mode.is_full(),
 1723            read_only: false,
 1724            use_autoclose: true,
 1725            use_auto_surround: true,
 1726            auto_replace_emoji_shortcode: false,
 1727            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1728            leader_id: None,
 1729            remote_id: None,
 1730            hover_state: Default::default(),
 1731            pending_mouse_down: None,
 1732            hovered_link_state: Default::default(),
 1733            edit_prediction_provider: None,
 1734            active_inline_completion: None,
 1735            stale_inline_completion_in_menu: None,
 1736            edit_prediction_preview: EditPredictionPreview::Inactive {
 1737                released_too_fast: false,
 1738            },
 1739            inline_diagnostics_enabled: mode.is_full(),
 1740            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1741            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1742
 1743            gutter_hovered: false,
 1744            pixel_position_of_newest_cursor: None,
 1745            last_bounds: None,
 1746            last_position_map: None,
 1747            expect_bounds_change: None,
 1748            gutter_dimensions: GutterDimensions::default(),
 1749            style: None,
 1750            show_cursor_names: false,
 1751            hovered_cursors: Default::default(),
 1752            next_editor_action_id: EditorActionId::default(),
 1753            editor_actions: Rc::default(),
 1754            inline_completions_hidden_for_vim_mode: false,
 1755            show_inline_completions_override: None,
 1756            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1757            edit_prediction_settings: EditPredictionSettings::Disabled,
 1758            edit_prediction_indent_conflict: false,
 1759            edit_prediction_requires_modifier_in_indent_conflict: true,
 1760            custom_context_menu: None,
 1761            show_git_blame_gutter: false,
 1762            show_git_blame_inline: false,
 1763            show_selection_menu: None,
 1764            show_git_blame_inline_delay_task: None,
 1765            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1766            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1767            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1768                .session
 1769                .restore_unsaved_buffers,
 1770            blame: None,
 1771            blame_subscription: None,
 1772            tasks: Default::default(),
 1773
 1774            breakpoint_store,
 1775            gutter_breakpoint_indicator: (None, None),
 1776            _subscriptions: vec![
 1777                cx.observe(&buffer, Self::on_buffer_changed),
 1778                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1779                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1780                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1781                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1782                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1783                cx.observe_window_activation(window, |editor, window, cx| {
 1784                    let active = window.is_window_active();
 1785                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1786                        if active {
 1787                            blink_manager.enable(cx);
 1788                        } else {
 1789                            blink_manager.disable(cx);
 1790                        }
 1791                    });
 1792                }),
 1793            ],
 1794            tasks_update_task: None,
 1795            linked_edit_ranges: Default::default(),
 1796            in_project_search: false,
 1797            previous_search_ranges: None,
 1798            breadcrumb_header: None,
 1799            focused_block: None,
 1800            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1801            addons: HashMap::default(),
 1802            registered_buffers: HashMap::default(),
 1803            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1804            selection_mark_mode: false,
 1805            toggle_fold_multiple_buffers: Task::ready(()),
 1806            serialize_selections: Task::ready(()),
 1807            serialize_folds: Task::ready(()),
 1808            text_style_refinement: None,
 1809            load_diff_task: load_uncommitted_diff,
 1810            temporary_diff_override: false,
 1811            mouse_cursor_hidden: false,
 1812            hide_mouse_mode: EditorSettings::get_global(cx)
 1813                .hide_mouse
 1814                .unwrap_or_default(),
 1815            change_list: ChangeList::new(),
 1816        };
 1817        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1818            this._subscriptions
 1819                .push(cx.observe(breakpoints, |_, _, cx| {
 1820                    cx.notify();
 1821                }));
 1822        }
 1823        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1824        this._subscriptions.extend(project_subscriptions);
 1825
 1826        this._subscriptions.push(cx.subscribe_in(
 1827            &cx.entity(),
 1828            window,
 1829            |editor, _, e: &EditorEvent, window, cx| match e {
 1830                EditorEvent::ScrollPositionChanged { local, .. } => {
 1831                    if *local {
 1832                        let new_anchor = editor.scroll_manager.anchor();
 1833                        let snapshot = editor.snapshot(window, cx);
 1834                        editor.update_restoration_data(cx, move |data| {
 1835                            data.scroll_position = (
 1836                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1837                                new_anchor.offset,
 1838                            );
 1839                        });
 1840                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1841                        editor.inline_blame_popover.take();
 1842                    }
 1843                }
 1844                EditorEvent::Edited { .. } => {
 1845                    if !vim_enabled(cx) {
 1846                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1847                        let pop_state = editor
 1848                            .change_list
 1849                            .last()
 1850                            .map(|previous| {
 1851                                previous.len() == selections.len()
 1852                                    && previous.iter().enumerate().all(|(ix, p)| {
 1853                                        p.to_display_point(&map).row()
 1854                                            == selections[ix].head().row()
 1855                                    })
 1856                            })
 1857                            .unwrap_or(false);
 1858                        let new_positions = selections
 1859                            .into_iter()
 1860                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1861                            .collect();
 1862                        editor
 1863                            .change_list
 1864                            .push_to_change_list(pop_state, new_positions);
 1865                    }
 1866                }
 1867                _ => (),
 1868            },
 1869        ));
 1870
 1871        if let Some(dap_store) = this
 1872            .project
 1873            .as_ref()
 1874            .map(|project| project.read(cx).dap_store())
 1875        {
 1876            let weak_editor = cx.weak_entity();
 1877
 1878            this._subscriptions
 1879                .push(
 1880                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1881                        let session_entity = cx.entity();
 1882                        weak_editor
 1883                            .update(cx, |editor, cx| {
 1884                                editor._subscriptions.push(
 1885                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1886                                );
 1887                            })
 1888                            .ok();
 1889                    }),
 1890                );
 1891
 1892            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1893                this._subscriptions
 1894                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1895            }
 1896        }
 1897
 1898        this.end_selection(window, cx);
 1899        this.scroll_manager.show_scrollbars(window, cx);
 1900        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1901
 1902        if mode.is_full() {
 1903            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1904            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1905
 1906            if this.git_blame_inline_enabled {
 1907                this.git_blame_inline_enabled = true;
 1908                this.start_git_blame_inline(false, window, cx);
 1909            }
 1910
 1911            this.go_to_active_debug_line(window, cx);
 1912
 1913            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1914                if let Some(project) = this.project.as_ref() {
 1915                    let handle = project.update(cx, |project, cx| {
 1916                        project.register_buffer_with_language_servers(&buffer, cx)
 1917                    });
 1918                    this.registered_buffers
 1919                        .insert(buffer.read(cx).remote_id(), handle);
 1920                }
 1921            }
 1922        }
 1923
 1924        this.report_editor_event("Editor Opened", None, cx);
 1925        this
 1926    }
 1927
 1928    pub fn deploy_mouse_context_menu(
 1929        &mut self,
 1930        position: gpui::Point<Pixels>,
 1931        context_menu: Entity<ContextMenu>,
 1932        window: &mut Window,
 1933        cx: &mut Context<Self>,
 1934    ) {
 1935        self.mouse_context_menu = Some(MouseContextMenu::new(
 1936            self,
 1937            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1938            context_menu,
 1939            window,
 1940            cx,
 1941        ));
 1942    }
 1943
 1944    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1945        self.mouse_context_menu
 1946            .as_ref()
 1947            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1948    }
 1949
 1950    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1951        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1952    }
 1953
 1954    fn key_context_internal(
 1955        &self,
 1956        has_active_edit_prediction: bool,
 1957        window: &Window,
 1958        cx: &App,
 1959    ) -> KeyContext {
 1960        let mut key_context = KeyContext::new_with_defaults();
 1961        key_context.add("Editor");
 1962        let mode = match self.mode {
 1963            EditorMode::SingleLine { .. } => "single_line",
 1964            EditorMode::AutoHeight { .. } => "auto_height",
 1965            EditorMode::Full { .. } => "full",
 1966        };
 1967
 1968        if EditorSettings::jupyter_enabled(cx) {
 1969            key_context.add("jupyter");
 1970        }
 1971
 1972        key_context.set("mode", mode);
 1973        if self.pending_rename.is_some() {
 1974            key_context.add("renaming");
 1975        }
 1976
 1977        match self.context_menu.borrow().as_ref() {
 1978            Some(CodeContextMenu::Completions(_)) => {
 1979                key_context.add("menu");
 1980                key_context.add("showing_completions");
 1981            }
 1982            Some(CodeContextMenu::CodeActions(_)) => {
 1983                key_context.add("menu");
 1984                key_context.add("showing_code_actions")
 1985            }
 1986            None => {}
 1987        }
 1988
 1989        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1990        if !self.focus_handle(cx).contains_focused(window, cx)
 1991            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1992        {
 1993            for addon in self.addons.values() {
 1994                addon.extend_key_context(&mut key_context, cx)
 1995            }
 1996        }
 1997
 1998        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1999            if let Some(extension) = singleton_buffer
 2000                .read(cx)
 2001                .file()
 2002                .and_then(|file| file.path().extension()?.to_str())
 2003            {
 2004                key_context.set("extension", extension.to_string());
 2005            }
 2006        } else {
 2007            key_context.add("multibuffer");
 2008        }
 2009
 2010        if has_active_edit_prediction {
 2011            if self.edit_prediction_in_conflict() {
 2012                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2013            } else {
 2014                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2015                key_context.add("copilot_suggestion");
 2016            }
 2017        }
 2018
 2019        if self.selection_mark_mode {
 2020            key_context.add("selection_mode");
 2021        }
 2022
 2023        key_context
 2024    }
 2025
 2026    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2027        self.mouse_cursor_hidden = match origin {
 2028            HideMouseCursorOrigin::TypingAction => {
 2029                matches!(
 2030                    self.hide_mouse_mode,
 2031                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2032                )
 2033            }
 2034            HideMouseCursorOrigin::MovementAction => {
 2035                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2036            }
 2037        };
 2038    }
 2039
 2040    pub fn edit_prediction_in_conflict(&self) -> bool {
 2041        if !self.show_edit_predictions_in_menu() {
 2042            return false;
 2043        }
 2044
 2045        let showing_completions = self
 2046            .context_menu
 2047            .borrow()
 2048            .as_ref()
 2049            .map_or(false, |context| {
 2050                matches!(context, CodeContextMenu::Completions(_))
 2051            });
 2052
 2053        showing_completions
 2054            || self.edit_prediction_requires_modifier()
 2055            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2056            // bindings to insert tab characters.
 2057            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2058    }
 2059
 2060    pub fn accept_edit_prediction_keybind(
 2061        &self,
 2062        window: &Window,
 2063        cx: &App,
 2064    ) -> AcceptEditPredictionBinding {
 2065        let key_context = self.key_context_internal(true, window, cx);
 2066        let in_conflict = self.edit_prediction_in_conflict();
 2067
 2068        AcceptEditPredictionBinding(
 2069            window
 2070                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2071                .into_iter()
 2072                .filter(|binding| {
 2073                    !in_conflict
 2074                        || binding
 2075                            .keystrokes()
 2076                            .first()
 2077                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2078                })
 2079                .rev()
 2080                .min_by_key(|binding| {
 2081                    binding
 2082                        .keystrokes()
 2083                        .first()
 2084                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2085                }),
 2086        )
 2087    }
 2088
 2089    pub fn new_file(
 2090        workspace: &mut Workspace,
 2091        _: &workspace::NewFile,
 2092        window: &mut Window,
 2093        cx: &mut Context<Workspace>,
 2094    ) {
 2095        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2096            "Failed to create buffer",
 2097            window,
 2098            cx,
 2099            |e, _, _| match e.error_code() {
 2100                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2101                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2102                e.error_tag("required").unwrap_or("the latest version")
 2103            )),
 2104                _ => None,
 2105            },
 2106        );
 2107    }
 2108
 2109    pub fn new_in_workspace(
 2110        workspace: &mut Workspace,
 2111        window: &mut Window,
 2112        cx: &mut Context<Workspace>,
 2113    ) -> Task<Result<Entity<Editor>>> {
 2114        let project = workspace.project().clone();
 2115        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2116
 2117        cx.spawn_in(window, async move |workspace, cx| {
 2118            let buffer = create.await?;
 2119            workspace.update_in(cx, |workspace, window, cx| {
 2120                let editor =
 2121                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2122                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2123                editor
 2124            })
 2125        })
 2126    }
 2127
 2128    fn new_file_vertical(
 2129        workspace: &mut Workspace,
 2130        _: &workspace::NewFileSplitVertical,
 2131        window: &mut Window,
 2132        cx: &mut Context<Workspace>,
 2133    ) {
 2134        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2135    }
 2136
 2137    fn new_file_horizontal(
 2138        workspace: &mut Workspace,
 2139        _: &workspace::NewFileSplitHorizontal,
 2140        window: &mut Window,
 2141        cx: &mut Context<Workspace>,
 2142    ) {
 2143        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2144    }
 2145
 2146    fn new_file_in_direction(
 2147        workspace: &mut Workspace,
 2148        direction: SplitDirection,
 2149        window: &mut Window,
 2150        cx: &mut Context<Workspace>,
 2151    ) {
 2152        let project = workspace.project().clone();
 2153        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2154
 2155        cx.spawn_in(window, async move |workspace, cx| {
 2156            let buffer = create.await?;
 2157            workspace.update_in(cx, move |workspace, window, cx| {
 2158                workspace.split_item(
 2159                    direction,
 2160                    Box::new(
 2161                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2162                    ),
 2163                    window,
 2164                    cx,
 2165                )
 2166            })?;
 2167            anyhow::Ok(())
 2168        })
 2169        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2170            match e.error_code() {
 2171                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2172                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2173                e.error_tag("required").unwrap_or("the latest version")
 2174            )),
 2175                _ => None,
 2176            }
 2177        });
 2178    }
 2179
 2180    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2181        self.leader_id
 2182    }
 2183
 2184    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2185        &self.buffer
 2186    }
 2187
 2188    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2189        self.workspace.as_ref()?.0.upgrade()
 2190    }
 2191
 2192    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2193        self.buffer().read(cx).title(cx)
 2194    }
 2195
 2196    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2197        let git_blame_gutter_max_author_length = self
 2198            .render_git_blame_gutter(cx)
 2199            .then(|| {
 2200                if let Some(blame) = self.blame.as_ref() {
 2201                    let max_author_length =
 2202                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2203                    Some(max_author_length)
 2204                } else {
 2205                    None
 2206                }
 2207            })
 2208            .flatten();
 2209
 2210        EditorSnapshot {
 2211            mode: self.mode,
 2212            show_gutter: self.show_gutter,
 2213            show_line_numbers: self.show_line_numbers,
 2214            show_git_diff_gutter: self.show_git_diff_gutter,
 2215            show_code_actions: self.show_code_actions,
 2216            show_runnables: self.show_runnables,
 2217            show_breakpoints: self.show_breakpoints,
 2218            git_blame_gutter_max_author_length,
 2219            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2220            scroll_anchor: self.scroll_manager.anchor(),
 2221            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2222            placeholder_text: self.placeholder_text.clone(),
 2223            is_focused: self.focus_handle.is_focused(window),
 2224            current_line_highlight: self
 2225                .current_line_highlight
 2226                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2227            gutter_hovered: self.gutter_hovered,
 2228        }
 2229    }
 2230
 2231    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2232        self.buffer.read(cx).language_at(point, cx)
 2233    }
 2234
 2235    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2236        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2237    }
 2238
 2239    pub fn active_excerpt(
 2240        &self,
 2241        cx: &App,
 2242    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2243        self.buffer
 2244            .read(cx)
 2245            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2246    }
 2247
 2248    pub fn mode(&self) -> EditorMode {
 2249        self.mode
 2250    }
 2251
 2252    pub fn set_mode(&mut self, mode: EditorMode) {
 2253        self.mode = mode;
 2254    }
 2255
 2256    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2257        self.collaboration_hub.as_deref()
 2258    }
 2259
 2260    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2261        self.collaboration_hub = Some(hub);
 2262    }
 2263
 2264    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2265        self.in_project_search = in_project_search;
 2266    }
 2267
 2268    pub fn set_custom_context_menu(
 2269        &mut self,
 2270        f: impl 'static
 2271        + Fn(
 2272            &mut Self,
 2273            DisplayPoint,
 2274            &mut Window,
 2275            &mut Context<Self>,
 2276        ) -> Option<Entity<ui::ContextMenu>>,
 2277    ) {
 2278        self.custom_context_menu = Some(Box::new(f))
 2279    }
 2280
 2281    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2282        self.completion_provider = provider;
 2283    }
 2284
 2285    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2286        self.semantics_provider.clone()
 2287    }
 2288
 2289    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2290        self.semantics_provider = provider;
 2291    }
 2292
 2293    pub fn set_edit_prediction_provider<T>(
 2294        &mut self,
 2295        provider: Option<Entity<T>>,
 2296        window: &mut Window,
 2297        cx: &mut Context<Self>,
 2298    ) where
 2299        T: EditPredictionProvider,
 2300    {
 2301        self.edit_prediction_provider =
 2302            provider.map(|provider| RegisteredInlineCompletionProvider {
 2303                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2304                    if this.focus_handle.is_focused(window) {
 2305                        this.update_visible_inline_completion(window, cx);
 2306                    }
 2307                }),
 2308                provider: Arc::new(provider),
 2309            });
 2310        self.update_edit_prediction_settings(cx);
 2311        self.refresh_inline_completion(false, false, window, cx);
 2312    }
 2313
 2314    pub fn placeholder_text(&self) -> Option<&str> {
 2315        self.placeholder_text.as_deref()
 2316    }
 2317
 2318    pub fn set_placeholder_text(
 2319        &mut self,
 2320        placeholder_text: impl Into<Arc<str>>,
 2321        cx: &mut Context<Self>,
 2322    ) {
 2323        let placeholder_text = Some(placeholder_text.into());
 2324        if self.placeholder_text != placeholder_text {
 2325            self.placeholder_text = placeholder_text;
 2326            cx.notify();
 2327        }
 2328    }
 2329
 2330    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2331        self.cursor_shape = cursor_shape;
 2332
 2333        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2334        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2335
 2336        cx.notify();
 2337    }
 2338
 2339    pub fn set_current_line_highlight(
 2340        &mut self,
 2341        current_line_highlight: Option<CurrentLineHighlight>,
 2342    ) {
 2343        self.current_line_highlight = current_line_highlight;
 2344    }
 2345
 2346    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2347        self.collapse_matches = collapse_matches;
 2348    }
 2349
 2350    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2351        let buffers = self.buffer.read(cx).all_buffers();
 2352        let Some(project) = self.project.as_ref() else {
 2353            return;
 2354        };
 2355        project.update(cx, |project, cx| {
 2356            for buffer in buffers {
 2357                self.registered_buffers
 2358                    .entry(buffer.read(cx).remote_id())
 2359                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2360            }
 2361        })
 2362    }
 2363
 2364    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2365        if self.collapse_matches {
 2366            return range.start..range.start;
 2367        }
 2368        range.clone()
 2369    }
 2370
 2371    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2372        if self.display_map.read(cx).clip_at_line_ends != clip {
 2373            self.display_map
 2374                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2375        }
 2376    }
 2377
 2378    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2379        self.input_enabled = input_enabled;
 2380    }
 2381
 2382    pub fn set_inline_completions_hidden_for_vim_mode(
 2383        &mut self,
 2384        hidden: bool,
 2385        window: &mut Window,
 2386        cx: &mut Context<Self>,
 2387    ) {
 2388        if hidden != self.inline_completions_hidden_for_vim_mode {
 2389            self.inline_completions_hidden_for_vim_mode = hidden;
 2390            if hidden {
 2391                self.update_visible_inline_completion(window, cx);
 2392            } else {
 2393                self.refresh_inline_completion(true, false, window, cx);
 2394            }
 2395        }
 2396    }
 2397
 2398    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2399        self.menu_inline_completions_policy = value;
 2400    }
 2401
 2402    pub fn set_autoindent(&mut self, autoindent: bool) {
 2403        if autoindent {
 2404            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2405        } else {
 2406            self.autoindent_mode = None;
 2407        }
 2408    }
 2409
 2410    pub fn read_only(&self, cx: &App) -> bool {
 2411        self.read_only || self.buffer.read(cx).read_only()
 2412    }
 2413
 2414    pub fn set_read_only(&mut self, read_only: bool) {
 2415        self.read_only = read_only;
 2416    }
 2417
 2418    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2419        self.use_autoclose = autoclose;
 2420    }
 2421
 2422    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2423        self.use_auto_surround = auto_surround;
 2424    }
 2425
 2426    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2427        self.auto_replace_emoji_shortcode = auto_replace;
 2428    }
 2429
 2430    pub fn toggle_edit_predictions(
 2431        &mut self,
 2432        _: &ToggleEditPrediction,
 2433        window: &mut Window,
 2434        cx: &mut Context<Self>,
 2435    ) {
 2436        if self.show_inline_completions_override.is_some() {
 2437            self.set_show_edit_predictions(None, window, cx);
 2438        } else {
 2439            let show_edit_predictions = !self.edit_predictions_enabled();
 2440            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2441        }
 2442    }
 2443
 2444    pub fn set_show_edit_predictions(
 2445        &mut self,
 2446        show_edit_predictions: Option<bool>,
 2447        window: &mut Window,
 2448        cx: &mut Context<Self>,
 2449    ) {
 2450        self.show_inline_completions_override = show_edit_predictions;
 2451        self.update_edit_prediction_settings(cx);
 2452
 2453        if let Some(false) = show_edit_predictions {
 2454            self.discard_inline_completion(false, cx);
 2455        } else {
 2456            self.refresh_inline_completion(false, true, window, cx);
 2457        }
 2458    }
 2459
 2460    fn inline_completions_disabled_in_scope(
 2461        &self,
 2462        buffer: &Entity<Buffer>,
 2463        buffer_position: language::Anchor,
 2464        cx: &App,
 2465    ) -> bool {
 2466        let snapshot = buffer.read(cx).snapshot();
 2467        let settings = snapshot.settings_at(buffer_position, cx);
 2468
 2469        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2470            return false;
 2471        };
 2472
 2473        scope.override_name().map_or(false, |scope_name| {
 2474            settings
 2475                .edit_predictions_disabled_in
 2476                .iter()
 2477                .any(|s| s == scope_name)
 2478        })
 2479    }
 2480
 2481    pub fn set_use_modal_editing(&mut self, to: bool) {
 2482        self.use_modal_editing = to;
 2483    }
 2484
 2485    pub fn use_modal_editing(&self) -> bool {
 2486        self.use_modal_editing
 2487    }
 2488
 2489    fn selections_did_change(
 2490        &mut self,
 2491        local: bool,
 2492        old_cursor_position: &Anchor,
 2493        show_completions: bool,
 2494        window: &mut Window,
 2495        cx: &mut Context<Self>,
 2496    ) {
 2497        window.invalidate_character_coordinates();
 2498
 2499        // Copy selections to primary selection buffer
 2500        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2501        if local {
 2502            let selections = self.selections.all::<usize>(cx);
 2503            let buffer_handle = self.buffer.read(cx).read(cx);
 2504
 2505            let mut text = String::new();
 2506            for (index, selection) in selections.iter().enumerate() {
 2507                let text_for_selection = buffer_handle
 2508                    .text_for_range(selection.start..selection.end)
 2509                    .collect::<String>();
 2510
 2511                text.push_str(&text_for_selection);
 2512                if index != selections.len() - 1 {
 2513                    text.push('\n');
 2514                }
 2515            }
 2516
 2517            if !text.is_empty() {
 2518                cx.write_to_primary(ClipboardItem::new_string(text));
 2519            }
 2520        }
 2521
 2522        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2523            self.buffer.update(cx, |buffer, cx| {
 2524                buffer.set_active_selections(
 2525                    &self.selections.disjoint_anchors(),
 2526                    self.selections.line_mode,
 2527                    self.cursor_shape,
 2528                    cx,
 2529                )
 2530            });
 2531        }
 2532        let display_map = self
 2533            .display_map
 2534            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2535        let buffer = &display_map.buffer_snapshot;
 2536        self.add_selections_state = None;
 2537        self.select_next_state = None;
 2538        self.select_prev_state = None;
 2539        self.select_syntax_node_history.try_clear();
 2540        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2541        self.snippet_stack
 2542            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2543        self.take_rename(false, window, cx);
 2544
 2545        let new_cursor_position = self.selections.newest_anchor().head();
 2546
 2547        self.push_to_nav_history(
 2548            *old_cursor_position,
 2549            Some(new_cursor_position.to_point(buffer)),
 2550            false,
 2551            cx,
 2552        );
 2553
 2554        if local {
 2555            let new_cursor_position = self.selections.newest_anchor().head();
 2556            let mut context_menu = self.context_menu.borrow_mut();
 2557            let completion_menu = match context_menu.as_ref() {
 2558                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2559                _ => {
 2560                    *context_menu = None;
 2561                    None
 2562                }
 2563            };
 2564            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2565                if !self.registered_buffers.contains_key(&buffer_id) {
 2566                    if let Some(project) = self.project.as_ref() {
 2567                        project.update(cx, |project, cx| {
 2568                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2569                                return;
 2570                            };
 2571                            self.registered_buffers.insert(
 2572                                buffer_id,
 2573                                project.register_buffer_with_language_servers(&buffer, cx),
 2574                            );
 2575                        })
 2576                    }
 2577                }
 2578            }
 2579
 2580            if let Some(completion_menu) = completion_menu {
 2581                let cursor_position = new_cursor_position.to_offset(buffer);
 2582                let (word_range, kind) =
 2583                    buffer.surrounding_word(completion_menu.initial_position, true);
 2584                if kind == Some(CharKind::Word)
 2585                    && word_range.to_inclusive().contains(&cursor_position)
 2586                {
 2587                    let mut completion_menu = completion_menu.clone();
 2588                    drop(context_menu);
 2589
 2590                    let query = Self::completion_query(buffer, cursor_position);
 2591                    cx.spawn(async move |this, cx| {
 2592                        completion_menu
 2593                            .filter(query.as_deref(), cx.background_executor().clone())
 2594                            .await;
 2595
 2596                        this.update(cx, |this, cx| {
 2597                            let mut context_menu = this.context_menu.borrow_mut();
 2598                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2599                            else {
 2600                                return;
 2601                            };
 2602
 2603                            if menu.id > completion_menu.id {
 2604                                return;
 2605                            }
 2606
 2607                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2608                            drop(context_menu);
 2609                            cx.notify();
 2610                        })
 2611                    })
 2612                    .detach();
 2613
 2614                    if show_completions {
 2615                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2616                    }
 2617                } else {
 2618                    drop(context_menu);
 2619                    self.hide_context_menu(window, cx);
 2620                }
 2621            } else {
 2622                drop(context_menu);
 2623            }
 2624
 2625            hide_hover(self, cx);
 2626
 2627            if old_cursor_position.to_display_point(&display_map).row()
 2628                != new_cursor_position.to_display_point(&display_map).row()
 2629            {
 2630                self.available_code_actions.take();
 2631            }
 2632            self.refresh_code_actions(window, cx);
 2633            self.refresh_document_highlights(cx);
 2634            self.refresh_selected_text_highlights(false, window, cx);
 2635            refresh_matching_bracket_highlights(self, window, cx);
 2636            self.update_visible_inline_completion(window, cx);
 2637            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2638            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2639            self.inline_blame_popover.take();
 2640            if self.git_blame_inline_enabled {
 2641                self.start_inline_blame_timer(window, cx);
 2642            }
 2643        }
 2644
 2645        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2646        cx.emit(EditorEvent::SelectionsChanged { local });
 2647
 2648        let selections = &self.selections.disjoint;
 2649        if selections.len() == 1 {
 2650            cx.emit(SearchEvent::ActiveMatchChanged)
 2651        }
 2652        if local {
 2653            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2654                let inmemory_selections = selections
 2655                    .iter()
 2656                    .map(|s| {
 2657                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2658                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2659                    })
 2660                    .collect();
 2661                self.update_restoration_data(cx, |data| {
 2662                    data.selections = inmemory_selections;
 2663                });
 2664
 2665                if WorkspaceSettings::get(None, cx).restore_on_startup
 2666                    != RestoreOnStartupBehavior::None
 2667                {
 2668                    if let Some(workspace_id) =
 2669                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2670                    {
 2671                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2672                        let selections = selections.clone();
 2673                        let background_executor = cx.background_executor().clone();
 2674                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2675                        self.serialize_selections = cx.background_spawn(async move {
 2676                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2677                    let db_selections = selections
 2678                        .iter()
 2679                        .map(|selection| {
 2680                            (
 2681                                selection.start.to_offset(&snapshot),
 2682                                selection.end.to_offset(&snapshot),
 2683                            )
 2684                        })
 2685                        .collect();
 2686
 2687                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2688                        .await
 2689                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2690                        .log_err();
 2691                });
 2692                    }
 2693                }
 2694            }
 2695        }
 2696
 2697        cx.notify();
 2698    }
 2699
 2700    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2701        use text::ToOffset as _;
 2702        use text::ToPoint as _;
 2703
 2704        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2705            return;
 2706        }
 2707
 2708        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2709            return;
 2710        };
 2711
 2712        let snapshot = singleton.read(cx).snapshot();
 2713        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2714            let display_snapshot = display_map.snapshot(cx);
 2715
 2716            display_snapshot
 2717                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2718                .map(|fold| {
 2719                    fold.range.start.text_anchor.to_point(&snapshot)
 2720                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2721                })
 2722                .collect()
 2723        });
 2724        self.update_restoration_data(cx, |data| {
 2725            data.folds = inmemory_folds;
 2726        });
 2727
 2728        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2729            return;
 2730        };
 2731        let background_executor = cx.background_executor().clone();
 2732        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2733        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2734            display_map
 2735                .snapshot(cx)
 2736                .folds_in_range(0..snapshot.len())
 2737                .map(|fold| {
 2738                    (
 2739                        fold.range.start.text_anchor.to_offset(&snapshot),
 2740                        fold.range.end.text_anchor.to_offset(&snapshot),
 2741                    )
 2742                })
 2743                .collect()
 2744        });
 2745        self.serialize_folds = cx.background_spawn(async move {
 2746            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2747            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2748                .await
 2749                .with_context(|| {
 2750                    format!(
 2751                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2752                    )
 2753                })
 2754                .log_err();
 2755        });
 2756    }
 2757
 2758    pub fn sync_selections(
 2759        &mut self,
 2760        other: Entity<Editor>,
 2761        cx: &mut Context<Self>,
 2762    ) -> gpui::Subscription {
 2763        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2764        self.selections.change_with(cx, |selections| {
 2765            selections.select_anchors(other_selections);
 2766        });
 2767
 2768        let other_subscription =
 2769            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2770                EditorEvent::SelectionsChanged { local: true } => {
 2771                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2772                    if other_selections.is_empty() {
 2773                        return;
 2774                    }
 2775                    this.selections.change_with(cx, |selections| {
 2776                        selections.select_anchors(other_selections);
 2777                    });
 2778                }
 2779                _ => {}
 2780            });
 2781
 2782        let this_subscription =
 2783            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2784                EditorEvent::SelectionsChanged { local: true } => {
 2785                    let these_selections = this.selections.disjoint.to_vec();
 2786                    if these_selections.is_empty() {
 2787                        return;
 2788                    }
 2789                    other.update(cx, |other_editor, cx| {
 2790                        other_editor.selections.change_with(cx, |selections| {
 2791                            selections.select_anchors(these_selections);
 2792                        })
 2793                    });
 2794                }
 2795                _ => {}
 2796            });
 2797
 2798        Subscription::join(other_subscription, this_subscription)
 2799    }
 2800
 2801    pub fn change_selections<R>(
 2802        &mut self,
 2803        autoscroll: Option<Autoscroll>,
 2804        window: &mut Window,
 2805        cx: &mut Context<Self>,
 2806        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2807    ) -> R {
 2808        self.change_selections_inner(autoscroll, true, window, cx, change)
 2809    }
 2810
 2811    fn change_selections_inner<R>(
 2812        &mut self,
 2813        autoscroll: Option<Autoscroll>,
 2814        request_completions: bool,
 2815        window: &mut Window,
 2816        cx: &mut Context<Self>,
 2817        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2818    ) -> R {
 2819        let old_cursor_position = self.selections.newest_anchor().head();
 2820        self.push_to_selection_history();
 2821
 2822        let (changed, result) = self.selections.change_with(cx, change);
 2823
 2824        if changed {
 2825            if let Some(autoscroll) = autoscroll {
 2826                self.request_autoscroll(autoscroll, cx);
 2827            }
 2828            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2829
 2830            if self.should_open_signature_help_automatically(
 2831                &old_cursor_position,
 2832                self.signature_help_state.backspace_pressed(),
 2833                cx,
 2834            ) {
 2835                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2836            }
 2837            self.signature_help_state.set_backspace_pressed(false);
 2838        }
 2839
 2840        result
 2841    }
 2842
 2843    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2844    where
 2845        I: IntoIterator<Item = (Range<S>, T)>,
 2846        S: ToOffset,
 2847        T: Into<Arc<str>>,
 2848    {
 2849        if self.read_only(cx) {
 2850            return;
 2851        }
 2852
 2853        self.buffer
 2854            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2855    }
 2856
 2857    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2858    where
 2859        I: IntoIterator<Item = (Range<S>, T)>,
 2860        S: ToOffset,
 2861        T: Into<Arc<str>>,
 2862    {
 2863        if self.read_only(cx) {
 2864            return;
 2865        }
 2866
 2867        self.buffer.update(cx, |buffer, cx| {
 2868            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2869        });
 2870    }
 2871
 2872    pub fn edit_with_block_indent<I, S, T>(
 2873        &mut self,
 2874        edits: I,
 2875        original_indent_columns: Vec<Option<u32>>,
 2876        cx: &mut Context<Self>,
 2877    ) where
 2878        I: IntoIterator<Item = (Range<S>, T)>,
 2879        S: ToOffset,
 2880        T: Into<Arc<str>>,
 2881    {
 2882        if self.read_only(cx) {
 2883            return;
 2884        }
 2885
 2886        self.buffer.update(cx, |buffer, cx| {
 2887            buffer.edit(
 2888                edits,
 2889                Some(AutoindentMode::Block {
 2890                    original_indent_columns,
 2891                }),
 2892                cx,
 2893            )
 2894        });
 2895    }
 2896
 2897    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2898        self.hide_context_menu(window, cx);
 2899
 2900        match phase {
 2901            SelectPhase::Begin {
 2902                position,
 2903                add,
 2904                click_count,
 2905            } => self.begin_selection(position, add, click_count, window, cx),
 2906            SelectPhase::BeginColumnar {
 2907                position,
 2908                goal_column,
 2909                reset,
 2910            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2911            SelectPhase::Extend {
 2912                position,
 2913                click_count,
 2914            } => self.extend_selection(position, click_count, window, cx),
 2915            SelectPhase::Update {
 2916                position,
 2917                goal_column,
 2918                scroll_delta,
 2919            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2920            SelectPhase::End => self.end_selection(window, cx),
 2921        }
 2922    }
 2923
 2924    fn extend_selection(
 2925        &mut self,
 2926        position: DisplayPoint,
 2927        click_count: usize,
 2928        window: &mut Window,
 2929        cx: &mut Context<Self>,
 2930    ) {
 2931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2932        let tail = self.selections.newest::<usize>(cx).tail();
 2933        self.begin_selection(position, false, click_count, window, cx);
 2934
 2935        let position = position.to_offset(&display_map, Bias::Left);
 2936        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2937
 2938        let mut pending_selection = self
 2939            .selections
 2940            .pending_anchor()
 2941            .expect("extend_selection not called with pending selection");
 2942        if position >= tail {
 2943            pending_selection.start = tail_anchor;
 2944        } else {
 2945            pending_selection.end = tail_anchor;
 2946            pending_selection.reversed = true;
 2947        }
 2948
 2949        let mut pending_mode = self.selections.pending_mode().unwrap();
 2950        match &mut pending_mode {
 2951            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2952            _ => {}
 2953        }
 2954
 2955        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2956            s.set_pending(pending_selection, pending_mode)
 2957        });
 2958    }
 2959
 2960    fn begin_selection(
 2961        &mut self,
 2962        position: DisplayPoint,
 2963        add: bool,
 2964        click_count: usize,
 2965        window: &mut Window,
 2966        cx: &mut Context<Self>,
 2967    ) {
 2968        if !self.focus_handle.is_focused(window) {
 2969            self.last_focused_descendant = None;
 2970            window.focus(&self.focus_handle);
 2971        }
 2972
 2973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2974        let buffer = &display_map.buffer_snapshot;
 2975        let newest_selection = self.selections.newest_anchor().clone();
 2976        let position = display_map.clip_point(position, Bias::Left);
 2977
 2978        let start;
 2979        let end;
 2980        let mode;
 2981        let mut auto_scroll;
 2982        match click_count {
 2983            1 => {
 2984                start = buffer.anchor_before(position.to_point(&display_map));
 2985                end = start;
 2986                mode = SelectMode::Character;
 2987                auto_scroll = true;
 2988            }
 2989            2 => {
 2990                let range = movement::surrounding_word(&display_map, position);
 2991                start = buffer.anchor_before(range.start.to_point(&display_map));
 2992                end = buffer.anchor_before(range.end.to_point(&display_map));
 2993                mode = SelectMode::Word(start..end);
 2994                auto_scroll = true;
 2995            }
 2996            3 => {
 2997                let position = display_map
 2998                    .clip_point(position, Bias::Left)
 2999                    .to_point(&display_map);
 3000                let line_start = display_map.prev_line_boundary(position).0;
 3001                let next_line_start = buffer.clip_point(
 3002                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3003                    Bias::Left,
 3004                );
 3005                start = buffer.anchor_before(line_start);
 3006                end = buffer.anchor_before(next_line_start);
 3007                mode = SelectMode::Line(start..end);
 3008                auto_scroll = true;
 3009            }
 3010            _ => {
 3011                start = buffer.anchor_before(0);
 3012                end = buffer.anchor_before(buffer.len());
 3013                mode = SelectMode::All;
 3014                auto_scroll = false;
 3015            }
 3016        }
 3017        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3018
 3019        let point_to_delete: Option<usize> = {
 3020            let selected_points: Vec<Selection<Point>> =
 3021                self.selections.disjoint_in_range(start..end, cx);
 3022
 3023            if !add || click_count > 1 {
 3024                None
 3025            } else if !selected_points.is_empty() {
 3026                Some(selected_points[0].id)
 3027            } else {
 3028                let clicked_point_already_selected =
 3029                    self.selections.disjoint.iter().find(|selection| {
 3030                        selection.start.to_point(buffer) == start.to_point(buffer)
 3031                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3032                    });
 3033
 3034                clicked_point_already_selected.map(|selection| selection.id)
 3035            }
 3036        };
 3037
 3038        let selections_count = self.selections.count();
 3039
 3040        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3041            if let Some(point_to_delete) = point_to_delete {
 3042                s.delete(point_to_delete);
 3043
 3044                if selections_count == 1 {
 3045                    s.set_pending_anchor_range(start..end, mode);
 3046                }
 3047            } else {
 3048                if !add {
 3049                    s.clear_disjoint();
 3050                } else if click_count > 1 {
 3051                    s.delete(newest_selection.id)
 3052                }
 3053
 3054                s.set_pending_anchor_range(start..end, mode);
 3055            }
 3056        });
 3057    }
 3058
 3059    fn begin_columnar_selection(
 3060        &mut self,
 3061        position: DisplayPoint,
 3062        goal_column: u32,
 3063        reset: bool,
 3064        window: &mut Window,
 3065        cx: &mut Context<Self>,
 3066    ) {
 3067        if !self.focus_handle.is_focused(window) {
 3068            self.last_focused_descendant = None;
 3069            window.focus(&self.focus_handle);
 3070        }
 3071
 3072        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3073
 3074        if reset {
 3075            let pointer_position = display_map
 3076                .buffer_snapshot
 3077                .anchor_before(position.to_point(&display_map));
 3078
 3079            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3080                s.clear_disjoint();
 3081                s.set_pending_anchor_range(
 3082                    pointer_position..pointer_position,
 3083                    SelectMode::Character,
 3084                );
 3085            });
 3086        }
 3087
 3088        let tail = self.selections.newest::<Point>(cx).tail();
 3089        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3090
 3091        if !reset {
 3092            self.select_columns(
 3093                tail.to_display_point(&display_map),
 3094                position,
 3095                goal_column,
 3096                &display_map,
 3097                window,
 3098                cx,
 3099            );
 3100        }
 3101    }
 3102
 3103    fn update_selection(
 3104        &mut self,
 3105        position: DisplayPoint,
 3106        goal_column: u32,
 3107        scroll_delta: gpui::Point<f32>,
 3108        window: &mut Window,
 3109        cx: &mut Context<Self>,
 3110    ) {
 3111        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3112
 3113        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3114            let tail = tail.to_display_point(&display_map);
 3115            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3116        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3117            let buffer = self.buffer.read(cx).snapshot(cx);
 3118            let head;
 3119            let tail;
 3120            let mode = self.selections.pending_mode().unwrap();
 3121            match &mode {
 3122                SelectMode::Character => {
 3123                    head = position.to_point(&display_map);
 3124                    tail = pending.tail().to_point(&buffer);
 3125                }
 3126                SelectMode::Word(original_range) => {
 3127                    let original_display_range = original_range.start.to_display_point(&display_map)
 3128                        ..original_range.end.to_display_point(&display_map);
 3129                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3130                        ..original_display_range.end.to_point(&display_map);
 3131                    if movement::is_inside_word(&display_map, position)
 3132                        || original_display_range.contains(&position)
 3133                    {
 3134                        let word_range = movement::surrounding_word(&display_map, position);
 3135                        if word_range.start < original_display_range.start {
 3136                            head = word_range.start.to_point(&display_map);
 3137                        } else {
 3138                            head = word_range.end.to_point(&display_map);
 3139                        }
 3140                    } else {
 3141                        head = position.to_point(&display_map);
 3142                    }
 3143
 3144                    if head <= original_buffer_range.start {
 3145                        tail = original_buffer_range.end;
 3146                    } else {
 3147                        tail = original_buffer_range.start;
 3148                    }
 3149                }
 3150                SelectMode::Line(original_range) => {
 3151                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3152
 3153                    let position = display_map
 3154                        .clip_point(position, Bias::Left)
 3155                        .to_point(&display_map);
 3156                    let line_start = display_map.prev_line_boundary(position).0;
 3157                    let next_line_start = buffer.clip_point(
 3158                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3159                        Bias::Left,
 3160                    );
 3161
 3162                    if line_start < original_range.start {
 3163                        head = line_start
 3164                    } else {
 3165                        head = next_line_start
 3166                    }
 3167
 3168                    if head <= original_range.start {
 3169                        tail = original_range.end;
 3170                    } else {
 3171                        tail = original_range.start;
 3172                    }
 3173                }
 3174                SelectMode::All => {
 3175                    return;
 3176                }
 3177            };
 3178
 3179            if head < tail {
 3180                pending.start = buffer.anchor_before(head);
 3181                pending.end = buffer.anchor_before(tail);
 3182                pending.reversed = true;
 3183            } else {
 3184                pending.start = buffer.anchor_before(tail);
 3185                pending.end = buffer.anchor_before(head);
 3186                pending.reversed = false;
 3187            }
 3188
 3189            self.change_selections(None, window, cx, |s| {
 3190                s.set_pending(pending, mode);
 3191            });
 3192        } else {
 3193            log::error!("update_selection dispatched with no pending selection");
 3194            return;
 3195        }
 3196
 3197        self.apply_scroll_delta(scroll_delta, window, cx);
 3198        cx.notify();
 3199    }
 3200
 3201    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3202        self.columnar_selection_tail.take();
 3203        if self.selections.pending_anchor().is_some() {
 3204            let selections = self.selections.all::<usize>(cx);
 3205            self.change_selections(None, window, cx, |s| {
 3206                s.select(selections);
 3207                s.clear_pending();
 3208            });
 3209        }
 3210    }
 3211
 3212    fn select_columns(
 3213        &mut self,
 3214        tail: DisplayPoint,
 3215        head: DisplayPoint,
 3216        goal_column: u32,
 3217        display_map: &DisplaySnapshot,
 3218        window: &mut Window,
 3219        cx: &mut Context<Self>,
 3220    ) {
 3221        let start_row = cmp::min(tail.row(), head.row());
 3222        let end_row = cmp::max(tail.row(), head.row());
 3223        let start_column = cmp::min(tail.column(), goal_column);
 3224        let end_column = cmp::max(tail.column(), goal_column);
 3225        let reversed = start_column < tail.column();
 3226
 3227        let selection_ranges = (start_row.0..=end_row.0)
 3228            .map(DisplayRow)
 3229            .filter_map(|row| {
 3230                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3231                    let start = display_map
 3232                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3233                        .to_point(display_map);
 3234                    let end = display_map
 3235                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3236                        .to_point(display_map);
 3237                    if reversed {
 3238                        Some(end..start)
 3239                    } else {
 3240                        Some(start..end)
 3241                    }
 3242                } else {
 3243                    None
 3244                }
 3245            })
 3246            .collect::<Vec<_>>();
 3247
 3248        self.change_selections(None, window, cx, |s| {
 3249            s.select_ranges(selection_ranges);
 3250        });
 3251        cx.notify();
 3252    }
 3253
 3254    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3255        self.selections
 3256            .all_adjusted(cx)
 3257            .iter()
 3258            .any(|selection| !selection.is_empty())
 3259    }
 3260
 3261    pub fn has_pending_nonempty_selection(&self) -> bool {
 3262        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3263            Some(Selection { start, end, .. }) => start != end,
 3264            None => false,
 3265        };
 3266
 3267        pending_nonempty_selection
 3268            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3269    }
 3270
 3271    pub fn has_pending_selection(&self) -> bool {
 3272        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3273    }
 3274
 3275    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3276        self.selection_mark_mode = false;
 3277
 3278        if self.clear_expanded_diff_hunks(cx) {
 3279            cx.notify();
 3280            return;
 3281        }
 3282        if self.dismiss_menus_and_popups(true, window, cx) {
 3283            return;
 3284        }
 3285
 3286        if self.mode.is_full()
 3287            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3288        {
 3289            return;
 3290        }
 3291
 3292        cx.propagate();
 3293    }
 3294
 3295    pub fn dismiss_menus_and_popups(
 3296        &mut self,
 3297        is_user_requested: bool,
 3298        window: &mut Window,
 3299        cx: &mut Context<Self>,
 3300    ) -> bool {
 3301        if self.take_rename(false, window, cx).is_some() {
 3302            return true;
 3303        }
 3304
 3305        if hide_hover(self, cx) {
 3306            return true;
 3307        }
 3308
 3309        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3310            return true;
 3311        }
 3312
 3313        if self.hide_context_menu(window, cx).is_some() {
 3314            return true;
 3315        }
 3316
 3317        if self.mouse_context_menu.take().is_some() {
 3318            return true;
 3319        }
 3320
 3321        if is_user_requested && self.discard_inline_completion(true, cx) {
 3322            return true;
 3323        }
 3324
 3325        if self.snippet_stack.pop().is_some() {
 3326            return true;
 3327        }
 3328
 3329        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3330            self.dismiss_diagnostics(cx);
 3331            return true;
 3332        }
 3333
 3334        false
 3335    }
 3336
 3337    fn linked_editing_ranges_for(
 3338        &self,
 3339        selection: Range<text::Anchor>,
 3340        cx: &App,
 3341    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3342        if self.linked_edit_ranges.is_empty() {
 3343            return None;
 3344        }
 3345        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3346            selection.end.buffer_id.and_then(|end_buffer_id| {
 3347                if selection.start.buffer_id != Some(end_buffer_id) {
 3348                    return None;
 3349                }
 3350                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3351                let snapshot = buffer.read(cx).snapshot();
 3352                self.linked_edit_ranges
 3353                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3354                    .map(|ranges| (ranges, snapshot, buffer))
 3355            })?;
 3356        use text::ToOffset as TO;
 3357        // find offset from the start of current range to current cursor position
 3358        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3359
 3360        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3361        let start_difference = start_offset - start_byte_offset;
 3362        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3363        let end_difference = end_offset - start_byte_offset;
 3364        // Current range has associated linked ranges.
 3365        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3366        for range in linked_ranges.iter() {
 3367            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3368            let end_offset = start_offset + end_difference;
 3369            let start_offset = start_offset + start_difference;
 3370            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3371                continue;
 3372            }
 3373            if self.selections.disjoint_anchor_ranges().any(|s| {
 3374                if s.start.buffer_id != selection.start.buffer_id
 3375                    || s.end.buffer_id != selection.end.buffer_id
 3376                {
 3377                    return false;
 3378                }
 3379                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3380                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3381            }) {
 3382                continue;
 3383            }
 3384            let start = buffer_snapshot.anchor_after(start_offset);
 3385            let end = buffer_snapshot.anchor_after(end_offset);
 3386            linked_edits
 3387                .entry(buffer.clone())
 3388                .or_default()
 3389                .push(start..end);
 3390        }
 3391        Some(linked_edits)
 3392    }
 3393
 3394    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3395        let text: Arc<str> = text.into();
 3396
 3397        if self.read_only(cx) {
 3398            return;
 3399        }
 3400
 3401        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3402
 3403        let selections = self.selections.all_adjusted(cx);
 3404        let mut bracket_inserted = false;
 3405        let mut edits = Vec::new();
 3406        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3407        let mut new_selections = Vec::with_capacity(selections.len());
 3408        let mut new_autoclose_regions = Vec::new();
 3409        let snapshot = self.buffer.read(cx).read(cx);
 3410        let mut clear_linked_edit_ranges = false;
 3411
 3412        for (selection, autoclose_region) in
 3413            self.selections_with_autoclose_regions(selections, &snapshot)
 3414        {
 3415            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3416                // Determine if the inserted text matches the opening or closing
 3417                // bracket of any of this language's bracket pairs.
 3418                let mut bracket_pair = None;
 3419                let mut is_bracket_pair_start = false;
 3420                let mut is_bracket_pair_end = false;
 3421                if !text.is_empty() {
 3422                    let mut bracket_pair_matching_end = None;
 3423                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3424                    //  and they are removing the character that triggered IME popup.
 3425                    for (pair, enabled) in scope.brackets() {
 3426                        if !pair.close && !pair.surround {
 3427                            continue;
 3428                        }
 3429
 3430                        if enabled && pair.start.ends_with(text.as_ref()) {
 3431                            let prefix_len = pair.start.len() - text.len();
 3432                            let preceding_text_matches_prefix = prefix_len == 0
 3433                                || (selection.start.column >= (prefix_len as u32)
 3434                                    && snapshot.contains_str_at(
 3435                                        Point::new(
 3436                                            selection.start.row,
 3437                                            selection.start.column - (prefix_len as u32),
 3438                                        ),
 3439                                        &pair.start[..prefix_len],
 3440                                    ));
 3441                            if preceding_text_matches_prefix {
 3442                                bracket_pair = Some(pair.clone());
 3443                                is_bracket_pair_start = true;
 3444                                break;
 3445                            }
 3446                        }
 3447                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3448                        {
 3449                            // take first bracket pair matching end, but don't break in case a later bracket
 3450                            // pair matches start
 3451                            bracket_pair_matching_end = Some(pair.clone());
 3452                        }
 3453                    }
 3454                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3455                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3456                        is_bracket_pair_end = true;
 3457                    }
 3458                }
 3459
 3460                if let Some(bracket_pair) = bracket_pair {
 3461                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3462                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3463                    let auto_surround =
 3464                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3465                    if selection.is_empty() {
 3466                        if is_bracket_pair_start {
 3467                            // If the inserted text is a suffix of an opening bracket and the
 3468                            // selection is preceded by the rest of the opening bracket, then
 3469                            // insert the closing bracket.
 3470                            let following_text_allows_autoclose = snapshot
 3471                                .chars_at(selection.start)
 3472                                .next()
 3473                                .map_or(true, |c| scope.should_autoclose_before(c));
 3474
 3475                            let preceding_text_allows_autoclose = selection.start.column == 0
 3476                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3477                                    true,
 3478                                    |c| {
 3479                                        bracket_pair.start != bracket_pair.end
 3480                                            || !snapshot
 3481                                                .char_classifier_at(selection.start)
 3482                                                .is_word(c)
 3483                                    },
 3484                                );
 3485
 3486                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3487                                && bracket_pair.start.len() == 1
 3488                            {
 3489                                let target = bracket_pair.start.chars().next().unwrap();
 3490                                let current_line_count = snapshot
 3491                                    .reversed_chars_at(selection.start)
 3492                                    .take_while(|&c| c != '\n')
 3493                                    .filter(|&c| c == target)
 3494                                    .count();
 3495                                current_line_count % 2 == 1
 3496                            } else {
 3497                                false
 3498                            };
 3499
 3500                            if autoclose
 3501                                && bracket_pair.close
 3502                                && following_text_allows_autoclose
 3503                                && preceding_text_allows_autoclose
 3504                                && !is_closing_quote
 3505                            {
 3506                                let anchor = snapshot.anchor_before(selection.end);
 3507                                new_selections.push((selection.map(|_| anchor), text.len()));
 3508                                new_autoclose_regions.push((
 3509                                    anchor,
 3510                                    text.len(),
 3511                                    selection.id,
 3512                                    bracket_pair.clone(),
 3513                                ));
 3514                                edits.push((
 3515                                    selection.range(),
 3516                                    format!("{}{}", text, bracket_pair.end).into(),
 3517                                ));
 3518                                bracket_inserted = true;
 3519                                continue;
 3520                            }
 3521                        }
 3522
 3523                        if let Some(region) = autoclose_region {
 3524                            // If the selection is followed by an auto-inserted closing bracket,
 3525                            // then don't insert that closing bracket again; just move the selection
 3526                            // past the closing bracket.
 3527                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3528                                && text.as_ref() == region.pair.end.as_str();
 3529                            if should_skip {
 3530                                let anchor = snapshot.anchor_after(selection.end);
 3531                                new_selections
 3532                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3533                                continue;
 3534                            }
 3535                        }
 3536
 3537                        let always_treat_brackets_as_autoclosed = snapshot
 3538                            .language_settings_at(selection.start, cx)
 3539                            .always_treat_brackets_as_autoclosed;
 3540                        if always_treat_brackets_as_autoclosed
 3541                            && is_bracket_pair_end
 3542                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3543                        {
 3544                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3545                            // and the inserted text is a closing bracket and the selection is followed
 3546                            // by the closing bracket then move the selection past the closing bracket.
 3547                            let anchor = snapshot.anchor_after(selection.end);
 3548                            new_selections.push((selection.map(|_| anchor), text.len()));
 3549                            continue;
 3550                        }
 3551                    }
 3552                    // If an opening bracket is 1 character long and is typed while
 3553                    // text is selected, then surround that text with the bracket pair.
 3554                    else if auto_surround
 3555                        && bracket_pair.surround
 3556                        && is_bracket_pair_start
 3557                        && bracket_pair.start.chars().count() == 1
 3558                    {
 3559                        edits.push((selection.start..selection.start, text.clone()));
 3560                        edits.push((
 3561                            selection.end..selection.end,
 3562                            bracket_pair.end.as_str().into(),
 3563                        ));
 3564                        bracket_inserted = true;
 3565                        new_selections.push((
 3566                            Selection {
 3567                                id: selection.id,
 3568                                start: snapshot.anchor_after(selection.start),
 3569                                end: snapshot.anchor_before(selection.end),
 3570                                reversed: selection.reversed,
 3571                                goal: selection.goal,
 3572                            },
 3573                            0,
 3574                        ));
 3575                        continue;
 3576                    }
 3577                }
 3578            }
 3579
 3580            if self.auto_replace_emoji_shortcode
 3581                && selection.is_empty()
 3582                && text.as_ref().ends_with(':')
 3583            {
 3584                if let Some(possible_emoji_short_code) =
 3585                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3586                {
 3587                    if !possible_emoji_short_code.is_empty() {
 3588                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3589                            let emoji_shortcode_start = Point::new(
 3590                                selection.start.row,
 3591                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3592                            );
 3593
 3594                            // Remove shortcode from buffer
 3595                            edits.push((
 3596                                emoji_shortcode_start..selection.start,
 3597                                "".to_string().into(),
 3598                            ));
 3599                            new_selections.push((
 3600                                Selection {
 3601                                    id: selection.id,
 3602                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3603                                    end: snapshot.anchor_before(selection.start),
 3604                                    reversed: selection.reversed,
 3605                                    goal: selection.goal,
 3606                                },
 3607                                0,
 3608                            ));
 3609
 3610                            // Insert emoji
 3611                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3612                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3613                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3614
 3615                            continue;
 3616                        }
 3617                    }
 3618                }
 3619            }
 3620
 3621            // If not handling any auto-close operation, then just replace the selected
 3622            // text with the given input and move the selection to the end of the
 3623            // newly inserted text.
 3624            let anchor = snapshot.anchor_after(selection.end);
 3625            if !self.linked_edit_ranges.is_empty() {
 3626                let start_anchor = snapshot.anchor_before(selection.start);
 3627
 3628                let is_word_char = text.chars().next().map_or(true, |char| {
 3629                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3630                    classifier.is_word(char)
 3631                });
 3632
 3633                if is_word_char {
 3634                    if let Some(ranges) = self
 3635                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3636                    {
 3637                        for (buffer, edits) in ranges {
 3638                            linked_edits
 3639                                .entry(buffer.clone())
 3640                                .or_default()
 3641                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3642                        }
 3643                    }
 3644                } else {
 3645                    clear_linked_edit_ranges = true;
 3646                }
 3647            }
 3648
 3649            new_selections.push((selection.map(|_| anchor), 0));
 3650            edits.push((selection.start..selection.end, text.clone()));
 3651        }
 3652
 3653        drop(snapshot);
 3654
 3655        self.transact(window, cx, |this, window, cx| {
 3656            if clear_linked_edit_ranges {
 3657                this.linked_edit_ranges.clear();
 3658            }
 3659            let initial_buffer_versions =
 3660                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3661
 3662            this.buffer.update(cx, |buffer, cx| {
 3663                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3664            });
 3665            for (buffer, edits) in linked_edits {
 3666                buffer.update(cx, |buffer, cx| {
 3667                    let snapshot = buffer.snapshot();
 3668                    let edits = edits
 3669                        .into_iter()
 3670                        .map(|(range, text)| {
 3671                            use text::ToPoint as TP;
 3672                            let end_point = TP::to_point(&range.end, &snapshot);
 3673                            let start_point = TP::to_point(&range.start, &snapshot);
 3674                            (start_point..end_point, text)
 3675                        })
 3676                        .sorted_by_key(|(range, _)| range.start);
 3677                    buffer.edit(edits, None, cx);
 3678                })
 3679            }
 3680            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3681            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3682            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3683            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3684                .zip(new_selection_deltas)
 3685                .map(|(selection, delta)| Selection {
 3686                    id: selection.id,
 3687                    start: selection.start + delta,
 3688                    end: selection.end + delta,
 3689                    reversed: selection.reversed,
 3690                    goal: SelectionGoal::None,
 3691                })
 3692                .collect::<Vec<_>>();
 3693
 3694            let mut i = 0;
 3695            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3696                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3697                let start = map.buffer_snapshot.anchor_before(position);
 3698                let end = map.buffer_snapshot.anchor_after(position);
 3699                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3700                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3701                        Ordering::Less => i += 1,
 3702                        Ordering::Greater => break,
 3703                        Ordering::Equal => {
 3704                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3705                                Ordering::Less => i += 1,
 3706                                Ordering::Equal => break,
 3707                                Ordering::Greater => break,
 3708                            }
 3709                        }
 3710                    }
 3711                }
 3712                this.autoclose_regions.insert(
 3713                    i,
 3714                    AutocloseRegion {
 3715                        selection_id,
 3716                        range: start..end,
 3717                        pair,
 3718                    },
 3719                );
 3720            }
 3721
 3722            let had_active_inline_completion = this.has_active_inline_completion();
 3723            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3724                s.select(new_selections)
 3725            });
 3726
 3727            if !bracket_inserted {
 3728                if let Some(on_type_format_task) =
 3729                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3730                {
 3731                    on_type_format_task.detach_and_log_err(cx);
 3732                }
 3733            }
 3734
 3735            let editor_settings = EditorSettings::get_global(cx);
 3736            if bracket_inserted
 3737                && (editor_settings.auto_signature_help
 3738                    || editor_settings.show_signature_help_after_edits)
 3739            {
 3740                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3741            }
 3742
 3743            let trigger_in_words =
 3744                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3745            if this.hard_wrap.is_some() {
 3746                let latest: Range<Point> = this.selections.newest(cx).range();
 3747                if latest.is_empty()
 3748                    && this
 3749                        .buffer()
 3750                        .read(cx)
 3751                        .snapshot(cx)
 3752                        .line_len(MultiBufferRow(latest.start.row))
 3753                        == latest.start.column
 3754                {
 3755                    this.rewrap_impl(
 3756                        RewrapOptions {
 3757                            override_language_settings: true,
 3758                            preserve_existing_whitespace: true,
 3759                        },
 3760                        cx,
 3761                    )
 3762                }
 3763            }
 3764            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3765            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3766            this.refresh_inline_completion(true, false, window, cx);
 3767            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3768        });
 3769    }
 3770
 3771    fn find_possible_emoji_shortcode_at_position(
 3772        snapshot: &MultiBufferSnapshot,
 3773        position: Point,
 3774    ) -> Option<String> {
 3775        let mut chars = Vec::new();
 3776        let mut found_colon = false;
 3777        for char in snapshot.reversed_chars_at(position).take(100) {
 3778            // Found a possible emoji shortcode in the middle of the buffer
 3779            if found_colon {
 3780                if char.is_whitespace() {
 3781                    chars.reverse();
 3782                    return Some(chars.iter().collect());
 3783                }
 3784                // If the previous character is not a whitespace, we are in the middle of a word
 3785                // and we only want to complete the shortcode if the word is made up of other emojis
 3786                let mut containing_word = String::new();
 3787                for ch in snapshot
 3788                    .reversed_chars_at(position)
 3789                    .skip(chars.len() + 1)
 3790                    .take(100)
 3791                {
 3792                    if ch.is_whitespace() {
 3793                        break;
 3794                    }
 3795                    containing_word.push(ch);
 3796                }
 3797                let containing_word = containing_word.chars().rev().collect::<String>();
 3798                if util::word_consists_of_emojis(containing_word.as_str()) {
 3799                    chars.reverse();
 3800                    return Some(chars.iter().collect());
 3801                }
 3802            }
 3803
 3804            if char.is_whitespace() || !char.is_ascii() {
 3805                return None;
 3806            }
 3807            if char == ':' {
 3808                found_colon = true;
 3809            } else {
 3810                chars.push(char);
 3811            }
 3812        }
 3813        // Found a possible emoji shortcode at the beginning of the buffer
 3814        chars.reverse();
 3815        Some(chars.iter().collect())
 3816    }
 3817
 3818    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3819        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3820        self.transact(window, cx, |this, window, cx| {
 3821            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3822                let selections = this.selections.all::<usize>(cx);
 3823                let multi_buffer = this.buffer.read(cx);
 3824                let buffer = multi_buffer.snapshot(cx);
 3825                selections
 3826                    .iter()
 3827                    .map(|selection| {
 3828                        let start_point = selection.start.to_point(&buffer);
 3829                        let mut indent =
 3830                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3831                        indent.len = cmp::min(indent.len, start_point.column);
 3832                        let start = selection.start;
 3833                        let end = selection.end;
 3834                        let selection_is_empty = start == end;
 3835                        let language_scope = buffer.language_scope_at(start);
 3836                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3837                            &language_scope
 3838                        {
 3839                            let insert_extra_newline =
 3840                                insert_extra_newline_brackets(&buffer, start..end, language)
 3841                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3842
 3843                            // Comment extension on newline is allowed only for cursor selections
 3844                            let comment_delimiter = maybe!({
 3845                                if !selection_is_empty {
 3846                                    return None;
 3847                                }
 3848
 3849                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3850                                    return None;
 3851                                }
 3852
 3853                                let delimiters = language.line_comment_prefixes();
 3854                                let max_len_of_delimiter =
 3855                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3856                                let (snapshot, range) =
 3857                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3858
 3859                                let mut index_of_first_non_whitespace = 0;
 3860                                let comment_candidate = snapshot
 3861                                    .chars_for_range(range)
 3862                                    .skip_while(|c| {
 3863                                        let should_skip = c.is_whitespace();
 3864                                        if should_skip {
 3865                                            index_of_first_non_whitespace += 1;
 3866                                        }
 3867                                        should_skip
 3868                                    })
 3869                                    .take(max_len_of_delimiter)
 3870                                    .collect::<String>();
 3871                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3872                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3873                                })?;
 3874                                let cursor_is_placed_after_comment_marker =
 3875                                    index_of_first_non_whitespace + comment_prefix.len()
 3876                                        <= start_point.column as usize;
 3877                                if cursor_is_placed_after_comment_marker {
 3878                                    Some(comment_prefix.clone())
 3879                                } else {
 3880                                    None
 3881                                }
 3882                            });
 3883                            (comment_delimiter, insert_extra_newline)
 3884                        } else {
 3885                            (None, false)
 3886                        };
 3887
 3888                        let capacity_for_delimiter = comment_delimiter
 3889                            .as_deref()
 3890                            .map(str::len)
 3891                            .unwrap_or_default();
 3892                        let mut new_text =
 3893                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3894                        new_text.push('\n');
 3895                        new_text.extend(indent.chars());
 3896                        if let Some(delimiter) = &comment_delimiter {
 3897                            new_text.push_str(delimiter);
 3898                        }
 3899                        if insert_extra_newline {
 3900                            new_text = new_text.repeat(2);
 3901                        }
 3902
 3903                        let anchor = buffer.anchor_after(end);
 3904                        let new_selection = selection.map(|_| anchor);
 3905                        (
 3906                            (start..end, new_text),
 3907                            (insert_extra_newline, new_selection),
 3908                        )
 3909                    })
 3910                    .unzip()
 3911            };
 3912
 3913            this.edit_with_autoindent(edits, cx);
 3914            let buffer = this.buffer.read(cx).snapshot(cx);
 3915            let new_selections = selection_fixup_info
 3916                .into_iter()
 3917                .map(|(extra_newline_inserted, new_selection)| {
 3918                    let mut cursor = new_selection.end.to_point(&buffer);
 3919                    if extra_newline_inserted {
 3920                        cursor.row -= 1;
 3921                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3922                    }
 3923                    new_selection.map(|_| cursor)
 3924                })
 3925                .collect();
 3926
 3927            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3928                s.select(new_selections)
 3929            });
 3930            this.refresh_inline_completion(true, false, window, cx);
 3931        });
 3932    }
 3933
 3934    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3935        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3936
 3937        let buffer = self.buffer.read(cx);
 3938        let snapshot = buffer.snapshot(cx);
 3939
 3940        let mut edits = Vec::new();
 3941        let mut rows = Vec::new();
 3942
 3943        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3944            let cursor = selection.head();
 3945            let row = cursor.row;
 3946
 3947            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3948
 3949            let newline = "\n".to_string();
 3950            edits.push((start_of_line..start_of_line, newline));
 3951
 3952            rows.push(row + rows_inserted as u32);
 3953        }
 3954
 3955        self.transact(window, cx, |editor, window, cx| {
 3956            editor.edit(edits, cx);
 3957
 3958            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3959                let mut index = 0;
 3960                s.move_cursors_with(|map, _, _| {
 3961                    let row = rows[index];
 3962                    index += 1;
 3963
 3964                    let point = Point::new(row, 0);
 3965                    let boundary = map.next_line_boundary(point).1;
 3966                    let clipped = map.clip_point(boundary, Bias::Left);
 3967
 3968                    (clipped, SelectionGoal::None)
 3969                });
 3970            });
 3971
 3972            let mut indent_edits = Vec::new();
 3973            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3974            for row in rows {
 3975                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3976                for (row, indent) in indents {
 3977                    if indent.len == 0 {
 3978                        continue;
 3979                    }
 3980
 3981                    let text = match indent.kind {
 3982                        IndentKind::Space => " ".repeat(indent.len as usize),
 3983                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3984                    };
 3985                    let point = Point::new(row.0, 0);
 3986                    indent_edits.push((point..point, text));
 3987                }
 3988            }
 3989            editor.edit(indent_edits, cx);
 3990        });
 3991    }
 3992
 3993    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3994        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3995
 3996        let buffer = self.buffer.read(cx);
 3997        let snapshot = buffer.snapshot(cx);
 3998
 3999        let mut edits = Vec::new();
 4000        let mut rows = Vec::new();
 4001        let mut rows_inserted = 0;
 4002
 4003        for selection in self.selections.all_adjusted(cx) {
 4004            let cursor = selection.head();
 4005            let row = cursor.row;
 4006
 4007            let point = Point::new(row + 1, 0);
 4008            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4009
 4010            let newline = "\n".to_string();
 4011            edits.push((start_of_line..start_of_line, newline));
 4012
 4013            rows_inserted += 1;
 4014            rows.push(row + rows_inserted);
 4015        }
 4016
 4017        self.transact(window, cx, |editor, window, cx| {
 4018            editor.edit(edits, cx);
 4019
 4020            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4021                let mut index = 0;
 4022                s.move_cursors_with(|map, _, _| {
 4023                    let row = rows[index];
 4024                    index += 1;
 4025
 4026                    let point = Point::new(row, 0);
 4027                    let boundary = map.next_line_boundary(point).1;
 4028                    let clipped = map.clip_point(boundary, Bias::Left);
 4029
 4030                    (clipped, SelectionGoal::None)
 4031                });
 4032            });
 4033
 4034            let mut indent_edits = Vec::new();
 4035            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4036            for row in rows {
 4037                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4038                for (row, indent) in indents {
 4039                    if indent.len == 0 {
 4040                        continue;
 4041                    }
 4042
 4043                    let text = match indent.kind {
 4044                        IndentKind::Space => " ".repeat(indent.len as usize),
 4045                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4046                    };
 4047                    let point = Point::new(row.0, 0);
 4048                    indent_edits.push((point..point, text));
 4049                }
 4050            }
 4051            editor.edit(indent_edits, cx);
 4052        });
 4053    }
 4054
 4055    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4056        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4057            original_indent_columns: Vec::new(),
 4058        });
 4059        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4060    }
 4061
 4062    fn insert_with_autoindent_mode(
 4063        &mut self,
 4064        text: &str,
 4065        autoindent_mode: Option<AutoindentMode>,
 4066        window: &mut Window,
 4067        cx: &mut Context<Self>,
 4068    ) {
 4069        if self.read_only(cx) {
 4070            return;
 4071        }
 4072
 4073        let text: Arc<str> = text.into();
 4074        self.transact(window, cx, |this, window, cx| {
 4075            let old_selections = this.selections.all_adjusted(cx);
 4076            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4077                let anchors = {
 4078                    let snapshot = buffer.read(cx);
 4079                    old_selections
 4080                        .iter()
 4081                        .map(|s| {
 4082                            let anchor = snapshot.anchor_after(s.head());
 4083                            s.map(|_| anchor)
 4084                        })
 4085                        .collect::<Vec<_>>()
 4086                };
 4087                buffer.edit(
 4088                    old_selections
 4089                        .iter()
 4090                        .map(|s| (s.start..s.end, text.clone())),
 4091                    autoindent_mode,
 4092                    cx,
 4093                );
 4094                anchors
 4095            });
 4096
 4097            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4098                s.select_anchors(selection_anchors);
 4099            });
 4100
 4101            cx.notify();
 4102        });
 4103    }
 4104
 4105    fn trigger_completion_on_input(
 4106        &mut self,
 4107        text: &str,
 4108        trigger_in_words: bool,
 4109        window: &mut Window,
 4110        cx: &mut Context<Self>,
 4111    ) {
 4112        let ignore_completion_provider = self
 4113            .context_menu
 4114            .borrow()
 4115            .as_ref()
 4116            .map(|menu| match menu {
 4117                CodeContextMenu::Completions(completions_menu) => {
 4118                    completions_menu.ignore_completion_provider
 4119                }
 4120                CodeContextMenu::CodeActions(_) => false,
 4121            })
 4122            .unwrap_or(false);
 4123
 4124        if ignore_completion_provider {
 4125            self.show_word_completions(&ShowWordCompletions, window, cx);
 4126        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4127            self.show_completions(
 4128                &ShowCompletions {
 4129                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4130                },
 4131                window,
 4132                cx,
 4133            );
 4134        } else {
 4135            self.hide_context_menu(window, cx);
 4136        }
 4137    }
 4138
 4139    fn is_completion_trigger(
 4140        &self,
 4141        text: &str,
 4142        trigger_in_words: bool,
 4143        cx: &mut Context<Self>,
 4144    ) -> bool {
 4145        let position = self.selections.newest_anchor().head();
 4146        let multibuffer = self.buffer.read(cx);
 4147        let Some(buffer) = position
 4148            .buffer_id
 4149            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4150        else {
 4151            return false;
 4152        };
 4153
 4154        if let Some(completion_provider) = &self.completion_provider {
 4155            completion_provider.is_completion_trigger(
 4156                &buffer,
 4157                position.text_anchor,
 4158                text,
 4159                trigger_in_words,
 4160                cx,
 4161            )
 4162        } else {
 4163            false
 4164        }
 4165    }
 4166
 4167    /// If any empty selections is touching the start of its innermost containing autoclose
 4168    /// region, expand it to select the brackets.
 4169    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4170        let selections = self.selections.all::<usize>(cx);
 4171        let buffer = self.buffer.read(cx).read(cx);
 4172        let new_selections = self
 4173            .selections_with_autoclose_regions(selections, &buffer)
 4174            .map(|(mut selection, region)| {
 4175                if !selection.is_empty() {
 4176                    return selection;
 4177                }
 4178
 4179                if let Some(region) = region {
 4180                    let mut range = region.range.to_offset(&buffer);
 4181                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4182                        range.start -= region.pair.start.len();
 4183                        if buffer.contains_str_at(range.start, &region.pair.start)
 4184                            && buffer.contains_str_at(range.end, &region.pair.end)
 4185                        {
 4186                            range.end += region.pair.end.len();
 4187                            selection.start = range.start;
 4188                            selection.end = range.end;
 4189
 4190                            return selection;
 4191                        }
 4192                    }
 4193                }
 4194
 4195                let always_treat_brackets_as_autoclosed = buffer
 4196                    .language_settings_at(selection.start, cx)
 4197                    .always_treat_brackets_as_autoclosed;
 4198
 4199                if !always_treat_brackets_as_autoclosed {
 4200                    return selection;
 4201                }
 4202
 4203                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4204                    for (pair, enabled) in scope.brackets() {
 4205                        if !enabled || !pair.close {
 4206                            continue;
 4207                        }
 4208
 4209                        if buffer.contains_str_at(selection.start, &pair.end) {
 4210                            let pair_start_len = pair.start.len();
 4211                            if buffer.contains_str_at(
 4212                                selection.start.saturating_sub(pair_start_len),
 4213                                &pair.start,
 4214                            ) {
 4215                                selection.start -= pair_start_len;
 4216                                selection.end += pair.end.len();
 4217
 4218                                return selection;
 4219                            }
 4220                        }
 4221                    }
 4222                }
 4223
 4224                selection
 4225            })
 4226            .collect();
 4227
 4228        drop(buffer);
 4229        self.change_selections(None, window, cx, |selections| {
 4230            selections.select(new_selections)
 4231        });
 4232    }
 4233
 4234    /// Iterate the given selections, and for each one, find the smallest surrounding
 4235    /// autoclose region. This uses the ordering of the selections and the autoclose
 4236    /// regions to avoid repeated comparisons.
 4237    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4238        &'a self,
 4239        selections: impl IntoIterator<Item = Selection<D>>,
 4240        buffer: &'a MultiBufferSnapshot,
 4241    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4242        let mut i = 0;
 4243        let mut regions = self.autoclose_regions.as_slice();
 4244        selections.into_iter().map(move |selection| {
 4245            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4246
 4247            let mut enclosing = None;
 4248            while let Some(pair_state) = regions.get(i) {
 4249                if pair_state.range.end.to_offset(buffer) < range.start {
 4250                    regions = &regions[i + 1..];
 4251                    i = 0;
 4252                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4253                    break;
 4254                } else {
 4255                    if pair_state.selection_id == selection.id {
 4256                        enclosing = Some(pair_state);
 4257                    }
 4258                    i += 1;
 4259                }
 4260            }
 4261
 4262            (selection, enclosing)
 4263        })
 4264    }
 4265
 4266    /// Remove any autoclose regions that no longer contain their selection.
 4267    fn invalidate_autoclose_regions(
 4268        &mut self,
 4269        mut selections: &[Selection<Anchor>],
 4270        buffer: &MultiBufferSnapshot,
 4271    ) {
 4272        self.autoclose_regions.retain(|state| {
 4273            let mut i = 0;
 4274            while let Some(selection) = selections.get(i) {
 4275                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4276                    selections = &selections[1..];
 4277                    continue;
 4278                }
 4279                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4280                    break;
 4281                }
 4282                if selection.id == state.selection_id {
 4283                    return true;
 4284                } else {
 4285                    i += 1;
 4286                }
 4287            }
 4288            false
 4289        });
 4290    }
 4291
 4292    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4293        let offset = position.to_offset(buffer);
 4294        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4295        if offset > word_range.start && kind == Some(CharKind::Word) {
 4296            Some(
 4297                buffer
 4298                    .text_for_range(word_range.start..offset)
 4299                    .collect::<String>(),
 4300            )
 4301        } else {
 4302            None
 4303        }
 4304    }
 4305
 4306    pub fn toggle_inline_values(
 4307        &mut self,
 4308        _: &ToggleInlineValues,
 4309        _: &mut Window,
 4310        cx: &mut Context<Self>,
 4311    ) {
 4312        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4313
 4314        self.refresh_inline_values(cx);
 4315    }
 4316
 4317    pub fn toggle_inlay_hints(
 4318        &mut self,
 4319        _: &ToggleInlayHints,
 4320        _: &mut Window,
 4321        cx: &mut Context<Self>,
 4322    ) {
 4323        self.refresh_inlay_hints(
 4324            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4325            cx,
 4326        );
 4327    }
 4328
 4329    pub fn inlay_hints_enabled(&self) -> bool {
 4330        self.inlay_hint_cache.enabled
 4331    }
 4332
 4333    pub fn inline_values_enabled(&self) -> bool {
 4334        self.inline_value_cache.enabled
 4335    }
 4336
 4337    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4338        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4339            return;
 4340        }
 4341
 4342        let reason_description = reason.description();
 4343        let ignore_debounce = matches!(
 4344            reason,
 4345            InlayHintRefreshReason::SettingsChange(_)
 4346                | InlayHintRefreshReason::Toggle(_)
 4347                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4348                | InlayHintRefreshReason::ModifiersChanged(_)
 4349        );
 4350        let (invalidate_cache, required_languages) = match reason {
 4351            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4352                match self.inlay_hint_cache.modifiers_override(enabled) {
 4353                    Some(enabled) => {
 4354                        if enabled {
 4355                            (InvalidationStrategy::RefreshRequested, None)
 4356                        } else {
 4357                            self.splice_inlays(
 4358                                &self
 4359                                    .visible_inlay_hints(cx)
 4360                                    .iter()
 4361                                    .map(|inlay| inlay.id)
 4362                                    .collect::<Vec<InlayId>>(),
 4363                                Vec::new(),
 4364                                cx,
 4365                            );
 4366                            return;
 4367                        }
 4368                    }
 4369                    None => return,
 4370                }
 4371            }
 4372            InlayHintRefreshReason::Toggle(enabled) => {
 4373                if self.inlay_hint_cache.toggle(enabled) {
 4374                    if enabled {
 4375                        (InvalidationStrategy::RefreshRequested, None)
 4376                    } else {
 4377                        self.splice_inlays(
 4378                            &self
 4379                                .visible_inlay_hints(cx)
 4380                                .iter()
 4381                                .map(|inlay| inlay.id)
 4382                                .collect::<Vec<InlayId>>(),
 4383                            Vec::new(),
 4384                            cx,
 4385                        );
 4386                        return;
 4387                    }
 4388                } else {
 4389                    return;
 4390                }
 4391            }
 4392            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4393                match self.inlay_hint_cache.update_settings(
 4394                    &self.buffer,
 4395                    new_settings,
 4396                    self.visible_inlay_hints(cx),
 4397                    cx,
 4398                ) {
 4399                    ControlFlow::Break(Some(InlaySplice {
 4400                        to_remove,
 4401                        to_insert,
 4402                    })) => {
 4403                        self.splice_inlays(&to_remove, to_insert, cx);
 4404                        return;
 4405                    }
 4406                    ControlFlow::Break(None) => return,
 4407                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4408                }
 4409            }
 4410            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4411                if let Some(InlaySplice {
 4412                    to_remove,
 4413                    to_insert,
 4414                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4415                {
 4416                    self.splice_inlays(&to_remove, to_insert, cx);
 4417                }
 4418                self.display_map.update(cx, |display_map, _| {
 4419                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4420                });
 4421                return;
 4422            }
 4423            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4424            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4425                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4426            }
 4427            InlayHintRefreshReason::RefreshRequested => {
 4428                (InvalidationStrategy::RefreshRequested, None)
 4429            }
 4430        };
 4431
 4432        if let Some(InlaySplice {
 4433            to_remove,
 4434            to_insert,
 4435        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4436            reason_description,
 4437            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4438            invalidate_cache,
 4439            ignore_debounce,
 4440            cx,
 4441        ) {
 4442            self.splice_inlays(&to_remove, to_insert, cx);
 4443        }
 4444    }
 4445
 4446    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4447        self.display_map
 4448            .read(cx)
 4449            .current_inlays()
 4450            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4451            .cloned()
 4452            .collect()
 4453    }
 4454
 4455    pub fn excerpts_for_inlay_hints_query(
 4456        &self,
 4457        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4458        cx: &mut Context<Editor>,
 4459    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4460        let Some(project) = self.project.as_ref() else {
 4461            return HashMap::default();
 4462        };
 4463        let project = project.read(cx);
 4464        let multi_buffer = self.buffer().read(cx);
 4465        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4466        let multi_buffer_visible_start = self
 4467            .scroll_manager
 4468            .anchor()
 4469            .anchor
 4470            .to_point(&multi_buffer_snapshot);
 4471        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4472            multi_buffer_visible_start
 4473                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4474            Bias::Left,
 4475        );
 4476        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4477        multi_buffer_snapshot
 4478            .range_to_buffer_ranges(multi_buffer_visible_range)
 4479            .into_iter()
 4480            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4481            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4482                let buffer_file = project::File::from_dyn(buffer.file())?;
 4483                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4484                let worktree_entry = buffer_worktree
 4485                    .read(cx)
 4486                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4487                if worktree_entry.is_ignored {
 4488                    return None;
 4489                }
 4490
 4491                let language = buffer.language()?;
 4492                if let Some(restrict_to_languages) = restrict_to_languages {
 4493                    if !restrict_to_languages.contains(language) {
 4494                        return None;
 4495                    }
 4496                }
 4497                Some((
 4498                    excerpt_id,
 4499                    (
 4500                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4501                        buffer.version().clone(),
 4502                        excerpt_visible_range,
 4503                    ),
 4504                ))
 4505            })
 4506            .collect()
 4507    }
 4508
 4509    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4510        TextLayoutDetails {
 4511            text_system: window.text_system().clone(),
 4512            editor_style: self.style.clone().unwrap(),
 4513            rem_size: window.rem_size(),
 4514            scroll_anchor: self.scroll_manager.anchor(),
 4515            visible_rows: self.visible_line_count(),
 4516            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4517        }
 4518    }
 4519
 4520    pub fn splice_inlays(
 4521        &self,
 4522        to_remove: &[InlayId],
 4523        to_insert: Vec<Inlay>,
 4524        cx: &mut Context<Self>,
 4525    ) {
 4526        self.display_map.update(cx, |display_map, cx| {
 4527            display_map.splice_inlays(to_remove, to_insert, cx)
 4528        });
 4529        cx.notify();
 4530    }
 4531
 4532    fn trigger_on_type_formatting(
 4533        &self,
 4534        input: String,
 4535        window: &mut Window,
 4536        cx: &mut Context<Self>,
 4537    ) -> Option<Task<Result<()>>> {
 4538        if input.len() != 1 {
 4539            return None;
 4540        }
 4541
 4542        let project = self.project.as_ref()?;
 4543        let position = self.selections.newest_anchor().head();
 4544        let (buffer, buffer_position) = self
 4545            .buffer
 4546            .read(cx)
 4547            .text_anchor_for_position(position, cx)?;
 4548
 4549        let settings = language_settings::language_settings(
 4550            buffer
 4551                .read(cx)
 4552                .language_at(buffer_position)
 4553                .map(|l| l.name()),
 4554            buffer.read(cx).file(),
 4555            cx,
 4556        );
 4557        if !settings.use_on_type_format {
 4558            return None;
 4559        }
 4560
 4561        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4562        // hence we do LSP request & edit on host side only — add formats to host's history.
 4563        let push_to_lsp_host_history = true;
 4564        // If this is not the host, append its history with new edits.
 4565        let push_to_client_history = project.read(cx).is_via_collab();
 4566
 4567        let on_type_formatting = project.update(cx, |project, cx| {
 4568            project.on_type_format(
 4569                buffer.clone(),
 4570                buffer_position,
 4571                input,
 4572                push_to_lsp_host_history,
 4573                cx,
 4574            )
 4575        });
 4576        Some(cx.spawn_in(window, async move |editor, cx| {
 4577            if let Some(transaction) = on_type_formatting.await? {
 4578                if push_to_client_history {
 4579                    buffer
 4580                        .update(cx, |buffer, _| {
 4581                            buffer.push_transaction(transaction, Instant::now());
 4582                            buffer.finalize_last_transaction();
 4583                        })
 4584                        .ok();
 4585                }
 4586                editor.update(cx, |editor, cx| {
 4587                    editor.refresh_document_highlights(cx);
 4588                })?;
 4589            }
 4590            Ok(())
 4591        }))
 4592    }
 4593
 4594    pub fn show_word_completions(
 4595        &mut self,
 4596        _: &ShowWordCompletions,
 4597        window: &mut Window,
 4598        cx: &mut Context<Self>,
 4599    ) {
 4600        self.open_completions_menu(true, None, window, cx);
 4601    }
 4602
 4603    pub fn show_completions(
 4604        &mut self,
 4605        options: &ShowCompletions,
 4606        window: &mut Window,
 4607        cx: &mut Context<Self>,
 4608    ) {
 4609        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4610    }
 4611
 4612    fn open_completions_menu(
 4613        &mut self,
 4614        ignore_completion_provider: bool,
 4615        trigger: Option<&str>,
 4616        window: &mut Window,
 4617        cx: &mut Context<Self>,
 4618    ) {
 4619        if self.pending_rename.is_some() {
 4620            return;
 4621        }
 4622        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4623            return;
 4624        }
 4625
 4626        let position = self.selections.newest_anchor().head();
 4627        if position.diff_base_anchor.is_some() {
 4628            return;
 4629        }
 4630        let (buffer, buffer_position) =
 4631            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4632                output
 4633            } else {
 4634                return;
 4635            };
 4636        let buffer_snapshot = buffer.read(cx).snapshot();
 4637        let show_completion_documentation = buffer_snapshot
 4638            .settings_at(buffer_position, cx)
 4639            .show_completion_documentation;
 4640
 4641        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4642
 4643        let trigger_kind = match trigger {
 4644            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4645                CompletionTriggerKind::TRIGGER_CHARACTER
 4646            }
 4647            _ => CompletionTriggerKind::INVOKED,
 4648        };
 4649        let completion_context = CompletionContext {
 4650            trigger_character: trigger.and_then(|trigger| {
 4651                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4652                    Some(String::from(trigger))
 4653                } else {
 4654                    None
 4655                }
 4656            }),
 4657            trigger_kind,
 4658        };
 4659
 4660        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4661        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4662            let word_to_exclude = buffer_snapshot
 4663                .text_for_range(old_range.clone())
 4664                .collect::<String>();
 4665            (
 4666                buffer_snapshot.anchor_before(old_range.start)
 4667                    ..buffer_snapshot.anchor_after(old_range.end),
 4668                Some(word_to_exclude),
 4669            )
 4670        } else {
 4671            (buffer_position..buffer_position, None)
 4672        };
 4673
 4674        let completion_settings = language_settings(
 4675            buffer_snapshot
 4676                .language_at(buffer_position)
 4677                .map(|language| language.name()),
 4678            buffer_snapshot.file(),
 4679            cx,
 4680        )
 4681        .completions;
 4682
 4683        // The document can be large, so stay in reasonable bounds when searching for words,
 4684        // otherwise completion pop-up might be slow to appear.
 4685        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4686        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4687        let min_word_search = buffer_snapshot.clip_point(
 4688            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4689            Bias::Left,
 4690        );
 4691        let max_word_search = buffer_snapshot.clip_point(
 4692            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4693            Bias::Right,
 4694        );
 4695        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4696            ..buffer_snapshot.point_to_offset(max_word_search);
 4697
 4698        let provider = self
 4699            .completion_provider
 4700            .as_ref()
 4701            .filter(|_| !ignore_completion_provider);
 4702        let skip_digits = query
 4703            .as_ref()
 4704            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4705
 4706        let (mut words, provided_completions) = match provider {
 4707            Some(provider) => {
 4708                let completions = provider.completions(
 4709                    position.excerpt_id,
 4710                    &buffer,
 4711                    buffer_position,
 4712                    completion_context,
 4713                    window,
 4714                    cx,
 4715                );
 4716
 4717                let words = match completion_settings.words {
 4718                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4719                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4720                        .background_spawn(async move {
 4721                            buffer_snapshot.words_in_range(WordsQuery {
 4722                                fuzzy_contents: None,
 4723                                range: word_search_range,
 4724                                skip_digits,
 4725                            })
 4726                        }),
 4727                };
 4728
 4729                (words, completions)
 4730            }
 4731            None => (
 4732                cx.background_spawn(async move {
 4733                    buffer_snapshot.words_in_range(WordsQuery {
 4734                        fuzzy_contents: None,
 4735                        range: word_search_range,
 4736                        skip_digits,
 4737                    })
 4738                }),
 4739                Task::ready(Ok(None)),
 4740            ),
 4741        };
 4742
 4743        let sort_completions = provider
 4744            .as_ref()
 4745            .map_or(false, |provider| provider.sort_completions());
 4746
 4747        let filter_completions = provider
 4748            .as_ref()
 4749            .map_or(true, |provider| provider.filter_completions());
 4750
 4751        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4752
 4753        let id = post_inc(&mut self.next_completion_id);
 4754        let task = cx.spawn_in(window, async move |editor, cx| {
 4755            async move {
 4756                editor.update(cx, |this, _| {
 4757                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4758                })?;
 4759
 4760                let mut completions = Vec::new();
 4761                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4762                    completions.extend(provided_completions);
 4763                    if completion_settings.words == WordsCompletionMode::Fallback {
 4764                        words = Task::ready(BTreeMap::default());
 4765                    }
 4766                }
 4767
 4768                let mut words = words.await;
 4769                if let Some(word_to_exclude) = &word_to_exclude {
 4770                    words.remove(word_to_exclude);
 4771                }
 4772                for lsp_completion in &completions {
 4773                    words.remove(&lsp_completion.new_text);
 4774                }
 4775                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4776                    replace_range: old_range.clone(),
 4777                    new_text: word.clone(),
 4778                    label: CodeLabel::plain(word, None),
 4779                    icon_path: None,
 4780                    documentation: None,
 4781                    source: CompletionSource::BufferWord {
 4782                        word_range,
 4783                        resolved: false,
 4784                    },
 4785                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4786                    confirm: None,
 4787                }));
 4788
 4789                let menu = if completions.is_empty() {
 4790                    None
 4791                } else {
 4792                    let mut menu = CompletionsMenu::new(
 4793                        id,
 4794                        sort_completions,
 4795                        show_completion_documentation,
 4796                        ignore_completion_provider,
 4797                        position,
 4798                        buffer.clone(),
 4799                        completions.into(),
 4800                        snippet_sort_order,
 4801                    );
 4802
 4803                    menu.filter(
 4804                        if filter_completions {
 4805                            query.as_deref()
 4806                        } else {
 4807                            None
 4808                        },
 4809                        cx.background_executor().clone(),
 4810                    )
 4811                    .await;
 4812
 4813                    menu.visible().then_some(menu)
 4814                };
 4815
 4816                editor.update_in(cx, |editor, window, cx| {
 4817                    match editor.context_menu.borrow().as_ref() {
 4818                        None => {}
 4819                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4820                            if prev_menu.id > id {
 4821                                return;
 4822                            }
 4823                        }
 4824                        _ => return,
 4825                    }
 4826
 4827                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4828                        let mut menu = menu.unwrap();
 4829                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4830
 4831                        *editor.context_menu.borrow_mut() =
 4832                            Some(CodeContextMenu::Completions(menu));
 4833
 4834                        if editor.show_edit_predictions_in_menu() {
 4835                            editor.update_visible_inline_completion(window, cx);
 4836                        } else {
 4837                            editor.discard_inline_completion(false, cx);
 4838                        }
 4839
 4840                        cx.notify();
 4841                    } else if editor.completion_tasks.len() <= 1 {
 4842                        // If there are no more completion tasks and the last menu was
 4843                        // empty, we should hide it.
 4844                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4845                        // If it was already hidden and we don't show inline
 4846                        // completions in the menu, we should also show the
 4847                        // inline-completion when available.
 4848                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4849                            editor.update_visible_inline_completion(window, cx);
 4850                        }
 4851                    }
 4852                })?;
 4853
 4854                anyhow::Ok(())
 4855            }
 4856            .log_err()
 4857            .await
 4858        });
 4859
 4860        self.completion_tasks.push((id, task));
 4861    }
 4862
 4863    #[cfg(feature = "test-support")]
 4864    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4865        let menu = self.context_menu.borrow();
 4866        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4867            let completions = menu.completions.borrow();
 4868            Some(completions.to_vec())
 4869        } else {
 4870            None
 4871        }
 4872    }
 4873
 4874    pub fn confirm_completion(
 4875        &mut self,
 4876        action: &ConfirmCompletion,
 4877        window: &mut Window,
 4878        cx: &mut Context<Self>,
 4879    ) -> Option<Task<Result<()>>> {
 4880        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4881        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4882    }
 4883
 4884    pub fn confirm_completion_insert(
 4885        &mut self,
 4886        _: &ConfirmCompletionInsert,
 4887        window: &mut Window,
 4888        cx: &mut Context<Self>,
 4889    ) -> Option<Task<Result<()>>> {
 4890        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4891        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4892    }
 4893
 4894    pub fn confirm_completion_replace(
 4895        &mut self,
 4896        _: &ConfirmCompletionReplace,
 4897        window: &mut Window,
 4898        cx: &mut Context<Self>,
 4899    ) -> Option<Task<Result<()>>> {
 4900        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4901        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4902    }
 4903
 4904    pub fn compose_completion(
 4905        &mut self,
 4906        action: &ComposeCompletion,
 4907        window: &mut Window,
 4908        cx: &mut Context<Self>,
 4909    ) -> Option<Task<Result<()>>> {
 4910        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4911        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4912    }
 4913
 4914    fn do_completion(
 4915        &mut self,
 4916        item_ix: Option<usize>,
 4917        intent: CompletionIntent,
 4918        window: &mut Window,
 4919        cx: &mut Context<Editor>,
 4920    ) -> Option<Task<Result<()>>> {
 4921        use language::ToOffset as _;
 4922
 4923        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4924        else {
 4925            return None;
 4926        };
 4927
 4928        let candidate_id = {
 4929            let entries = completions_menu.entries.borrow();
 4930            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4931            if self.show_edit_predictions_in_menu() {
 4932                self.discard_inline_completion(true, cx);
 4933            }
 4934            mat.candidate_id
 4935        };
 4936
 4937        let buffer_handle = completions_menu.buffer;
 4938        let completion = completions_menu
 4939            .completions
 4940            .borrow()
 4941            .get(candidate_id)?
 4942            .clone();
 4943        cx.stop_propagation();
 4944
 4945        let snippet;
 4946        let new_text;
 4947        if completion.is_snippet() {
 4948            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4949            new_text = snippet.as_ref().unwrap().text.clone();
 4950        } else {
 4951            snippet = None;
 4952            new_text = completion.new_text.clone();
 4953        };
 4954
 4955        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4956        let buffer = buffer_handle.read(cx);
 4957        let snapshot = self.buffer.read(cx).snapshot(cx);
 4958        let replace_range_multibuffer = {
 4959            let excerpt = snapshot
 4960                .excerpt_containing(self.selections.newest_anchor().range())
 4961                .unwrap();
 4962            let multibuffer_anchor = snapshot
 4963                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4964                .unwrap()
 4965                ..snapshot
 4966                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4967                    .unwrap();
 4968            multibuffer_anchor.start.to_offset(&snapshot)
 4969                ..multibuffer_anchor.end.to_offset(&snapshot)
 4970        };
 4971        let newest_anchor = self.selections.newest_anchor();
 4972        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4973            return None;
 4974        }
 4975
 4976        let old_text = buffer
 4977            .text_for_range(replace_range.clone())
 4978            .collect::<String>();
 4979        let lookbehind = newest_anchor
 4980            .start
 4981            .text_anchor
 4982            .to_offset(buffer)
 4983            .saturating_sub(replace_range.start);
 4984        let lookahead = replace_range
 4985            .end
 4986            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4987        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4988        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4989
 4990        let selections = self.selections.all::<usize>(cx);
 4991        let mut ranges = Vec::new();
 4992        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4993
 4994        for selection in &selections {
 4995            let range = if selection.id == newest_anchor.id {
 4996                replace_range_multibuffer.clone()
 4997            } else {
 4998                let mut range = selection.range();
 4999
 5000                // if prefix is present, don't duplicate it
 5001                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5002                    range.start = range.start.saturating_sub(lookbehind);
 5003
 5004                    // if suffix is also present, mimic the newest cursor and replace it
 5005                    if selection.id != newest_anchor.id
 5006                        && snapshot.contains_str_at(range.end, suffix)
 5007                    {
 5008                        range.end += lookahead;
 5009                    }
 5010                }
 5011                range
 5012            };
 5013
 5014            ranges.push(range.clone());
 5015
 5016            if !self.linked_edit_ranges.is_empty() {
 5017                let start_anchor = snapshot.anchor_before(range.start);
 5018                let end_anchor = snapshot.anchor_after(range.end);
 5019                if let Some(ranges) = self
 5020                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5021                {
 5022                    for (buffer, edits) in ranges {
 5023                        linked_edits
 5024                            .entry(buffer.clone())
 5025                            .or_default()
 5026                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5027                    }
 5028                }
 5029            }
 5030        }
 5031
 5032        cx.emit(EditorEvent::InputHandled {
 5033            utf16_range_to_replace: None,
 5034            text: new_text.clone().into(),
 5035        });
 5036
 5037        self.transact(window, cx, |this, window, cx| {
 5038            if let Some(mut snippet) = snippet {
 5039                snippet.text = new_text.to_string();
 5040                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5041            } else {
 5042                this.buffer.update(cx, |buffer, cx| {
 5043                    let auto_indent = match completion.insert_text_mode {
 5044                        Some(InsertTextMode::AS_IS) => None,
 5045                        _ => this.autoindent_mode.clone(),
 5046                    };
 5047                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5048                    buffer.edit(edits, auto_indent, cx);
 5049                });
 5050            }
 5051            for (buffer, edits) in linked_edits {
 5052                buffer.update(cx, |buffer, cx| {
 5053                    let snapshot = buffer.snapshot();
 5054                    let edits = edits
 5055                        .into_iter()
 5056                        .map(|(range, text)| {
 5057                            use text::ToPoint as TP;
 5058                            let end_point = TP::to_point(&range.end, &snapshot);
 5059                            let start_point = TP::to_point(&range.start, &snapshot);
 5060                            (start_point..end_point, text)
 5061                        })
 5062                        .sorted_by_key(|(range, _)| range.start);
 5063                    buffer.edit(edits, None, cx);
 5064                })
 5065            }
 5066
 5067            this.refresh_inline_completion(true, false, window, cx);
 5068        });
 5069
 5070        let show_new_completions_on_confirm = completion
 5071            .confirm
 5072            .as_ref()
 5073            .map_or(false, |confirm| confirm(intent, window, cx));
 5074        if show_new_completions_on_confirm {
 5075            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5076        }
 5077
 5078        let provider = self.completion_provider.as_ref()?;
 5079        drop(completion);
 5080        let apply_edits = provider.apply_additional_edits_for_completion(
 5081            buffer_handle,
 5082            completions_menu.completions.clone(),
 5083            candidate_id,
 5084            true,
 5085            cx,
 5086        );
 5087
 5088        let editor_settings = EditorSettings::get_global(cx);
 5089        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5090            // After the code completion is finished, users often want to know what signatures are needed.
 5091            // so we should automatically call signature_help
 5092            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5093        }
 5094
 5095        Some(cx.foreground_executor().spawn(async move {
 5096            apply_edits.await?;
 5097            Ok(())
 5098        }))
 5099    }
 5100
 5101    pub fn toggle_code_actions(
 5102        &mut self,
 5103        action: &ToggleCodeActions,
 5104        window: &mut Window,
 5105        cx: &mut Context<Self>,
 5106    ) {
 5107        let quick_launch = action.quick_launch;
 5108        let mut context_menu = self.context_menu.borrow_mut();
 5109        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5110            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5111                // Toggle if we're selecting the same one
 5112                *context_menu = None;
 5113                cx.notify();
 5114                return;
 5115            } else {
 5116                // Otherwise, clear it and start a new one
 5117                *context_menu = None;
 5118                cx.notify();
 5119            }
 5120        }
 5121        drop(context_menu);
 5122        let snapshot = self.snapshot(window, cx);
 5123        let deployed_from_indicator = action.deployed_from_indicator;
 5124        let mut task = self.code_actions_task.take();
 5125        let action = action.clone();
 5126        cx.spawn_in(window, async move |editor, cx| {
 5127            while let Some(prev_task) = task {
 5128                prev_task.await.log_err();
 5129                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5130            }
 5131
 5132            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5133                if editor.focus_handle.is_focused(window) {
 5134                    let multibuffer_point = action
 5135                        .deployed_from_indicator
 5136                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5137                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5138                    let (buffer, buffer_row) = snapshot
 5139                        .buffer_snapshot
 5140                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5141                        .and_then(|(buffer_snapshot, range)| {
 5142                            editor
 5143                                .buffer
 5144                                .read(cx)
 5145                                .buffer(buffer_snapshot.remote_id())
 5146                                .map(|buffer| (buffer, range.start.row))
 5147                        })?;
 5148                    let (_, code_actions) = editor
 5149                        .available_code_actions
 5150                        .clone()
 5151                        .and_then(|(location, code_actions)| {
 5152                            let snapshot = location.buffer.read(cx).snapshot();
 5153                            let point_range = location.range.to_point(&snapshot);
 5154                            let point_range = point_range.start.row..=point_range.end.row;
 5155                            if point_range.contains(&buffer_row) {
 5156                                Some((location, code_actions))
 5157                            } else {
 5158                                None
 5159                            }
 5160                        })
 5161                        .unzip();
 5162                    let buffer_id = buffer.read(cx).remote_id();
 5163                    let tasks = editor
 5164                        .tasks
 5165                        .get(&(buffer_id, buffer_row))
 5166                        .map(|t| Arc::new(t.to_owned()));
 5167                    if tasks.is_none() && code_actions.is_none() {
 5168                        return None;
 5169                    }
 5170
 5171                    editor.completion_tasks.clear();
 5172                    editor.discard_inline_completion(false, cx);
 5173                    let task_context =
 5174                        tasks
 5175                            .as_ref()
 5176                            .zip(editor.project.clone())
 5177                            .map(|(tasks, project)| {
 5178                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5179                            });
 5180
 5181                    Some(cx.spawn_in(window, async move |editor, cx| {
 5182                        let task_context = match task_context {
 5183                            Some(task_context) => task_context.await,
 5184                            None => None,
 5185                        };
 5186                        let resolved_tasks =
 5187                            tasks
 5188                                .zip(task_context.clone())
 5189                                .map(|(tasks, task_context)| ResolvedTasks {
 5190                                    templates: tasks.resolve(&task_context).collect(),
 5191                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5192                                        multibuffer_point.row,
 5193                                        tasks.column,
 5194                                    )),
 5195                                });
 5196                        let spawn_straight_away = quick_launch
 5197                            && resolved_tasks
 5198                                .as_ref()
 5199                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5200                            && code_actions
 5201                                .as_ref()
 5202                                .map_or(true, |actions| actions.is_empty());
 5203                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5204                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5205                                maybe!({
 5206                                    let project = editor.project.as_ref()?;
 5207                                    let dap_store = project.read(cx).dap_store();
 5208                                    let mut scenarios = vec![];
 5209                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5210                                    let debug_adapter: SharedString = buffer
 5211                                        .read(cx)
 5212                                        .language()?
 5213                                        .context_provider()?
 5214                                        .debug_adapter()?
 5215                                        .into();
 5216                                    dap_store.update(cx, |this, cx| {
 5217                                        for (_, task) in &resolved_tasks.templates {
 5218                                            if let Some(scenario) = this
 5219                                                .debug_scenario_for_build_task(
 5220                                                    task.resolved.clone(),
 5221                                                    SharedString::from(
 5222                                                        task.original_task().label.clone(),
 5223                                                    ),
 5224                                                    debug_adapter.clone(),
 5225                                                    cx,
 5226                                                )
 5227                                            {
 5228                                                scenarios.push(scenario);
 5229                                            }
 5230                                        }
 5231                                    });
 5232                                    Some(scenarios)
 5233                                })
 5234                                .unwrap_or_default()
 5235                            } else {
 5236                                vec![]
 5237                            }
 5238                        })?;
 5239                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5240                            *editor.context_menu.borrow_mut() =
 5241                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5242                                    buffer,
 5243                                    actions: CodeActionContents::new(
 5244                                        resolved_tasks,
 5245                                        code_actions,
 5246                                        debug_scenarios,
 5247                                        task_context.unwrap_or_default(),
 5248                                    ),
 5249                                    selected_item: Default::default(),
 5250                                    scroll_handle: UniformListScrollHandle::default(),
 5251                                    deployed_from_indicator,
 5252                                }));
 5253                            if spawn_straight_away {
 5254                                if let Some(task) = editor.confirm_code_action(
 5255                                    &ConfirmCodeAction { item_ix: Some(0) },
 5256                                    window,
 5257                                    cx,
 5258                                ) {
 5259                                    cx.notify();
 5260                                    return task;
 5261                                }
 5262                            }
 5263                            cx.notify();
 5264                            Task::ready(Ok(()))
 5265                        }) {
 5266                            task.await
 5267                        } else {
 5268                            Ok(())
 5269                        }
 5270                    }))
 5271                } else {
 5272                    Some(Task::ready(Ok(())))
 5273                }
 5274            })?;
 5275            if let Some(task) = spawned_test_task {
 5276                task.await?;
 5277            }
 5278
 5279            Ok::<_, anyhow::Error>(())
 5280        })
 5281        .detach_and_log_err(cx);
 5282    }
 5283
 5284    pub fn confirm_code_action(
 5285        &mut self,
 5286        action: &ConfirmCodeAction,
 5287        window: &mut Window,
 5288        cx: &mut Context<Self>,
 5289    ) -> Option<Task<Result<()>>> {
 5290        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5291
 5292        let actions_menu =
 5293            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5294                menu
 5295            } else {
 5296                return None;
 5297            };
 5298
 5299        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5300        let action = actions_menu.actions.get(action_ix)?;
 5301        let title = action.label();
 5302        let buffer = actions_menu.buffer;
 5303        let workspace = self.workspace()?;
 5304
 5305        match action {
 5306            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5307                workspace.update(cx, |workspace, cx| {
 5308                    workspace.schedule_resolved_task(
 5309                        task_source_kind,
 5310                        resolved_task,
 5311                        false,
 5312                        window,
 5313                        cx,
 5314                    );
 5315
 5316                    Some(Task::ready(Ok(())))
 5317                })
 5318            }
 5319            CodeActionsItem::CodeAction {
 5320                excerpt_id,
 5321                action,
 5322                provider,
 5323            } => {
 5324                let apply_code_action =
 5325                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5326                let workspace = workspace.downgrade();
 5327                Some(cx.spawn_in(window, async move |editor, cx| {
 5328                    let project_transaction = apply_code_action.await?;
 5329                    Self::open_project_transaction(
 5330                        &editor,
 5331                        workspace,
 5332                        project_transaction,
 5333                        title,
 5334                        cx,
 5335                    )
 5336                    .await
 5337                }))
 5338            }
 5339            CodeActionsItem::DebugScenario(scenario) => {
 5340                let context = actions_menu.actions.context.clone();
 5341
 5342                workspace.update(cx, |workspace, cx| {
 5343                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5344                });
 5345                Some(Task::ready(Ok(())))
 5346            }
 5347        }
 5348    }
 5349
 5350    pub async fn open_project_transaction(
 5351        this: &WeakEntity<Editor>,
 5352        workspace: WeakEntity<Workspace>,
 5353        transaction: ProjectTransaction,
 5354        title: String,
 5355        cx: &mut AsyncWindowContext,
 5356    ) -> Result<()> {
 5357        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5358        cx.update(|_, cx| {
 5359            entries.sort_unstable_by_key(|(buffer, _)| {
 5360                buffer.read(cx).file().map(|f| f.path().clone())
 5361            });
 5362        })?;
 5363
 5364        // If the project transaction's edits are all contained within this editor, then
 5365        // avoid opening a new editor to display them.
 5366
 5367        if let Some((buffer, transaction)) = entries.first() {
 5368            if entries.len() == 1 {
 5369                let excerpt = this.update(cx, |editor, cx| {
 5370                    editor
 5371                        .buffer()
 5372                        .read(cx)
 5373                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5374                })?;
 5375                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5376                    if excerpted_buffer == *buffer {
 5377                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5378                            let excerpt_range = excerpt_range.to_offset(buffer);
 5379                            buffer
 5380                                .edited_ranges_for_transaction::<usize>(transaction)
 5381                                .all(|range| {
 5382                                    excerpt_range.start <= range.start
 5383                                        && excerpt_range.end >= range.end
 5384                                })
 5385                        })?;
 5386
 5387                        if all_edits_within_excerpt {
 5388                            return Ok(());
 5389                        }
 5390                    }
 5391                }
 5392            }
 5393        } else {
 5394            return Ok(());
 5395        }
 5396
 5397        let mut ranges_to_highlight = Vec::new();
 5398        let excerpt_buffer = cx.new(|cx| {
 5399            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5400            for (buffer_handle, transaction) in &entries {
 5401                let edited_ranges = buffer_handle
 5402                    .read(cx)
 5403                    .edited_ranges_for_transaction::<Point>(transaction)
 5404                    .collect::<Vec<_>>();
 5405                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5406                    PathKey::for_buffer(buffer_handle, cx),
 5407                    buffer_handle.clone(),
 5408                    edited_ranges,
 5409                    DEFAULT_MULTIBUFFER_CONTEXT,
 5410                    cx,
 5411                );
 5412
 5413                ranges_to_highlight.extend(ranges);
 5414            }
 5415            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5416            multibuffer
 5417        })?;
 5418
 5419        workspace.update_in(cx, |workspace, window, cx| {
 5420            let project = workspace.project().clone();
 5421            let editor =
 5422                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5423            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5424            editor.update(cx, |editor, cx| {
 5425                editor.highlight_background::<Self>(
 5426                    &ranges_to_highlight,
 5427                    |theme| theme.editor_highlighted_line_background,
 5428                    cx,
 5429                );
 5430            });
 5431        })?;
 5432
 5433        Ok(())
 5434    }
 5435
 5436    pub fn clear_code_action_providers(&mut self) {
 5437        self.code_action_providers.clear();
 5438        self.available_code_actions.take();
 5439    }
 5440
 5441    pub fn add_code_action_provider(
 5442        &mut self,
 5443        provider: Rc<dyn CodeActionProvider>,
 5444        window: &mut Window,
 5445        cx: &mut Context<Self>,
 5446    ) {
 5447        if self
 5448            .code_action_providers
 5449            .iter()
 5450            .any(|existing_provider| existing_provider.id() == provider.id())
 5451        {
 5452            return;
 5453        }
 5454
 5455        self.code_action_providers.push(provider);
 5456        self.refresh_code_actions(window, cx);
 5457    }
 5458
 5459    pub fn remove_code_action_provider(
 5460        &mut self,
 5461        id: Arc<str>,
 5462        window: &mut Window,
 5463        cx: &mut Context<Self>,
 5464    ) {
 5465        self.code_action_providers
 5466            .retain(|provider| provider.id() != id);
 5467        self.refresh_code_actions(window, cx);
 5468    }
 5469
 5470    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5471        let newest_selection = self.selections.newest_anchor().clone();
 5472        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5473        let buffer = self.buffer.read(cx);
 5474        if newest_selection.head().diff_base_anchor.is_some() {
 5475            return None;
 5476        }
 5477        let (start_buffer, start) =
 5478            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5479        let (end_buffer, end) =
 5480            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5481        if start_buffer != end_buffer {
 5482            return None;
 5483        }
 5484
 5485        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5486            cx.background_executor()
 5487                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5488                .await;
 5489
 5490            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5491                let providers = this.code_action_providers.clone();
 5492                let tasks = this
 5493                    .code_action_providers
 5494                    .iter()
 5495                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5496                    .collect::<Vec<_>>();
 5497                (providers, tasks)
 5498            })?;
 5499
 5500            let mut actions = Vec::new();
 5501            for (provider, provider_actions) in
 5502                providers.into_iter().zip(future::join_all(tasks).await)
 5503            {
 5504                if let Some(provider_actions) = provider_actions.log_err() {
 5505                    actions.extend(provider_actions.into_iter().map(|action| {
 5506                        AvailableCodeAction {
 5507                            excerpt_id: newest_selection.start.excerpt_id,
 5508                            action,
 5509                            provider: provider.clone(),
 5510                        }
 5511                    }));
 5512                }
 5513            }
 5514
 5515            this.update(cx, |this, cx| {
 5516                this.available_code_actions = if actions.is_empty() {
 5517                    None
 5518                } else {
 5519                    Some((
 5520                        Location {
 5521                            buffer: start_buffer,
 5522                            range: start..end,
 5523                        },
 5524                        actions.into(),
 5525                    ))
 5526                };
 5527                cx.notify();
 5528            })
 5529        }));
 5530        None
 5531    }
 5532
 5533    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5534        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5535            self.show_git_blame_inline = false;
 5536
 5537            self.show_git_blame_inline_delay_task =
 5538                Some(cx.spawn_in(window, async move |this, cx| {
 5539                    cx.background_executor().timer(delay).await;
 5540
 5541                    this.update(cx, |this, cx| {
 5542                        this.show_git_blame_inline = true;
 5543                        cx.notify();
 5544                    })
 5545                    .log_err();
 5546                }));
 5547        }
 5548    }
 5549
 5550    fn show_blame_popover(
 5551        &mut self,
 5552        blame_entry: &BlameEntry,
 5553        position: gpui::Point<Pixels>,
 5554        cx: &mut Context<Self>,
 5555    ) {
 5556        if let Some(state) = &mut self.inline_blame_popover {
 5557            state.hide_task.take();
 5558            cx.notify();
 5559        } else {
 5560            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5561            let show_task = cx.spawn(async move |editor, cx| {
 5562                cx.background_executor()
 5563                    .timer(std::time::Duration::from_millis(delay))
 5564                    .await;
 5565                editor
 5566                    .update(cx, |editor, cx| {
 5567                        if let Some(state) = &mut editor.inline_blame_popover {
 5568                            state.show_task = None;
 5569                            cx.notify();
 5570                        }
 5571                    })
 5572                    .ok();
 5573            });
 5574            let Some(blame) = self.blame.as_ref() else {
 5575                return;
 5576            };
 5577            let blame = blame.read(cx);
 5578            let details = blame.details_for_entry(&blame_entry);
 5579            let markdown = cx.new(|cx| {
 5580                Markdown::new(
 5581                    details
 5582                        .as_ref()
 5583                        .map(|message| message.message.clone())
 5584                        .unwrap_or_default(),
 5585                    None,
 5586                    None,
 5587                    cx,
 5588                )
 5589            });
 5590            self.inline_blame_popover = Some(InlineBlamePopover {
 5591                position,
 5592                show_task: Some(show_task),
 5593                hide_task: None,
 5594                popover_bounds: None,
 5595                popover_state: InlineBlamePopoverState {
 5596                    scroll_handle: ScrollHandle::new(),
 5597                    commit_message: details,
 5598                    markdown,
 5599                },
 5600            });
 5601        }
 5602    }
 5603
 5604    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5605        if let Some(state) = &mut self.inline_blame_popover {
 5606            if state.show_task.is_some() {
 5607                self.inline_blame_popover.take();
 5608                cx.notify();
 5609            } else {
 5610                let hide_task = cx.spawn(async move |editor, cx| {
 5611                    cx.background_executor()
 5612                        .timer(std::time::Duration::from_millis(100))
 5613                        .await;
 5614                    editor
 5615                        .update(cx, |editor, cx| {
 5616                            editor.inline_blame_popover.take();
 5617                            cx.notify();
 5618                        })
 5619                        .ok();
 5620                });
 5621                state.hide_task = Some(hide_task);
 5622            }
 5623        }
 5624    }
 5625
 5626    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5627        if self.pending_rename.is_some() {
 5628            return None;
 5629        }
 5630
 5631        let provider = self.semantics_provider.clone()?;
 5632        let buffer = self.buffer.read(cx);
 5633        let newest_selection = self.selections.newest_anchor().clone();
 5634        let cursor_position = newest_selection.head();
 5635        let (cursor_buffer, cursor_buffer_position) =
 5636            buffer.text_anchor_for_position(cursor_position, cx)?;
 5637        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5638        if cursor_buffer != tail_buffer {
 5639            return None;
 5640        }
 5641        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5642        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5643            cx.background_executor()
 5644                .timer(Duration::from_millis(debounce))
 5645                .await;
 5646
 5647            let highlights = if let Some(highlights) = cx
 5648                .update(|cx| {
 5649                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5650                })
 5651                .ok()
 5652                .flatten()
 5653            {
 5654                highlights.await.log_err()
 5655            } else {
 5656                None
 5657            };
 5658
 5659            if let Some(highlights) = highlights {
 5660                this.update(cx, |this, cx| {
 5661                    if this.pending_rename.is_some() {
 5662                        return;
 5663                    }
 5664
 5665                    let buffer_id = cursor_position.buffer_id;
 5666                    let buffer = this.buffer.read(cx);
 5667                    if !buffer
 5668                        .text_anchor_for_position(cursor_position, cx)
 5669                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5670                    {
 5671                        return;
 5672                    }
 5673
 5674                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5675                    let mut write_ranges = Vec::new();
 5676                    let mut read_ranges = Vec::new();
 5677                    for highlight in highlights {
 5678                        for (excerpt_id, excerpt_range) in
 5679                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5680                        {
 5681                            let start = highlight
 5682                                .range
 5683                                .start
 5684                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5685                            let end = highlight
 5686                                .range
 5687                                .end
 5688                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5689                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5690                                continue;
 5691                            }
 5692
 5693                            let range = Anchor {
 5694                                buffer_id,
 5695                                excerpt_id,
 5696                                text_anchor: start,
 5697                                diff_base_anchor: None,
 5698                            }..Anchor {
 5699                                buffer_id,
 5700                                excerpt_id,
 5701                                text_anchor: end,
 5702                                diff_base_anchor: None,
 5703                            };
 5704                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5705                                write_ranges.push(range);
 5706                            } else {
 5707                                read_ranges.push(range);
 5708                            }
 5709                        }
 5710                    }
 5711
 5712                    this.highlight_background::<DocumentHighlightRead>(
 5713                        &read_ranges,
 5714                        |theme| theme.editor_document_highlight_read_background,
 5715                        cx,
 5716                    );
 5717                    this.highlight_background::<DocumentHighlightWrite>(
 5718                        &write_ranges,
 5719                        |theme| theme.editor_document_highlight_write_background,
 5720                        cx,
 5721                    );
 5722                    cx.notify();
 5723                })
 5724                .log_err();
 5725            }
 5726        }));
 5727        None
 5728    }
 5729
 5730    fn prepare_highlight_query_from_selection(
 5731        &mut self,
 5732        cx: &mut Context<Editor>,
 5733    ) -> Option<(String, Range<Anchor>)> {
 5734        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5735            return None;
 5736        }
 5737        if !EditorSettings::get_global(cx).selection_highlight {
 5738            return None;
 5739        }
 5740        if self.selections.count() != 1 || self.selections.line_mode {
 5741            return None;
 5742        }
 5743        let selection = self.selections.newest::<Point>(cx);
 5744        if selection.is_empty() || selection.start.row != selection.end.row {
 5745            return None;
 5746        }
 5747        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5748        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5749        let query = multi_buffer_snapshot
 5750            .text_for_range(selection_anchor_range.clone())
 5751            .collect::<String>();
 5752        if query.trim().is_empty() {
 5753            return None;
 5754        }
 5755        Some((query, selection_anchor_range))
 5756    }
 5757
 5758    fn update_selection_occurrence_highlights(
 5759        &mut self,
 5760        query_text: String,
 5761        query_range: Range<Anchor>,
 5762        multi_buffer_range_to_query: Range<Point>,
 5763        use_debounce: bool,
 5764        window: &mut Window,
 5765        cx: &mut Context<Editor>,
 5766    ) -> Task<()> {
 5767        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5768        cx.spawn_in(window, async move |editor, cx| {
 5769            if use_debounce {
 5770                cx.background_executor()
 5771                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5772                    .await;
 5773            }
 5774            let match_task = cx.background_spawn(async move {
 5775                let buffer_ranges = multi_buffer_snapshot
 5776                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5777                    .into_iter()
 5778                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5779                let mut match_ranges = Vec::new();
 5780                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5781                    match_ranges.extend(
 5782                        project::search::SearchQuery::text(
 5783                            query_text.clone(),
 5784                            false,
 5785                            false,
 5786                            false,
 5787                            Default::default(),
 5788                            Default::default(),
 5789                            false,
 5790                            None,
 5791                        )
 5792                        .unwrap()
 5793                        .search(&buffer_snapshot, Some(search_range.clone()))
 5794                        .await
 5795                        .into_iter()
 5796                        .filter_map(|match_range| {
 5797                            let match_start = buffer_snapshot
 5798                                .anchor_after(search_range.start + match_range.start);
 5799                            let match_end =
 5800                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5801                            let match_anchor_range = Anchor::range_in_buffer(
 5802                                excerpt_id,
 5803                                buffer_snapshot.remote_id(),
 5804                                match_start..match_end,
 5805                            );
 5806                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5807                        }),
 5808                    );
 5809                }
 5810                match_ranges
 5811            });
 5812            let match_ranges = match_task.await;
 5813            editor
 5814                .update_in(cx, |editor, _, cx| {
 5815                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5816                    if !match_ranges.is_empty() {
 5817                        editor.highlight_background::<SelectedTextHighlight>(
 5818                            &match_ranges,
 5819                            |theme| theme.editor_document_highlight_bracket_background,
 5820                            cx,
 5821                        )
 5822                    }
 5823                })
 5824                .log_err();
 5825        })
 5826    }
 5827
 5828    fn refresh_selected_text_highlights(
 5829        &mut self,
 5830        on_buffer_edit: bool,
 5831        window: &mut Window,
 5832        cx: &mut Context<Editor>,
 5833    ) {
 5834        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5835        else {
 5836            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5837            self.quick_selection_highlight_task.take();
 5838            self.debounced_selection_highlight_task.take();
 5839            return;
 5840        };
 5841        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5842        if on_buffer_edit
 5843            || self
 5844                .quick_selection_highlight_task
 5845                .as_ref()
 5846                .map_or(true, |(prev_anchor_range, _)| {
 5847                    prev_anchor_range != &query_range
 5848                })
 5849        {
 5850            let multi_buffer_visible_start = self
 5851                .scroll_manager
 5852                .anchor()
 5853                .anchor
 5854                .to_point(&multi_buffer_snapshot);
 5855            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5856                multi_buffer_visible_start
 5857                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5858                Bias::Left,
 5859            );
 5860            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5861            self.quick_selection_highlight_task = Some((
 5862                query_range.clone(),
 5863                self.update_selection_occurrence_highlights(
 5864                    query_text.clone(),
 5865                    query_range.clone(),
 5866                    multi_buffer_visible_range,
 5867                    false,
 5868                    window,
 5869                    cx,
 5870                ),
 5871            ));
 5872        }
 5873        if on_buffer_edit
 5874            || self
 5875                .debounced_selection_highlight_task
 5876                .as_ref()
 5877                .map_or(true, |(prev_anchor_range, _)| {
 5878                    prev_anchor_range != &query_range
 5879                })
 5880        {
 5881            let multi_buffer_start = multi_buffer_snapshot
 5882                .anchor_before(0)
 5883                .to_point(&multi_buffer_snapshot);
 5884            let multi_buffer_end = multi_buffer_snapshot
 5885                .anchor_after(multi_buffer_snapshot.len())
 5886                .to_point(&multi_buffer_snapshot);
 5887            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5888            self.debounced_selection_highlight_task = Some((
 5889                query_range.clone(),
 5890                self.update_selection_occurrence_highlights(
 5891                    query_text,
 5892                    query_range,
 5893                    multi_buffer_full_range,
 5894                    true,
 5895                    window,
 5896                    cx,
 5897                ),
 5898            ));
 5899        }
 5900    }
 5901
 5902    pub fn refresh_inline_completion(
 5903        &mut self,
 5904        debounce: bool,
 5905        user_requested: bool,
 5906        window: &mut Window,
 5907        cx: &mut Context<Self>,
 5908    ) -> Option<()> {
 5909        let provider = self.edit_prediction_provider()?;
 5910        let cursor = self.selections.newest_anchor().head();
 5911        let (buffer, cursor_buffer_position) =
 5912            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5913
 5914        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5915            self.discard_inline_completion(false, cx);
 5916            return None;
 5917        }
 5918
 5919        if !user_requested
 5920            && (!self.should_show_edit_predictions()
 5921                || !self.is_focused(window)
 5922                || buffer.read(cx).is_empty())
 5923        {
 5924            self.discard_inline_completion(false, cx);
 5925            return None;
 5926        }
 5927
 5928        self.update_visible_inline_completion(window, cx);
 5929        provider.refresh(
 5930            self.project.clone(),
 5931            buffer,
 5932            cursor_buffer_position,
 5933            debounce,
 5934            cx,
 5935        );
 5936        Some(())
 5937    }
 5938
 5939    fn show_edit_predictions_in_menu(&self) -> bool {
 5940        match self.edit_prediction_settings {
 5941            EditPredictionSettings::Disabled => false,
 5942            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5943        }
 5944    }
 5945
 5946    pub fn edit_predictions_enabled(&self) -> bool {
 5947        match self.edit_prediction_settings {
 5948            EditPredictionSettings::Disabled => false,
 5949            EditPredictionSettings::Enabled { .. } => true,
 5950        }
 5951    }
 5952
 5953    fn edit_prediction_requires_modifier(&self) -> bool {
 5954        match self.edit_prediction_settings {
 5955            EditPredictionSettings::Disabled => false,
 5956            EditPredictionSettings::Enabled {
 5957                preview_requires_modifier,
 5958                ..
 5959            } => preview_requires_modifier,
 5960        }
 5961    }
 5962
 5963    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5964        if self.edit_prediction_provider.is_none() {
 5965            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5966        } else {
 5967            let selection = self.selections.newest_anchor();
 5968            let cursor = selection.head();
 5969
 5970            if let Some((buffer, cursor_buffer_position)) =
 5971                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5972            {
 5973                self.edit_prediction_settings =
 5974                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5975            }
 5976        }
 5977    }
 5978
 5979    fn edit_prediction_settings_at_position(
 5980        &self,
 5981        buffer: &Entity<Buffer>,
 5982        buffer_position: language::Anchor,
 5983        cx: &App,
 5984    ) -> EditPredictionSettings {
 5985        if !self.mode.is_full()
 5986            || !self.show_inline_completions_override.unwrap_or(true)
 5987            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5988        {
 5989            return EditPredictionSettings::Disabled;
 5990        }
 5991
 5992        let buffer = buffer.read(cx);
 5993
 5994        let file = buffer.file();
 5995
 5996        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5997            return EditPredictionSettings::Disabled;
 5998        };
 5999
 6000        let by_provider = matches!(
 6001            self.menu_inline_completions_policy,
 6002            MenuInlineCompletionsPolicy::ByProvider
 6003        );
 6004
 6005        let show_in_menu = by_provider
 6006            && self
 6007                .edit_prediction_provider
 6008                .as_ref()
 6009                .map_or(false, |provider| {
 6010                    provider.provider.show_completions_in_menu()
 6011                });
 6012
 6013        let preview_requires_modifier =
 6014            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6015
 6016        EditPredictionSettings::Enabled {
 6017            show_in_menu,
 6018            preview_requires_modifier,
 6019        }
 6020    }
 6021
 6022    fn should_show_edit_predictions(&self) -> bool {
 6023        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6024    }
 6025
 6026    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6027        matches!(
 6028            self.edit_prediction_preview,
 6029            EditPredictionPreview::Active { .. }
 6030        )
 6031    }
 6032
 6033    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6034        let cursor = self.selections.newest_anchor().head();
 6035        if let Some((buffer, cursor_position)) =
 6036            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6037        {
 6038            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6039        } else {
 6040            false
 6041        }
 6042    }
 6043
 6044    fn edit_predictions_enabled_in_buffer(
 6045        &self,
 6046        buffer: &Entity<Buffer>,
 6047        buffer_position: language::Anchor,
 6048        cx: &App,
 6049    ) -> bool {
 6050        maybe!({
 6051            if self.read_only(cx) {
 6052                return Some(false);
 6053            }
 6054            let provider = self.edit_prediction_provider()?;
 6055            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6056                return Some(false);
 6057            }
 6058            let buffer = buffer.read(cx);
 6059            let Some(file) = buffer.file() else {
 6060                return Some(true);
 6061            };
 6062            let settings = all_language_settings(Some(file), cx);
 6063            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6064        })
 6065        .unwrap_or(false)
 6066    }
 6067
 6068    fn cycle_inline_completion(
 6069        &mut self,
 6070        direction: Direction,
 6071        window: &mut Window,
 6072        cx: &mut Context<Self>,
 6073    ) -> Option<()> {
 6074        let provider = self.edit_prediction_provider()?;
 6075        let cursor = self.selections.newest_anchor().head();
 6076        let (buffer, cursor_buffer_position) =
 6077            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6078        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6079            return None;
 6080        }
 6081
 6082        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6083        self.update_visible_inline_completion(window, cx);
 6084
 6085        Some(())
 6086    }
 6087
 6088    pub fn show_inline_completion(
 6089        &mut self,
 6090        _: &ShowEditPrediction,
 6091        window: &mut Window,
 6092        cx: &mut Context<Self>,
 6093    ) {
 6094        if !self.has_active_inline_completion() {
 6095            self.refresh_inline_completion(false, true, window, cx);
 6096            return;
 6097        }
 6098
 6099        self.update_visible_inline_completion(window, cx);
 6100    }
 6101
 6102    pub fn display_cursor_names(
 6103        &mut self,
 6104        _: &DisplayCursorNames,
 6105        window: &mut Window,
 6106        cx: &mut Context<Self>,
 6107    ) {
 6108        self.show_cursor_names(window, cx);
 6109    }
 6110
 6111    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6112        self.show_cursor_names = true;
 6113        cx.notify();
 6114        cx.spawn_in(window, async move |this, cx| {
 6115            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6116            this.update(cx, |this, cx| {
 6117                this.show_cursor_names = false;
 6118                cx.notify()
 6119            })
 6120            .ok()
 6121        })
 6122        .detach();
 6123    }
 6124
 6125    pub fn next_edit_prediction(
 6126        &mut self,
 6127        _: &NextEditPrediction,
 6128        window: &mut Window,
 6129        cx: &mut Context<Self>,
 6130    ) {
 6131        if self.has_active_inline_completion() {
 6132            self.cycle_inline_completion(Direction::Next, window, cx);
 6133        } else {
 6134            let is_copilot_disabled = self
 6135                .refresh_inline_completion(false, true, window, cx)
 6136                .is_none();
 6137            if is_copilot_disabled {
 6138                cx.propagate();
 6139            }
 6140        }
 6141    }
 6142
 6143    pub fn previous_edit_prediction(
 6144        &mut self,
 6145        _: &PreviousEditPrediction,
 6146        window: &mut Window,
 6147        cx: &mut Context<Self>,
 6148    ) {
 6149        if self.has_active_inline_completion() {
 6150            self.cycle_inline_completion(Direction::Prev, window, cx);
 6151        } else {
 6152            let is_copilot_disabled = self
 6153                .refresh_inline_completion(false, true, window, cx)
 6154                .is_none();
 6155            if is_copilot_disabled {
 6156                cx.propagate();
 6157            }
 6158        }
 6159    }
 6160
 6161    pub fn accept_edit_prediction(
 6162        &mut self,
 6163        _: &AcceptEditPrediction,
 6164        window: &mut Window,
 6165        cx: &mut Context<Self>,
 6166    ) {
 6167        if self.show_edit_predictions_in_menu() {
 6168            self.hide_context_menu(window, cx);
 6169        }
 6170
 6171        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6172            return;
 6173        };
 6174
 6175        self.report_inline_completion_event(
 6176            active_inline_completion.completion_id.clone(),
 6177            true,
 6178            cx,
 6179        );
 6180
 6181        match &active_inline_completion.completion {
 6182            InlineCompletion::Move { target, .. } => {
 6183                let target = *target;
 6184
 6185                if let Some(position_map) = &self.last_position_map {
 6186                    if position_map
 6187                        .visible_row_range
 6188                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6189                        || !self.edit_prediction_requires_modifier()
 6190                    {
 6191                        self.unfold_ranges(&[target..target], true, false, cx);
 6192                        // Note that this is also done in vim's handler of the Tab action.
 6193                        self.change_selections(
 6194                            Some(Autoscroll::newest()),
 6195                            window,
 6196                            cx,
 6197                            |selections| {
 6198                                selections.select_anchor_ranges([target..target]);
 6199                            },
 6200                        );
 6201                        self.clear_row_highlights::<EditPredictionPreview>();
 6202
 6203                        self.edit_prediction_preview
 6204                            .set_previous_scroll_position(None);
 6205                    } else {
 6206                        self.edit_prediction_preview
 6207                            .set_previous_scroll_position(Some(
 6208                                position_map.snapshot.scroll_anchor,
 6209                            ));
 6210
 6211                        self.highlight_rows::<EditPredictionPreview>(
 6212                            target..target,
 6213                            cx.theme().colors().editor_highlighted_line_background,
 6214                            RowHighlightOptions {
 6215                                autoscroll: true,
 6216                                ..Default::default()
 6217                            },
 6218                            cx,
 6219                        );
 6220                        self.request_autoscroll(Autoscroll::fit(), cx);
 6221                    }
 6222                }
 6223            }
 6224            InlineCompletion::Edit { edits, .. } => {
 6225                if let Some(provider) = self.edit_prediction_provider() {
 6226                    provider.accept(cx);
 6227                }
 6228
 6229                let snapshot = self.buffer.read(cx).snapshot(cx);
 6230                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6231
 6232                self.buffer.update(cx, |buffer, cx| {
 6233                    buffer.edit(edits.iter().cloned(), None, cx)
 6234                });
 6235
 6236                self.change_selections(None, window, cx, |s| {
 6237                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6238                });
 6239
 6240                self.update_visible_inline_completion(window, cx);
 6241                if self.active_inline_completion.is_none() {
 6242                    self.refresh_inline_completion(true, true, window, cx);
 6243                }
 6244
 6245                cx.notify();
 6246            }
 6247        }
 6248
 6249        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6250    }
 6251
 6252    pub fn accept_partial_inline_completion(
 6253        &mut self,
 6254        _: &AcceptPartialEditPrediction,
 6255        window: &mut Window,
 6256        cx: &mut Context<Self>,
 6257    ) {
 6258        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6259            return;
 6260        };
 6261        if self.selections.count() != 1 {
 6262            return;
 6263        }
 6264
 6265        self.report_inline_completion_event(
 6266            active_inline_completion.completion_id.clone(),
 6267            true,
 6268            cx,
 6269        );
 6270
 6271        match &active_inline_completion.completion {
 6272            InlineCompletion::Move { target, .. } => {
 6273                let target = *target;
 6274                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6275                    selections.select_anchor_ranges([target..target]);
 6276                });
 6277            }
 6278            InlineCompletion::Edit { edits, .. } => {
 6279                // Find an insertion that starts at the cursor position.
 6280                let snapshot = self.buffer.read(cx).snapshot(cx);
 6281                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6282                let insertion = edits.iter().find_map(|(range, text)| {
 6283                    let range = range.to_offset(&snapshot);
 6284                    if range.is_empty() && range.start == cursor_offset {
 6285                        Some(text)
 6286                    } else {
 6287                        None
 6288                    }
 6289                });
 6290
 6291                if let Some(text) = insertion {
 6292                    let mut partial_completion = text
 6293                        .chars()
 6294                        .by_ref()
 6295                        .take_while(|c| c.is_alphabetic())
 6296                        .collect::<String>();
 6297                    if partial_completion.is_empty() {
 6298                        partial_completion = text
 6299                            .chars()
 6300                            .by_ref()
 6301                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6302                            .collect::<String>();
 6303                    }
 6304
 6305                    cx.emit(EditorEvent::InputHandled {
 6306                        utf16_range_to_replace: None,
 6307                        text: partial_completion.clone().into(),
 6308                    });
 6309
 6310                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6311
 6312                    self.refresh_inline_completion(true, true, window, cx);
 6313                    cx.notify();
 6314                } else {
 6315                    self.accept_edit_prediction(&Default::default(), window, cx);
 6316                }
 6317            }
 6318        }
 6319    }
 6320
 6321    fn discard_inline_completion(
 6322        &mut self,
 6323        should_report_inline_completion_event: bool,
 6324        cx: &mut Context<Self>,
 6325    ) -> bool {
 6326        if should_report_inline_completion_event {
 6327            let completion_id = self
 6328                .active_inline_completion
 6329                .as_ref()
 6330                .and_then(|active_completion| active_completion.completion_id.clone());
 6331
 6332            self.report_inline_completion_event(completion_id, false, cx);
 6333        }
 6334
 6335        if let Some(provider) = self.edit_prediction_provider() {
 6336            provider.discard(cx);
 6337        }
 6338
 6339        self.take_active_inline_completion(cx)
 6340    }
 6341
 6342    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6343        let Some(provider) = self.edit_prediction_provider() else {
 6344            return;
 6345        };
 6346
 6347        let Some((_, buffer, _)) = self
 6348            .buffer
 6349            .read(cx)
 6350            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6351        else {
 6352            return;
 6353        };
 6354
 6355        let extension = buffer
 6356            .read(cx)
 6357            .file()
 6358            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6359
 6360        let event_type = match accepted {
 6361            true => "Edit Prediction Accepted",
 6362            false => "Edit Prediction Discarded",
 6363        };
 6364        telemetry::event!(
 6365            event_type,
 6366            provider = provider.name(),
 6367            prediction_id = id,
 6368            suggestion_accepted = accepted,
 6369            file_extension = extension,
 6370        );
 6371    }
 6372
 6373    pub fn has_active_inline_completion(&self) -> bool {
 6374        self.active_inline_completion.is_some()
 6375    }
 6376
 6377    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6378        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6379            return false;
 6380        };
 6381
 6382        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6383        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6384        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6385        true
 6386    }
 6387
 6388    /// Returns true when we're displaying the edit prediction popover below the cursor
 6389    /// like we are not previewing and the LSP autocomplete menu is visible
 6390    /// or we are in `when_holding_modifier` mode.
 6391    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6392        if self.edit_prediction_preview_is_active()
 6393            || !self.show_edit_predictions_in_menu()
 6394            || !self.edit_predictions_enabled()
 6395        {
 6396            return false;
 6397        }
 6398
 6399        if self.has_visible_completions_menu() {
 6400            return true;
 6401        }
 6402
 6403        has_completion && self.edit_prediction_requires_modifier()
 6404    }
 6405
 6406    fn handle_modifiers_changed(
 6407        &mut self,
 6408        modifiers: Modifiers,
 6409        position_map: &PositionMap,
 6410        window: &mut Window,
 6411        cx: &mut Context<Self>,
 6412    ) {
 6413        if self.show_edit_predictions_in_menu() {
 6414            self.update_edit_prediction_preview(&modifiers, window, cx);
 6415        }
 6416
 6417        self.update_selection_mode(&modifiers, position_map, window, cx);
 6418
 6419        let mouse_position = window.mouse_position();
 6420        if !position_map.text_hitbox.is_hovered(window) {
 6421            return;
 6422        }
 6423
 6424        self.update_hovered_link(
 6425            position_map.point_for_position(mouse_position),
 6426            &position_map.snapshot,
 6427            modifiers,
 6428            window,
 6429            cx,
 6430        )
 6431    }
 6432
 6433    fn update_selection_mode(
 6434        &mut self,
 6435        modifiers: &Modifiers,
 6436        position_map: &PositionMap,
 6437        window: &mut Window,
 6438        cx: &mut Context<Self>,
 6439    ) {
 6440        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6441            return;
 6442        }
 6443
 6444        let mouse_position = window.mouse_position();
 6445        let point_for_position = position_map.point_for_position(mouse_position);
 6446        let position = point_for_position.previous_valid;
 6447
 6448        self.select(
 6449            SelectPhase::BeginColumnar {
 6450                position,
 6451                reset: false,
 6452                goal_column: point_for_position.exact_unclipped.column(),
 6453            },
 6454            window,
 6455            cx,
 6456        );
 6457    }
 6458
 6459    fn update_edit_prediction_preview(
 6460        &mut self,
 6461        modifiers: &Modifiers,
 6462        window: &mut Window,
 6463        cx: &mut Context<Self>,
 6464    ) {
 6465        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6466        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6467            return;
 6468        };
 6469
 6470        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6471            if matches!(
 6472                self.edit_prediction_preview,
 6473                EditPredictionPreview::Inactive { .. }
 6474            ) {
 6475                self.edit_prediction_preview = EditPredictionPreview::Active {
 6476                    previous_scroll_position: None,
 6477                    since: Instant::now(),
 6478                };
 6479
 6480                self.update_visible_inline_completion(window, cx);
 6481                cx.notify();
 6482            }
 6483        } else if let EditPredictionPreview::Active {
 6484            previous_scroll_position,
 6485            since,
 6486        } = self.edit_prediction_preview
 6487        {
 6488            if let (Some(previous_scroll_position), Some(position_map)) =
 6489                (previous_scroll_position, self.last_position_map.as_ref())
 6490            {
 6491                self.set_scroll_position(
 6492                    previous_scroll_position
 6493                        .scroll_position(&position_map.snapshot.display_snapshot),
 6494                    window,
 6495                    cx,
 6496                );
 6497            }
 6498
 6499            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6500                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6501            };
 6502            self.clear_row_highlights::<EditPredictionPreview>();
 6503            self.update_visible_inline_completion(window, cx);
 6504            cx.notify();
 6505        }
 6506    }
 6507
 6508    fn update_visible_inline_completion(
 6509        &mut self,
 6510        _window: &mut Window,
 6511        cx: &mut Context<Self>,
 6512    ) -> Option<()> {
 6513        let selection = self.selections.newest_anchor();
 6514        let cursor = selection.head();
 6515        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6516        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6517        let excerpt_id = cursor.excerpt_id;
 6518
 6519        let show_in_menu = self.show_edit_predictions_in_menu();
 6520        let completions_menu_has_precedence = !show_in_menu
 6521            && (self.context_menu.borrow().is_some()
 6522                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6523
 6524        if completions_menu_has_precedence
 6525            || !offset_selection.is_empty()
 6526            || self
 6527                .active_inline_completion
 6528                .as_ref()
 6529                .map_or(false, |completion| {
 6530                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6531                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6532                    !invalidation_range.contains(&offset_selection.head())
 6533                })
 6534        {
 6535            self.discard_inline_completion(false, cx);
 6536            return None;
 6537        }
 6538
 6539        self.take_active_inline_completion(cx);
 6540        let Some(provider) = self.edit_prediction_provider() else {
 6541            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6542            return None;
 6543        };
 6544
 6545        let (buffer, cursor_buffer_position) =
 6546            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6547
 6548        self.edit_prediction_settings =
 6549            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6550
 6551        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6552
 6553        if self.edit_prediction_indent_conflict {
 6554            let cursor_point = cursor.to_point(&multibuffer);
 6555
 6556            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6557
 6558            if let Some((_, indent)) = indents.iter().next() {
 6559                if indent.len == cursor_point.column {
 6560                    self.edit_prediction_indent_conflict = false;
 6561                }
 6562            }
 6563        }
 6564
 6565        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6566        let edits = inline_completion
 6567            .edits
 6568            .into_iter()
 6569            .flat_map(|(range, new_text)| {
 6570                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6571                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6572                Some((start..end, new_text))
 6573            })
 6574            .collect::<Vec<_>>();
 6575        if edits.is_empty() {
 6576            return None;
 6577        }
 6578
 6579        let first_edit_start = edits.first().unwrap().0.start;
 6580        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6581        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6582
 6583        let last_edit_end = edits.last().unwrap().0.end;
 6584        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6585        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6586
 6587        let cursor_row = cursor.to_point(&multibuffer).row;
 6588
 6589        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6590
 6591        let mut inlay_ids = Vec::new();
 6592        let invalidation_row_range;
 6593        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6594            Some(cursor_row..edit_end_row)
 6595        } else if cursor_row > edit_end_row {
 6596            Some(edit_start_row..cursor_row)
 6597        } else {
 6598            None
 6599        };
 6600        let is_move =
 6601            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6602        let completion = if is_move {
 6603            invalidation_row_range =
 6604                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6605            let target = first_edit_start;
 6606            InlineCompletion::Move { target, snapshot }
 6607        } else {
 6608            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6609                && !self.inline_completions_hidden_for_vim_mode;
 6610
 6611            if show_completions_in_buffer {
 6612                if edits
 6613                    .iter()
 6614                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6615                {
 6616                    let mut inlays = Vec::new();
 6617                    for (range, new_text) in &edits {
 6618                        let inlay = Inlay::inline_completion(
 6619                            post_inc(&mut self.next_inlay_id),
 6620                            range.start,
 6621                            new_text.as_str(),
 6622                        );
 6623                        inlay_ids.push(inlay.id);
 6624                        inlays.push(inlay);
 6625                    }
 6626
 6627                    self.splice_inlays(&[], inlays, cx);
 6628                } else {
 6629                    let background_color = cx.theme().status().deleted_background;
 6630                    self.highlight_text::<InlineCompletionHighlight>(
 6631                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6632                        HighlightStyle {
 6633                            background_color: Some(background_color),
 6634                            ..Default::default()
 6635                        },
 6636                        cx,
 6637                    );
 6638                }
 6639            }
 6640
 6641            invalidation_row_range = edit_start_row..edit_end_row;
 6642
 6643            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6644                if provider.show_tab_accept_marker() {
 6645                    EditDisplayMode::TabAccept
 6646                } else {
 6647                    EditDisplayMode::Inline
 6648                }
 6649            } else {
 6650                EditDisplayMode::DiffPopover
 6651            };
 6652
 6653            InlineCompletion::Edit {
 6654                edits,
 6655                edit_preview: inline_completion.edit_preview,
 6656                display_mode,
 6657                snapshot,
 6658            }
 6659        };
 6660
 6661        let invalidation_range = multibuffer
 6662            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6663            ..multibuffer.anchor_after(Point::new(
 6664                invalidation_row_range.end,
 6665                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6666            ));
 6667
 6668        self.stale_inline_completion_in_menu = None;
 6669        self.active_inline_completion = Some(InlineCompletionState {
 6670            inlay_ids,
 6671            completion,
 6672            completion_id: inline_completion.id,
 6673            invalidation_range,
 6674        });
 6675
 6676        cx.notify();
 6677
 6678        Some(())
 6679    }
 6680
 6681    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6682        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6683    }
 6684
 6685    fn render_code_actions_indicator(
 6686        &self,
 6687        _style: &EditorStyle,
 6688        row: DisplayRow,
 6689        is_active: bool,
 6690        breakpoint: Option<&(Anchor, Breakpoint)>,
 6691        cx: &mut Context<Self>,
 6692    ) -> Option<IconButton> {
 6693        let color = Color::Muted;
 6694        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6695        let show_tooltip = !self.context_menu_visible();
 6696
 6697        if self.available_code_actions.is_some() {
 6698            Some(
 6699                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6700                    .shape(ui::IconButtonShape::Square)
 6701                    .icon_size(IconSize::XSmall)
 6702                    .icon_color(color)
 6703                    .toggle_state(is_active)
 6704                    .when(show_tooltip, |this| {
 6705                        this.tooltip({
 6706                            let focus_handle = self.focus_handle.clone();
 6707                            move |window, cx| {
 6708                                Tooltip::for_action_in(
 6709                                    "Toggle Code Actions",
 6710                                    &ToggleCodeActions {
 6711                                        deployed_from_indicator: None,
 6712                                        quick_launch: false,
 6713                                    },
 6714                                    &focus_handle,
 6715                                    window,
 6716                                    cx,
 6717                                )
 6718                            }
 6719                        })
 6720                    })
 6721                    .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 6722                        let quick_launch = e.down.button == MouseButton::Left;
 6723                        window.focus(&editor.focus_handle(cx));
 6724                        editor.toggle_code_actions(
 6725                            &ToggleCodeActions {
 6726                                deployed_from_indicator: Some(row),
 6727                                quick_launch,
 6728                            },
 6729                            window,
 6730                            cx,
 6731                        );
 6732                    }))
 6733                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6734                        editor.set_breakpoint_context_menu(
 6735                            row,
 6736                            position,
 6737                            event.down.position,
 6738                            window,
 6739                            cx,
 6740                        );
 6741                    })),
 6742            )
 6743        } else {
 6744            None
 6745        }
 6746    }
 6747
 6748    fn clear_tasks(&mut self) {
 6749        self.tasks.clear()
 6750    }
 6751
 6752    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6753        if self.tasks.insert(key, value).is_some() {
 6754            // This case should hopefully be rare, but just in case...
 6755            log::error!(
 6756                "multiple different run targets found on a single line, only the last target will be rendered"
 6757            )
 6758        }
 6759    }
 6760
 6761    /// Get all display points of breakpoints that will be rendered within editor
 6762    ///
 6763    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6764    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6765    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6766    fn active_breakpoints(
 6767        &self,
 6768        range: Range<DisplayRow>,
 6769        window: &mut Window,
 6770        cx: &mut Context<Self>,
 6771    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6772        let mut breakpoint_display_points = HashMap::default();
 6773
 6774        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6775            return breakpoint_display_points;
 6776        };
 6777
 6778        let snapshot = self.snapshot(window, cx);
 6779
 6780        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6781        let Some(project) = self.project.as_ref() else {
 6782            return breakpoint_display_points;
 6783        };
 6784
 6785        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6786            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6787
 6788        for (buffer_snapshot, range, excerpt_id) in
 6789            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6790        {
 6791            let Some(buffer) = project.read_with(cx, |this, cx| {
 6792                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6793            }) else {
 6794                continue;
 6795            };
 6796            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6797                &buffer,
 6798                Some(
 6799                    buffer_snapshot.anchor_before(range.start)
 6800                        ..buffer_snapshot.anchor_after(range.end),
 6801                ),
 6802                buffer_snapshot,
 6803                cx,
 6804            );
 6805            for (anchor, breakpoint) in breakpoints {
 6806                let multi_buffer_anchor =
 6807                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6808                let position = multi_buffer_anchor
 6809                    .to_point(&multi_buffer_snapshot)
 6810                    .to_display_point(&snapshot);
 6811
 6812                breakpoint_display_points
 6813                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6814            }
 6815        }
 6816
 6817        breakpoint_display_points
 6818    }
 6819
 6820    fn breakpoint_context_menu(
 6821        &self,
 6822        anchor: Anchor,
 6823        window: &mut Window,
 6824        cx: &mut Context<Self>,
 6825    ) -> Entity<ui::ContextMenu> {
 6826        let weak_editor = cx.weak_entity();
 6827        let focus_handle = self.focus_handle(cx);
 6828
 6829        let row = self
 6830            .buffer
 6831            .read(cx)
 6832            .snapshot(cx)
 6833            .summary_for_anchor::<Point>(&anchor)
 6834            .row;
 6835
 6836        let breakpoint = self
 6837            .breakpoint_at_row(row, window, cx)
 6838            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6839
 6840        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6841            "Edit Log Breakpoint"
 6842        } else {
 6843            "Set Log Breakpoint"
 6844        };
 6845
 6846        let condition_breakpoint_msg = if breakpoint
 6847            .as_ref()
 6848            .is_some_and(|bp| bp.1.condition.is_some())
 6849        {
 6850            "Edit Condition Breakpoint"
 6851        } else {
 6852            "Set Condition Breakpoint"
 6853        };
 6854
 6855        let hit_condition_breakpoint_msg = if breakpoint
 6856            .as_ref()
 6857            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6858        {
 6859            "Edit Hit Condition Breakpoint"
 6860        } else {
 6861            "Set Hit Condition Breakpoint"
 6862        };
 6863
 6864        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6865            "Unset Breakpoint"
 6866        } else {
 6867            "Set Breakpoint"
 6868        };
 6869
 6870        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6871            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6872
 6873        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6874            BreakpointState::Enabled => Some("Disable"),
 6875            BreakpointState::Disabled => Some("Enable"),
 6876        });
 6877
 6878        let (anchor, breakpoint) =
 6879            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6880
 6881        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6882            menu.on_blur_subscription(Subscription::new(|| {}))
 6883                .context(focus_handle)
 6884                .when(run_to_cursor, |this| {
 6885                    let weak_editor = weak_editor.clone();
 6886                    this.entry("Run to cursor", None, move |window, cx| {
 6887                        weak_editor
 6888                            .update(cx, |editor, cx| {
 6889                                editor.change_selections(None, window, cx, |s| {
 6890                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6891                                });
 6892                            })
 6893                            .ok();
 6894
 6895                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6896                    })
 6897                    .separator()
 6898                })
 6899                .when_some(toggle_state_msg, |this, msg| {
 6900                    this.entry(msg, None, {
 6901                        let weak_editor = weak_editor.clone();
 6902                        let breakpoint = breakpoint.clone();
 6903                        move |_window, cx| {
 6904                            weak_editor
 6905                                .update(cx, |this, cx| {
 6906                                    this.edit_breakpoint_at_anchor(
 6907                                        anchor,
 6908                                        breakpoint.as_ref().clone(),
 6909                                        BreakpointEditAction::InvertState,
 6910                                        cx,
 6911                                    );
 6912                                })
 6913                                .log_err();
 6914                        }
 6915                    })
 6916                })
 6917                .entry(set_breakpoint_msg, None, {
 6918                    let weak_editor = weak_editor.clone();
 6919                    let breakpoint = breakpoint.clone();
 6920                    move |_window, cx| {
 6921                        weak_editor
 6922                            .update(cx, |this, cx| {
 6923                                this.edit_breakpoint_at_anchor(
 6924                                    anchor,
 6925                                    breakpoint.as_ref().clone(),
 6926                                    BreakpointEditAction::Toggle,
 6927                                    cx,
 6928                                );
 6929                            })
 6930                            .log_err();
 6931                    }
 6932                })
 6933                .entry(log_breakpoint_msg, None, {
 6934                    let breakpoint = breakpoint.clone();
 6935                    let weak_editor = weak_editor.clone();
 6936                    move |window, cx| {
 6937                        weak_editor
 6938                            .update(cx, |this, cx| {
 6939                                this.add_edit_breakpoint_block(
 6940                                    anchor,
 6941                                    breakpoint.as_ref(),
 6942                                    BreakpointPromptEditAction::Log,
 6943                                    window,
 6944                                    cx,
 6945                                );
 6946                            })
 6947                            .log_err();
 6948                    }
 6949                })
 6950                .entry(condition_breakpoint_msg, None, {
 6951                    let breakpoint = breakpoint.clone();
 6952                    let weak_editor = weak_editor.clone();
 6953                    move |window, cx| {
 6954                        weak_editor
 6955                            .update(cx, |this, cx| {
 6956                                this.add_edit_breakpoint_block(
 6957                                    anchor,
 6958                                    breakpoint.as_ref(),
 6959                                    BreakpointPromptEditAction::Condition,
 6960                                    window,
 6961                                    cx,
 6962                                );
 6963                            })
 6964                            .log_err();
 6965                    }
 6966                })
 6967                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6968                    weak_editor
 6969                        .update(cx, |this, cx| {
 6970                            this.add_edit_breakpoint_block(
 6971                                anchor,
 6972                                breakpoint.as_ref(),
 6973                                BreakpointPromptEditAction::HitCondition,
 6974                                window,
 6975                                cx,
 6976                            );
 6977                        })
 6978                        .log_err();
 6979                })
 6980        })
 6981    }
 6982
 6983    fn render_breakpoint(
 6984        &self,
 6985        position: Anchor,
 6986        row: DisplayRow,
 6987        breakpoint: &Breakpoint,
 6988        cx: &mut Context<Self>,
 6989    ) -> IconButton {
 6990        // Is it a breakpoint that shows up when hovering over gutter?
 6991        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 6992            (false, false),
 6993            |PhantomBreakpointIndicator {
 6994                 is_active,
 6995                 display_row,
 6996                 collides_with_existing_breakpoint,
 6997             }| {
 6998                (
 6999                    is_active && display_row == row,
 7000                    collides_with_existing_breakpoint,
 7001                )
 7002            },
 7003        );
 7004
 7005        let (color, icon) = {
 7006            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 7007                (false, false) => ui::IconName::DebugBreakpoint,
 7008                (true, false) => ui::IconName::DebugLogBreakpoint,
 7009                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 7010                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 7011            };
 7012
 7013            let color = if is_phantom {
 7014                Color::Hint
 7015            } else {
 7016                Color::Debugger
 7017            };
 7018
 7019            (color, icon)
 7020        };
 7021
 7022        let breakpoint = Arc::from(breakpoint.clone());
 7023
 7024        let alt_as_text = gpui::Keystroke {
 7025            modifiers: Modifiers::secondary_key(),
 7026            ..Default::default()
 7027        };
 7028        let primary_action_text = if breakpoint.is_disabled() {
 7029            "enable"
 7030        } else if is_phantom && !collides_with_existing {
 7031            "set"
 7032        } else {
 7033            "unset"
 7034        };
 7035        let mut primary_text = format!("Click to {primary_action_text}");
 7036        if collides_with_existing && !breakpoint.is_disabled() {
 7037            use std::fmt::Write;
 7038            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7039        }
 7040        let primary_text = SharedString::from(primary_text);
 7041        let focus_handle = self.focus_handle.clone();
 7042        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7043            .icon_size(IconSize::XSmall)
 7044            .size(ui::ButtonSize::None)
 7045            .icon_color(color)
 7046            .style(ButtonStyle::Transparent)
 7047            .on_click(cx.listener({
 7048                let breakpoint = breakpoint.clone();
 7049
 7050                move |editor, event: &ClickEvent, window, cx| {
 7051                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7052                        BreakpointEditAction::InvertState
 7053                    } else {
 7054                        BreakpointEditAction::Toggle
 7055                    };
 7056
 7057                    window.focus(&editor.focus_handle(cx));
 7058                    editor.edit_breakpoint_at_anchor(
 7059                        position,
 7060                        breakpoint.as_ref().clone(),
 7061                        edit_action,
 7062                        cx,
 7063                    );
 7064                }
 7065            }))
 7066            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7067                editor.set_breakpoint_context_menu(
 7068                    row,
 7069                    Some(position),
 7070                    event.down.position,
 7071                    window,
 7072                    cx,
 7073                );
 7074            }))
 7075            .tooltip(move |window, cx| {
 7076                Tooltip::with_meta_in(
 7077                    primary_text.clone(),
 7078                    None,
 7079                    "Right-click for more options",
 7080                    &focus_handle,
 7081                    window,
 7082                    cx,
 7083                )
 7084            })
 7085    }
 7086
 7087    fn build_tasks_context(
 7088        project: &Entity<Project>,
 7089        buffer: &Entity<Buffer>,
 7090        buffer_row: u32,
 7091        tasks: &Arc<RunnableTasks>,
 7092        cx: &mut Context<Self>,
 7093    ) -> Task<Option<task::TaskContext>> {
 7094        let position = Point::new(buffer_row, tasks.column);
 7095        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7096        let location = Location {
 7097            buffer: buffer.clone(),
 7098            range: range_start..range_start,
 7099        };
 7100        // Fill in the environmental variables from the tree-sitter captures
 7101        let mut captured_task_variables = TaskVariables::default();
 7102        for (capture_name, value) in tasks.extra_variables.clone() {
 7103            captured_task_variables.insert(
 7104                task::VariableName::Custom(capture_name.into()),
 7105                value.clone(),
 7106            );
 7107        }
 7108        project.update(cx, |project, cx| {
 7109            project.task_store().update(cx, |task_store, cx| {
 7110                task_store.task_context_for_location(captured_task_variables, location, cx)
 7111            })
 7112        })
 7113    }
 7114
 7115    pub fn spawn_nearest_task(
 7116        &mut self,
 7117        action: &SpawnNearestTask,
 7118        window: &mut Window,
 7119        cx: &mut Context<Self>,
 7120    ) {
 7121        let Some((workspace, _)) = self.workspace.clone() else {
 7122            return;
 7123        };
 7124        let Some(project) = self.project.clone() else {
 7125            return;
 7126        };
 7127
 7128        // Try to find a closest, enclosing node using tree-sitter that has a
 7129        // task
 7130        let Some((buffer, buffer_row, tasks)) = self
 7131            .find_enclosing_node_task(cx)
 7132            // Or find the task that's closest in row-distance.
 7133            .or_else(|| self.find_closest_task(cx))
 7134        else {
 7135            return;
 7136        };
 7137
 7138        let reveal_strategy = action.reveal;
 7139        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7140        cx.spawn_in(window, async move |_, cx| {
 7141            let context = task_context.await?;
 7142            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7143
 7144            let resolved = &mut resolved_task.resolved;
 7145            resolved.reveal = reveal_strategy;
 7146
 7147            workspace
 7148                .update_in(cx, |workspace, window, cx| {
 7149                    workspace.schedule_resolved_task(
 7150                        task_source_kind,
 7151                        resolved_task,
 7152                        false,
 7153                        window,
 7154                        cx,
 7155                    );
 7156                })
 7157                .ok()
 7158        })
 7159        .detach();
 7160    }
 7161
 7162    fn find_closest_task(
 7163        &mut self,
 7164        cx: &mut Context<Self>,
 7165    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7166        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7167
 7168        let ((buffer_id, row), tasks) = self
 7169            .tasks
 7170            .iter()
 7171            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7172
 7173        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7174        let tasks = Arc::new(tasks.to_owned());
 7175        Some((buffer, *row, tasks))
 7176    }
 7177
 7178    fn find_enclosing_node_task(
 7179        &mut self,
 7180        cx: &mut Context<Self>,
 7181    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7182        let snapshot = self.buffer.read(cx).snapshot(cx);
 7183        let offset = self.selections.newest::<usize>(cx).head();
 7184        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7185        let buffer_id = excerpt.buffer().remote_id();
 7186
 7187        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7188        let mut cursor = layer.node().walk();
 7189
 7190        while cursor.goto_first_child_for_byte(offset).is_some() {
 7191            if cursor.node().end_byte() == offset {
 7192                cursor.goto_next_sibling();
 7193            }
 7194        }
 7195
 7196        // Ascend to the smallest ancestor that contains the range and has a task.
 7197        loop {
 7198            let node = cursor.node();
 7199            let node_range = node.byte_range();
 7200            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7201
 7202            // Check if this node contains our offset
 7203            if node_range.start <= offset && node_range.end >= offset {
 7204                // If it contains offset, check for task
 7205                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7206                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7207                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7208                }
 7209            }
 7210
 7211            if !cursor.goto_parent() {
 7212                break;
 7213            }
 7214        }
 7215        None
 7216    }
 7217
 7218    fn render_run_indicator(
 7219        &self,
 7220        _style: &EditorStyle,
 7221        is_active: bool,
 7222        row: DisplayRow,
 7223        breakpoint: Option<(Anchor, Breakpoint)>,
 7224        cx: &mut Context<Self>,
 7225    ) -> IconButton {
 7226        let color = Color::Muted;
 7227        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7228
 7229        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7230            .shape(ui::IconButtonShape::Square)
 7231            .icon_size(IconSize::XSmall)
 7232            .icon_color(color)
 7233            .toggle_state(is_active)
 7234            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7235                let quick_launch = e.down.button == MouseButton::Left;
 7236                window.focus(&editor.focus_handle(cx));
 7237                editor.toggle_code_actions(
 7238                    &ToggleCodeActions {
 7239                        deployed_from_indicator: Some(row),
 7240                        quick_launch,
 7241                    },
 7242                    window,
 7243                    cx,
 7244                );
 7245            }))
 7246            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7247                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7248            }))
 7249    }
 7250
 7251    pub fn context_menu_visible(&self) -> bool {
 7252        !self.edit_prediction_preview_is_active()
 7253            && self
 7254                .context_menu
 7255                .borrow()
 7256                .as_ref()
 7257                .map_or(false, |menu| menu.visible())
 7258    }
 7259
 7260    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7261        self.context_menu
 7262            .borrow()
 7263            .as_ref()
 7264            .map(|menu| menu.origin())
 7265    }
 7266
 7267    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7268        self.context_menu_options = Some(options);
 7269    }
 7270
 7271    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7272    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7273
 7274    fn render_edit_prediction_popover(
 7275        &mut self,
 7276        text_bounds: &Bounds<Pixels>,
 7277        content_origin: gpui::Point<Pixels>,
 7278        editor_snapshot: &EditorSnapshot,
 7279        visible_row_range: Range<DisplayRow>,
 7280        scroll_top: f32,
 7281        scroll_bottom: f32,
 7282        line_layouts: &[LineWithInvisibles],
 7283        line_height: Pixels,
 7284        scroll_pixel_position: gpui::Point<Pixels>,
 7285        newest_selection_head: Option<DisplayPoint>,
 7286        editor_width: Pixels,
 7287        style: &EditorStyle,
 7288        window: &mut Window,
 7289        cx: &mut App,
 7290    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7291        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7292
 7293        if self.edit_prediction_visible_in_cursor_popover(true) {
 7294            return None;
 7295        }
 7296
 7297        match &active_inline_completion.completion {
 7298            InlineCompletion::Move { target, .. } => {
 7299                let target_display_point = target.to_display_point(editor_snapshot);
 7300
 7301                if self.edit_prediction_requires_modifier() {
 7302                    if !self.edit_prediction_preview_is_active() {
 7303                        return None;
 7304                    }
 7305
 7306                    self.render_edit_prediction_modifier_jump_popover(
 7307                        text_bounds,
 7308                        content_origin,
 7309                        visible_row_range,
 7310                        line_layouts,
 7311                        line_height,
 7312                        scroll_pixel_position,
 7313                        newest_selection_head,
 7314                        target_display_point,
 7315                        window,
 7316                        cx,
 7317                    )
 7318                } else {
 7319                    self.render_edit_prediction_eager_jump_popover(
 7320                        text_bounds,
 7321                        content_origin,
 7322                        editor_snapshot,
 7323                        visible_row_range,
 7324                        scroll_top,
 7325                        scroll_bottom,
 7326                        line_height,
 7327                        scroll_pixel_position,
 7328                        target_display_point,
 7329                        editor_width,
 7330                        window,
 7331                        cx,
 7332                    )
 7333                }
 7334            }
 7335            InlineCompletion::Edit {
 7336                display_mode: EditDisplayMode::Inline,
 7337                ..
 7338            } => None,
 7339            InlineCompletion::Edit {
 7340                display_mode: EditDisplayMode::TabAccept,
 7341                edits,
 7342                ..
 7343            } => {
 7344                let range = &edits.first()?.0;
 7345                let target_display_point = range.end.to_display_point(editor_snapshot);
 7346
 7347                self.render_edit_prediction_end_of_line_popover(
 7348                    "Accept",
 7349                    editor_snapshot,
 7350                    visible_row_range,
 7351                    target_display_point,
 7352                    line_height,
 7353                    scroll_pixel_position,
 7354                    content_origin,
 7355                    editor_width,
 7356                    window,
 7357                    cx,
 7358                )
 7359            }
 7360            InlineCompletion::Edit {
 7361                edits,
 7362                edit_preview,
 7363                display_mode: EditDisplayMode::DiffPopover,
 7364                snapshot,
 7365            } => self.render_edit_prediction_diff_popover(
 7366                text_bounds,
 7367                content_origin,
 7368                editor_snapshot,
 7369                visible_row_range,
 7370                line_layouts,
 7371                line_height,
 7372                scroll_pixel_position,
 7373                newest_selection_head,
 7374                editor_width,
 7375                style,
 7376                edits,
 7377                edit_preview,
 7378                snapshot,
 7379                window,
 7380                cx,
 7381            ),
 7382        }
 7383    }
 7384
 7385    fn render_edit_prediction_modifier_jump_popover(
 7386        &mut self,
 7387        text_bounds: &Bounds<Pixels>,
 7388        content_origin: gpui::Point<Pixels>,
 7389        visible_row_range: Range<DisplayRow>,
 7390        line_layouts: &[LineWithInvisibles],
 7391        line_height: Pixels,
 7392        scroll_pixel_position: gpui::Point<Pixels>,
 7393        newest_selection_head: Option<DisplayPoint>,
 7394        target_display_point: DisplayPoint,
 7395        window: &mut Window,
 7396        cx: &mut App,
 7397    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7398        let scrolled_content_origin =
 7399            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7400
 7401        const SCROLL_PADDING_Y: Pixels = px(12.);
 7402
 7403        if target_display_point.row() < visible_row_range.start {
 7404            return self.render_edit_prediction_scroll_popover(
 7405                |_| SCROLL_PADDING_Y,
 7406                IconName::ArrowUp,
 7407                visible_row_range,
 7408                line_layouts,
 7409                newest_selection_head,
 7410                scrolled_content_origin,
 7411                window,
 7412                cx,
 7413            );
 7414        } else if target_display_point.row() >= visible_row_range.end {
 7415            return self.render_edit_prediction_scroll_popover(
 7416                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7417                IconName::ArrowDown,
 7418                visible_row_range,
 7419                line_layouts,
 7420                newest_selection_head,
 7421                scrolled_content_origin,
 7422                window,
 7423                cx,
 7424            );
 7425        }
 7426
 7427        const POLE_WIDTH: Pixels = px(2.);
 7428
 7429        let line_layout =
 7430            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7431        let target_column = target_display_point.column() as usize;
 7432
 7433        let target_x = line_layout.x_for_index(target_column);
 7434        let target_y =
 7435            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7436
 7437        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7438
 7439        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7440        border_color.l += 0.001;
 7441
 7442        let mut element = v_flex()
 7443            .items_end()
 7444            .when(flag_on_right, |el| el.items_start())
 7445            .child(if flag_on_right {
 7446                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7447                    .rounded_bl(px(0.))
 7448                    .rounded_tl(px(0.))
 7449                    .border_l_2()
 7450                    .border_color(border_color)
 7451            } else {
 7452                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7453                    .rounded_br(px(0.))
 7454                    .rounded_tr(px(0.))
 7455                    .border_r_2()
 7456                    .border_color(border_color)
 7457            })
 7458            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7459            .into_any();
 7460
 7461        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7462
 7463        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7464            - point(
 7465                if flag_on_right {
 7466                    POLE_WIDTH
 7467                } else {
 7468                    size.width - POLE_WIDTH
 7469                },
 7470                size.height - line_height,
 7471            );
 7472
 7473        origin.x = origin.x.max(content_origin.x);
 7474
 7475        element.prepaint_at(origin, window, cx);
 7476
 7477        Some((element, origin))
 7478    }
 7479
 7480    fn render_edit_prediction_scroll_popover(
 7481        &mut self,
 7482        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7483        scroll_icon: IconName,
 7484        visible_row_range: Range<DisplayRow>,
 7485        line_layouts: &[LineWithInvisibles],
 7486        newest_selection_head: Option<DisplayPoint>,
 7487        scrolled_content_origin: gpui::Point<Pixels>,
 7488        window: &mut Window,
 7489        cx: &mut App,
 7490    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7491        let mut element = self
 7492            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7493            .into_any();
 7494
 7495        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7496
 7497        let cursor = newest_selection_head?;
 7498        let cursor_row_layout =
 7499            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7500        let cursor_column = cursor.column() as usize;
 7501
 7502        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7503
 7504        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7505
 7506        element.prepaint_at(origin, window, cx);
 7507        Some((element, origin))
 7508    }
 7509
 7510    fn render_edit_prediction_eager_jump_popover(
 7511        &mut self,
 7512        text_bounds: &Bounds<Pixels>,
 7513        content_origin: gpui::Point<Pixels>,
 7514        editor_snapshot: &EditorSnapshot,
 7515        visible_row_range: Range<DisplayRow>,
 7516        scroll_top: f32,
 7517        scroll_bottom: f32,
 7518        line_height: Pixels,
 7519        scroll_pixel_position: gpui::Point<Pixels>,
 7520        target_display_point: DisplayPoint,
 7521        editor_width: Pixels,
 7522        window: &mut Window,
 7523        cx: &mut App,
 7524    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7525        if target_display_point.row().as_f32() < scroll_top {
 7526            let mut element = self
 7527                .render_edit_prediction_line_popover(
 7528                    "Jump to Edit",
 7529                    Some(IconName::ArrowUp),
 7530                    window,
 7531                    cx,
 7532                )?
 7533                .into_any();
 7534
 7535            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7536            let offset = point(
 7537                (text_bounds.size.width - size.width) / 2.,
 7538                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7539            );
 7540
 7541            let origin = text_bounds.origin + offset;
 7542            element.prepaint_at(origin, window, cx);
 7543            Some((element, origin))
 7544        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7545            let mut element = self
 7546                .render_edit_prediction_line_popover(
 7547                    "Jump to Edit",
 7548                    Some(IconName::ArrowDown),
 7549                    window,
 7550                    cx,
 7551                )?
 7552                .into_any();
 7553
 7554            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7555            let offset = point(
 7556                (text_bounds.size.width - size.width) / 2.,
 7557                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7558            );
 7559
 7560            let origin = text_bounds.origin + offset;
 7561            element.prepaint_at(origin, window, cx);
 7562            Some((element, origin))
 7563        } else {
 7564            self.render_edit_prediction_end_of_line_popover(
 7565                "Jump to Edit",
 7566                editor_snapshot,
 7567                visible_row_range,
 7568                target_display_point,
 7569                line_height,
 7570                scroll_pixel_position,
 7571                content_origin,
 7572                editor_width,
 7573                window,
 7574                cx,
 7575            )
 7576        }
 7577    }
 7578
 7579    fn render_edit_prediction_end_of_line_popover(
 7580        self: &mut Editor,
 7581        label: &'static str,
 7582        editor_snapshot: &EditorSnapshot,
 7583        visible_row_range: Range<DisplayRow>,
 7584        target_display_point: DisplayPoint,
 7585        line_height: Pixels,
 7586        scroll_pixel_position: gpui::Point<Pixels>,
 7587        content_origin: gpui::Point<Pixels>,
 7588        editor_width: Pixels,
 7589        window: &mut Window,
 7590        cx: &mut App,
 7591    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7592        let target_line_end = DisplayPoint::new(
 7593            target_display_point.row(),
 7594            editor_snapshot.line_len(target_display_point.row()),
 7595        );
 7596
 7597        let mut element = self
 7598            .render_edit_prediction_line_popover(label, None, window, cx)?
 7599            .into_any();
 7600
 7601        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7602
 7603        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7604
 7605        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7606        let mut origin = start_point
 7607            + line_origin
 7608            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7609        origin.x = origin.x.max(content_origin.x);
 7610
 7611        let max_x = content_origin.x + editor_width - size.width;
 7612
 7613        if origin.x > max_x {
 7614            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7615
 7616            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7617                origin.y += offset;
 7618                IconName::ArrowUp
 7619            } else {
 7620                origin.y -= offset;
 7621                IconName::ArrowDown
 7622            };
 7623
 7624            element = self
 7625                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7626                .into_any();
 7627
 7628            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7629
 7630            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7631        }
 7632
 7633        element.prepaint_at(origin, window, cx);
 7634        Some((element, origin))
 7635    }
 7636
 7637    fn render_edit_prediction_diff_popover(
 7638        self: &Editor,
 7639        text_bounds: &Bounds<Pixels>,
 7640        content_origin: gpui::Point<Pixels>,
 7641        editor_snapshot: &EditorSnapshot,
 7642        visible_row_range: Range<DisplayRow>,
 7643        line_layouts: &[LineWithInvisibles],
 7644        line_height: Pixels,
 7645        scroll_pixel_position: gpui::Point<Pixels>,
 7646        newest_selection_head: Option<DisplayPoint>,
 7647        editor_width: Pixels,
 7648        style: &EditorStyle,
 7649        edits: &Vec<(Range<Anchor>, String)>,
 7650        edit_preview: &Option<language::EditPreview>,
 7651        snapshot: &language::BufferSnapshot,
 7652        window: &mut Window,
 7653        cx: &mut App,
 7654    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7655        let edit_start = edits
 7656            .first()
 7657            .unwrap()
 7658            .0
 7659            .start
 7660            .to_display_point(editor_snapshot);
 7661        let edit_end = edits
 7662            .last()
 7663            .unwrap()
 7664            .0
 7665            .end
 7666            .to_display_point(editor_snapshot);
 7667
 7668        let is_visible = visible_row_range.contains(&edit_start.row())
 7669            || visible_row_range.contains(&edit_end.row());
 7670        if !is_visible {
 7671            return None;
 7672        }
 7673
 7674        let highlighted_edits =
 7675            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7676
 7677        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7678        let line_count = highlighted_edits.text.lines().count();
 7679
 7680        const BORDER_WIDTH: Pixels = px(1.);
 7681
 7682        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7683        let has_keybind = keybind.is_some();
 7684
 7685        let mut element = h_flex()
 7686            .items_start()
 7687            .child(
 7688                h_flex()
 7689                    .bg(cx.theme().colors().editor_background)
 7690                    .border(BORDER_WIDTH)
 7691                    .shadow_sm()
 7692                    .border_color(cx.theme().colors().border)
 7693                    .rounded_l_lg()
 7694                    .when(line_count > 1, |el| el.rounded_br_lg())
 7695                    .pr_1()
 7696                    .child(styled_text),
 7697            )
 7698            .child(
 7699                h_flex()
 7700                    .h(line_height + BORDER_WIDTH * 2.)
 7701                    .px_1p5()
 7702                    .gap_1()
 7703                    // Workaround: For some reason, there's a gap if we don't do this
 7704                    .ml(-BORDER_WIDTH)
 7705                    .shadow(smallvec![gpui::BoxShadow {
 7706                        color: gpui::black().opacity(0.05),
 7707                        offset: point(px(1.), px(1.)),
 7708                        blur_radius: px(2.),
 7709                        spread_radius: px(0.),
 7710                    }])
 7711                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7712                    .border(BORDER_WIDTH)
 7713                    .border_color(cx.theme().colors().border)
 7714                    .rounded_r_lg()
 7715                    .id("edit_prediction_diff_popover_keybind")
 7716                    .when(!has_keybind, |el| {
 7717                        let status_colors = cx.theme().status();
 7718
 7719                        el.bg(status_colors.error_background)
 7720                            .border_color(status_colors.error.opacity(0.6))
 7721                            .child(Icon::new(IconName::Info).color(Color::Error))
 7722                            .cursor_default()
 7723                            .hoverable_tooltip(move |_window, cx| {
 7724                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7725                            })
 7726                    })
 7727                    .children(keybind),
 7728            )
 7729            .into_any();
 7730
 7731        let longest_row =
 7732            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7733        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7734            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7735        } else {
 7736            layout_line(
 7737                longest_row,
 7738                editor_snapshot,
 7739                style,
 7740                editor_width,
 7741                |_| false,
 7742                window,
 7743                cx,
 7744            )
 7745            .width
 7746        };
 7747
 7748        let viewport_bounds =
 7749            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7750                right: -EditorElement::SCROLLBAR_WIDTH,
 7751                ..Default::default()
 7752            });
 7753
 7754        let x_after_longest =
 7755            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7756                - scroll_pixel_position.x;
 7757
 7758        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7759
 7760        // Fully visible if it can be displayed within the window (allow overlapping other
 7761        // panes). However, this is only allowed if the popover starts within text_bounds.
 7762        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7763            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7764
 7765        let mut origin = if can_position_to_the_right {
 7766            point(
 7767                x_after_longest,
 7768                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7769                    - scroll_pixel_position.y,
 7770            )
 7771        } else {
 7772            let cursor_row = newest_selection_head.map(|head| head.row());
 7773            let above_edit = edit_start
 7774                .row()
 7775                .0
 7776                .checked_sub(line_count as u32)
 7777                .map(DisplayRow);
 7778            let below_edit = Some(edit_end.row() + 1);
 7779            let above_cursor =
 7780                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7781            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7782
 7783            // Place the edit popover adjacent to the edit if there is a location
 7784            // available that is onscreen and does not obscure the cursor. Otherwise,
 7785            // place it adjacent to the cursor.
 7786            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7787                .into_iter()
 7788                .flatten()
 7789                .find(|&start_row| {
 7790                    let end_row = start_row + line_count as u32;
 7791                    visible_row_range.contains(&start_row)
 7792                        && visible_row_range.contains(&end_row)
 7793                        && cursor_row.map_or(true, |cursor_row| {
 7794                            !((start_row..end_row).contains(&cursor_row))
 7795                        })
 7796                })?;
 7797
 7798            content_origin
 7799                + point(
 7800                    -scroll_pixel_position.x,
 7801                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7802                )
 7803        };
 7804
 7805        origin.x -= BORDER_WIDTH;
 7806
 7807        window.defer_draw(element, origin, 1);
 7808
 7809        // Do not return an element, since it will already be drawn due to defer_draw.
 7810        None
 7811    }
 7812
 7813    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7814        px(30.)
 7815    }
 7816
 7817    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7818        if self.read_only(cx) {
 7819            cx.theme().players().read_only()
 7820        } else {
 7821            self.style.as_ref().unwrap().local_player
 7822        }
 7823    }
 7824
 7825    fn render_edit_prediction_accept_keybind(
 7826        &self,
 7827        window: &mut Window,
 7828        cx: &App,
 7829    ) -> Option<AnyElement> {
 7830        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7831        let accept_keystroke = accept_binding.keystroke()?;
 7832
 7833        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7834
 7835        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7836            Color::Accent
 7837        } else {
 7838            Color::Muted
 7839        };
 7840
 7841        h_flex()
 7842            .px_0p5()
 7843            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7844            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7845            .text_size(TextSize::XSmall.rems(cx))
 7846            .child(h_flex().children(ui::render_modifiers(
 7847                &accept_keystroke.modifiers,
 7848                PlatformStyle::platform(),
 7849                Some(modifiers_color),
 7850                Some(IconSize::XSmall.rems().into()),
 7851                true,
 7852            )))
 7853            .when(is_platform_style_mac, |parent| {
 7854                parent.child(accept_keystroke.key.clone())
 7855            })
 7856            .when(!is_platform_style_mac, |parent| {
 7857                parent.child(
 7858                    Key::new(
 7859                        util::capitalize(&accept_keystroke.key),
 7860                        Some(Color::Default),
 7861                    )
 7862                    .size(Some(IconSize::XSmall.rems().into())),
 7863                )
 7864            })
 7865            .into_any()
 7866            .into()
 7867    }
 7868
 7869    fn render_edit_prediction_line_popover(
 7870        &self,
 7871        label: impl Into<SharedString>,
 7872        icon: Option<IconName>,
 7873        window: &mut Window,
 7874        cx: &App,
 7875    ) -> Option<Stateful<Div>> {
 7876        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7877
 7878        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7879        let has_keybind = keybind.is_some();
 7880
 7881        let result = h_flex()
 7882            .id("ep-line-popover")
 7883            .py_0p5()
 7884            .pl_1()
 7885            .pr(padding_right)
 7886            .gap_1()
 7887            .rounded_md()
 7888            .border_1()
 7889            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7890            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7891            .shadow_sm()
 7892            .when(!has_keybind, |el| {
 7893                let status_colors = cx.theme().status();
 7894
 7895                el.bg(status_colors.error_background)
 7896                    .border_color(status_colors.error.opacity(0.6))
 7897                    .pl_2()
 7898                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7899                    .cursor_default()
 7900                    .hoverable_tooltip(move |_window, cx| {
 7901                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7902                    })
 7903            })
 7904            .children(keybind)
 7905            .child(
 7906                Label::new(label)
 7907                    .size(LabelSize::Small)
 7908                    .when(!has_keybind, |el| {
 7909                        el.color(cx.theme().status().error.into()).strikethrough()
 7910                    }),
 7911            )
 7912            .when(!has_keybind, |el| {
 7913                el.child(
 7914                    h_flex().ml_1().child(
 7915                        Icon::new(IconName::Info)
 7916                            .size(IconSize::Small)
 7917                            .color(cx.theme().status().error.into()),
 7918                    ),
 7919                )
 7920            })
 7921            .when_some(icon, |element, icon| {
 7922                element.child(
 7923                    div()
 7924                        .mt(px(1.5))
 7925                        .child(Icon::new(icon).size(IconSize::Small)),
 7926                )
 7927            });
 7928
 7929        Some(result)
 7930    }
 7931
 7932    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7933        let accent_color = cx.theme().colors().text_accent;
 7934        let editor_bg_color = cx.theme().colors().editor_background;
 7935        editor_bg_color.blend(accent_color.opacity(0.1))
 7936    }
 7937
 7938    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7939        let accent_color = cx.theme().colors().text_accent;
 7940        let editor_bg_color = cx.theme().colors().editor_background;
 7941        editor_bg_color.blend(accent_color.opacity(0.6))
 7942    }
 7943
 7944    fn render_edit_prediction_cursor_popover(
 7945        &self,
 7946        min_width: Pixels,
 7947        max_width: Pixels,
 7948        cursor_point: Point,
 7949        style: &EditorStyle,
 7950        accept_keystroke: Option<&gpui::Keystroke>,
 7951        _window: &Window,
 7952        cx: &mut Context<Editor>,
 7953    ) -> Option<AnyElement> {
 7954        let provider = self.edit_prediction_provider.as_ref()?;
 7955
 7956        if provider.provider.needs_terms_acceptance(cx) {
 7957            return Some(
 7958                h_flex()
 7959                    .min_w(min_width)
 7960                    .flex_1()
 7961                    .px_2()
 7962                    .py_1()
 7963                    .gap_3()
 7964                    .elevation_2(cx)
 7965                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7966                    .id("accept-terms")
 7967                    .cursor_pointer()
 7968                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7969                    .on_click(cx.listener(|this, _event, window, cx| {
 7970                        cx.stop_propagation();
 7971                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7972                        window.dispatch_action(
 7973                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7974                            cx,
 7975                        );
 7976                    }))
 7977                    .child(
 7978                        h_flex()
 7979                            .flex_1()
 7980                            .gap_2()
 7981                            .child(Icon::new(IconName::ZedPredict))
 7982                            .child(Label::new("Accept Terms of Service"))
 7983                            .child(div().w_full())
 7984                            .child(
 7985                                Icon::new(IconName::ArrowUpRight)
 7986                                    .color(Color::Muted)
 7987                                    .size(IconSize::Small),
 7988                            )
 7989                            .into_any_element(),
 7990                    )
 7991                    .into_any(),
 7992            );
 7993        }
 7994
 7995        let is_refreshing = provider.provider.is_refreshing(cx);
 7996
 7997        fn pending_completion_container() -> Div {
 7998            h_flex()
 7999                .h_full()
 8000                .flex_1()
 8001                .gap_2()
 8002                .child(Icon::new(IconName::ZedPredict))
 8003        }
 8004
 8005        let completion = match &self.active_inline_completion {
 8006            Some(prediction) => {
 8007                if !self.has_visible_completions_menu() {
 8008                    const RADIUS: Pixels = px(6.);
 8009                    const BORDER_WIDTH: Pixels = px(1.);
 8010
 8011                    return Some(
 8012                        h_flex()
 8013                            .elevation_2(cx)
 8014                            .border(BORDER_WIDTH)
 8015                            .border_color(cx.theme().colors().border)
 8016                            .when(accept_keystroke.is_none(), |el| {
 8017                                el.border_color(cx.theme().status().error)
 8018                            })
 8019                            .rounded(RADIUS)
 8020                            .rounded_tl(px(0.))
 8021                            .overflow_hidden()
 8022                            .child(div().px_1p5().child(match &prediction.completion {
 8023                                InlineCompletion::Move { target, snapshot } => {
 8024                                    use text::ToPoint as _;
 8025                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 8026                                    {
 8027                                        Icon::new(IconName::ZedPredictDown)
 8028                                    } else {
 8029                                        Icon::new(IconName::ZedPredictUp)
 8030                                    }
 8031                                }
 8032                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 8033                            }))
 8034                            .child(
 8035                                h_flex()
 8036                                    .gap_1()
 8037                                    .py_1()
 8038                                    .px_2()
 8039                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8040                                    .border_l_1()
 8041                                    .border_color(cx.theme().colors().border)
 8042                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8043                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8044                                        el.child(
 8045                                            Label::new("Hold")
 8046                                                .size(LabelSize::Small)
 8047                                                .when(accept_keystroke.is_none(), |el| {
 8048                                                    el.strikethrough()
 8049                                                })
 8050                                                .line_height_style(LineHeightStyle::UiLabel),
 8051                                        )
 8052                                    })
 8053                                    .id("edit_prediction_cursor_popover_keybind")
 8054                                    .when(accept_keystroke.is_none(), |el| {
 8055                                        let status_colors = cx.theme().status();
 8056
 8057                                        el.bg(status_colors.error_background)
 8058                                            .border_color(status_colors.error.opacity(0.6))
 8059                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8060                                            .cursor_default()
 8061                                            .hoverable_tooltip(move |_window, cx| {
 8062                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8063                                                    .into()
 8064                                            })
 8065                                    })
 8066                                    .when_some(
 8067                                        accept_keystroke.as_ref(),
 8068                                        |el, accept_keystroke| {
 8069                                            el.child(h_flex().children(ui::render_modifiers(
 8070                                                &accept_keystroke.modifiers,
 8071                                                PlatformStyle::platform(),
 8072                                                Some(Color::Default),
 8073                                                Some(IconSize::XSmall.rems().into()),
 8074                                                false,
 8075                                            )))
 8076                                        },
 8077                                    ),
 8078                            )
 8079                            .into_any(),
 8080                    );
 8081                }
 8082
 8083                self.render_edit_prediction_cursor_popover_preview(
 8084                    prediction,
 8085                    cursor_point,
 8086                    style,
 8087                    cx,
 8088                )?
 8089            }
 8090
 8091            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8092                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8093                    stale_completion,
 8094                    cursor_point,
 8095                    style,
 8096                    cx,
 8097                )?,
 8098
 8099                None => {
 8100                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8101                }
 8102            },
 8103
 8104            None => pending_completion_container().child(Label::new("No Prediction")),
 8105        };
 8106
 8107        let completion = if is_refreshing {
 8108            completion
 8109                .with_animation(
 8110                    "loading-completion",
 8111                    Animation::new(Duration::from_secs(2))
 8112                        .repeat()
 8113                        .with_easing(pulsating_between(0.4, 0.8)),
 8114                    |label, delta| label.opacity(delta),
 8115                )
 8116                .into_any_element()
 8117        } else {
 8118            completion.into_any_element()
 8119        };
 8120
 8121        let has_completion = self.active_inline_completion.is_some();
 8122
 8123        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8124        Some(
 8125            h_flex()
 8126                .min_w(min_width)
 8127                .max_w(max_width)
 8128                .flex_1()
 8129                .elevation_2(cx)
 8130                .border_color(cx.theme().colors().border)
 8131                .child(
 8132                    div()
 8133                        .flex_1()
 8134                        .py_1()
 8135                        .px_2()
 8136                        .overflow_hidden()
 8137                        .child(completion),
 8138                )
 8139                .when_some(accept_keystroke, |el, accept_keystroke| {
 8140                    if !accept_keystroke.modifiers.modified() {
 8141                        return el;
 8142                    }
 8143
 8144                    el.child(
 8145                        h_flex()
 8146                            .h_full()
 8147                            .border_l_1()
 8148                            .rounded_r_lg()
 8149                            .border_color(cx.theme().colors().border)
 8150                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8151                            .gap_1()
 8152                            .py_1()
 8153                            .px_2()
 8154                            .child(
 8155                                h_flex()
 8156                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8157                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8158                                    .child(h_flex().children(ui::render_modifiers(
 8159                                        &accept_keystroke.modifiers,
 8160                                        PlatformStyle::platform(),
 8161                                        Some(if !has_completion {
 8162                                            Color::Muted
 8163                                        } else {
 8164                                            Color::Default
 8165                                        }),
 8166                                        None,
 8167                                        false,
 8168                                    ))),
 8169                            )
 8170                            .child(Label::new("Preview").into_any_element())
 8171                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8172                    )
 8173                })
 8174                .into_any(),
 8175        )
 8176    }
 8177
 8178    fn render_edit_prediction_cursor_popover_preview(
 8179        &self,
 8180        completion: &InlineCompletionState,
 8181        cursor_point: Point,
 8182        style: &EditorStyle,
 8183        cx: &mut Context<Editor>,
 8184    ) -> Option<Div> {
 8185        use text::ToPoint as _;
 8186
 8187        fn render_relative_row_jump(
 8188            prefix: impl Into<String>,
 8189            current_row: u32,
 8190            target_row: u32,
 8191        ) -> Div {
 8192            let (row_diff, arrow) = if target_row < current_row {
 8193                (current_row - target_row, IconName::ArrowUp)
 8194            } else {
 8195                (target_row - current_row, IconName::ArrowDown)
 8196            };
 8197
 8198            h_flex()
 8199                .child(
 8200                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8201                        .color(Color::Muted)
 8202                        .size(LabelSize::Small),
 8203                )
 8204                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8205        }
 8206
 8207        match &completion.completion {
 8208            InlineCompletion::Move {
 8209                target, snapshot, ..
 8210            } => Some(
 8211                h_flex()
 8212                    .px_2()
 8213                    .gap_2()
 8214                    .flex_1()
 8215                    .child(
 8216                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8217                            Icon::new(IconName::ZedPredictDown)
 8218                        } else {
 8219                            Icon::new(IconName::ZedPredictUp)
 8220                        },
 8221                    )
 8222                    .child(Label::new("Jump to Edit")),
 8223            ),
 8224
 8225            InlineCompletion::Edit {
 8226                edits,
 8227                edit_preview,
 8228                snapshot,
 8229                display_mode: _,
 8230            } => {
 8231                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8232
 8233                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8234                    &snapshot,
 8235                    &edits,
 8236                    edit_preview.as_ref()?,
 8237                    true,
 8238                    cx,
 8239                )
 8240                .first_line_preview();
 8241
 8242                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8243                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8244
 8245                let preview = h_flex()
 8246                    .gap_1()
 8247                    .min_w_16()
 8248                    .child(styled_text)
 8249                    .when(has_more_lines, |parent| parent.child(""));
 8250
 8251                let left = if first_edit_row != cursor_point.row {
 8252                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8253                        .into_any_element()
 8254                } else {
 8255                    Icon::new(IconName::ZedPredict).into_any_element()
 8256                };
 8257
 8258                Some(
 8259                    h_flex()
 8260                        .h_full()
 8261                        .flex_1()
 8262                        .gap_2()
 8263                        .pr_1()
 8264                        .overflow_x_hidden()
 8265                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8266                        .child(left)
 8267                        .child(preview),
 8268                )
 8269            }
 8270        }
 8271    }
 8272
 8273    fn render_context_menu(
 8274        &self,
 8275        style: &EditorStyle,
 8276        max_height_in_lines: u32,
 8277        window: &mut Window,
 8278        cx: &mut Context<Editor>,
 8279    ) -> Option<AnyElement> {
 8280        let menu = self.context_menu.borrow();
 8281        let menu = menu.as_ref()?;
 8282        if !menu.visible() {
 8283            return None;
 8284        };
 8285        Some(menu.render(style, max_height_in_lines, window, cx))
 8286    }
 8287
 8288    fn render_context_menu_aside(
 8289        &mut self,
 8290        max_size: Size<Pixels>,
 8291        window: &mut Window,
 8292        cx: &mut Context<Editor>,
 8293    ) -> Option<AnyElement> {
 8294        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8295            if menu.visible() {
 8296                menu.render_aside(self, max_size, window, cx)
 8297            } else {
 8298                None
 8299            }
 8300        })
 8301    }
 8302
 8303    fn hide_context_menu(
 8304        &mut self,
 8305        window: &mut Window,
 8306        cx: &mut Context<Self>,
 8307    ) -> Option<CodeContextMenu> {
 8308        cx.notify();
 8309        self.completion_tasks.clear();
 8310        let context_menu = self.context_menu.borrow_mut().take();
 8311        self.stale_inline_completion_in_menu.take();
 8312        self.update_visible_inline_completion(window, cx);
 8313        context_menu
 8314    }
 8315
 8316    fn show_snippet_choices(
 8317        &mut self,
 8318        choices: &Vec<String>,
 8319        selection: Range<Anchor>,
 8320        cx: &mut Context<Self>,
 8321    ) {
 8322        if selection.start.buffer_id.is_none() {
 8323            return;
 8324        }
 8325        let buffer_id = selection.start.buffer_id.unwrap();
 8326        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8327        let id = post_inc(&mut self.next_completion_id);
 8328        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8329
 8330        if let Some(buffer) = buffer {
 8331            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8332                CompletionsMenu::new_snippet_choices(
 8333                    id,
 8334                    true,
 8335                    choices,
 8336                    selection,
 8337                    buffer,
 8338                    snippet_sort_order,
 8339                ),
 8340            ));
 8341        }
 8342    }
 8343
 8344    pub fn insert_snippet(
 8345        &mut self,
 8346        insertion_ranges: &[Range<usize>],
 8347        snippet: Snippet,
 8348        window: &mut Window,
 8349        cx: &mut Context<Self>,
 8350    ) -> Result<()> {
 8351        struct Tabstop<T> {
 8352            is_end_tabstop: bool,
 8353            ranges: Vec<Range<T>>,
 8354            choices: Option<Vec<String>>,
 8355        }
 8356
 8357        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8358            let snippet_text: Arc<str> = snippet.text.clone().into();
 8359            let edits = insertion_ranges
 8360                .iter()
 8361                .cloned()
 8362                .map(|range| (range, snippet_text.clone()));
 8363            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8364
 8365            let snapshot = &*buffer.read(cx);
 8366            let snippet = &snippet;
 8367            snippet
 8368                .tabstops
 8369                .iter()
 8370                .map(|tabstop| {
 8371                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8372                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8373                    });
 8374                    let mut tabstop_ranges = tabstop
 8375                        .ranges
 8376                        .iter()
 8377                        .flat_map(|tabstop_range| {
 8378                            let mut delta = 0_isize;
 8379                            insertion_ranges.iter().map(move |insertion_range| {
 8380                                let insertion_start = insertion_range.start as isize + delta;
 8381                                delta +=
 8382                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8383
 8384                                let start = ((insertion_start + tabstop_range.start) as usize)
 8385                                    .min(snapshot.len());
 8386                                let end = ((insertion_start + tabstop_range.end) as usize)
 8387                                    .min(snapshot.len());
 8388                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8389                            })
 8390                        })
 8391                        .collect::<Vec<_>>();
 8392                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8393
 8394                    Tabstop {
 8395                        is_end_tabstop,
 8396                        ranges: tabstop_ranges,
 8397                        choices: tabstop.choices.clone(),
 8398                    }
 8399                })
 8400                .collect::<Vec<_>>()
 8401        });
 8402        if let Some(tabstop) = tabstops.first() {
 8403            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8404                s.select_ranges(tabstop.ranges.iter().cloned());
 8405            });
 8406
 8407            if let Some(choices) = &tabstop.choices {
 8408                if let Some(selection) = tabstop.ranges.first() {
 8409                    self.show_snippet_choices(choices, selection.clone(), cx)
 8410                }
 8411            }
 8412
 8413            // If we're already at the last tabstop and it's at the end of the snippet,
 8414            // we're done, we don't need to keep the state around.
 8415            if !tabstop.is_end_tabstop {
 8416                let choices = tabstops
 8417                    .iter()
 8418                    .map(|tabstop| tabstop.choices.clone())
 8419                    .collect();
 8420
 8421                let ranges = tabstops
 8422                    .into_iter()
 8423                    .map(|tabstop| tabstop.ranges)
 8424                    .collect::<Vec<_>>();
 8425
 8426                self.snippet_stack.push(SnippetState {
 8427                    active_index: 0,
 8428                    ranges,
 8429                    choices,
 8430                });
 8431            }
 8432
 8433            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8434            if self.autoclose_regions.is_empty() {
 8435                let snapshot = self.buffer.read(cx).snapshot(cx);
 8436                for selection in &mut self.selections.all::<Point>(cx) {
 8437                    let selection_head = selection.head();
 8438                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8439                        continue;
 8440                    };
 8441
 8442                    let mut bracket_pair = None;
 8443                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8444                    let prev_chars = snapshot
 8445                        .reversed_chars_at(selection_head)
 8446                        .collect::<String>();
 8447                    for (pair, enabled) in scope.brackets() {
 8448                        if enabled
 8449                            && pair.close
 8450                            && prev_chars.starts_with(pair.start.as_str())
 8451                            && next_chars.starts_with(pair.end.as_str())
 8452                        {
 8453                            bracket_pair = Some(pair.clone());
 8454                            break;
 8455                        }
 8456                    }
 8457                    if let Some(pair) = bracket_pair {
 8458                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8459                        let autoclose_enabled =
 8460                            self.use_autoclose && snapshot_settings.use_autoclose;
 8461                        if autoclose_enabled {
 8462                            let start = snapshot.anchor_after(selection_head);
 8463                            let end = snapshot.anchor_after(selection_head);
 8464                            self.autoclose_regions.push(AutocloseRegion {
 8465                                selection_id: selection.id,
 8466                                range: start..end,
 8467                                pair,
 8468                            });
 8469                        }
 8470                    }
 8471                }
 8472            }
 8473        }
 8474        Ok(())
 8475    }
 8476
 8477    pub fn move_to_next_snippet_tabstop(
 8478        &mut self,
 8479        window: &mut Window,
 8480        cx: &mut Context<Self>,
 8481    ) -> bool {
 8482        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8483    }
 8484
 8485    pub fn move_to_prev_snippet_tabstop(
 8486        &mut self,
 8487        window: &mut Window,
 8488        cx: &mut Context<Self>,
 8489    ) -> bool {
 8490        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8491    }
 8492
 8493    pub fn move_to_snippet_tabstop(
 8494        &mut self,
 8495        bias: Bias,
 8496        window: &mut Window,
 8497        cx: &mut Context<Self>,
 8498    ) -> bool {
 8499        if let Some(mut snippet) = self.snippet_stack.pop() {
 8500            match bias {
 8501                Bias::Left => {
 8502                    if snippet.active_index > 0 {
 8503                        snippet.active_index -= 1;
 8504                    } else {
 8505                        self.snippet_stack.push(snippet);
 8506                        return false;
 8507                    }
 8508                }
 8509                Bias::Right => {
 8510                    if snippet.active_index + 1 < snippet.ranges.len() {
 8511                        snippet.active_index += 1;
 8512                    } else {
 8513                        self.snippet_stack.push(snippet);
 8514                        return false;
 8515                    }
 8516                }
 8517            }
 8518            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8519                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8520                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8521                });
 8522
 8523                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8524                    if let Some(selection) = current_ranges.first() {
 8525                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8526                    }
 8527                }
 8528
 8529                // If snippet state is not at the last tabstop, push it back on the stack
 8530                if snippet.active_index + 1 < snippet.ranges.len() {
 8531                    self.snippet_stack.push(snippet);
 8532                }
 8533                return true;
 8534            }
 8535        }
 8536
 8537        false
 8538    }
 8539
 8540    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8541        self.transact(window, cx, |this, window, cx| {
 8542            this.select_all(&SelectAll, window, cx);
 8543            this.insert("", window, cx);
 8544        });
 8545    }
 8546
 8547    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8548        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8549        self.transact(window, cx, |this, window, cx| {
 8550            this.select_autoclose_pair(window, cx);
 8551            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8552            if !this.linked_edit_ranges.is_empty() {
 8553                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8554                let snapshot = this.buffer.read(cx).snapshot(cx);
 8555
 8556                for selection in selections.iter() {
 8557                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8558                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8559                    if selection_start.buffer_id != selection_end.buffer_id {
 8560                        continue;
 8561                    }
 8562                    if let Some(ranges) =
 8563                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8564                    {
 8565                        for (buffer, entries) in ranges {
 8566                            linked_ranges.entry(buffer).or_default().extend(entries);
 8567                        }
 8568                    }
 8569                }
 8570            }
 8571
 8572            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8573            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8574            for selection in &mut selections {
 8575                if selection.is_empty() {
 8576                    let old_head = selection.head();
 8577                    let mut new_head =
 8578                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8579                            .to_point(&display_map);
 8580                    if let Some((buffer, line_buffer_range)) = display_map
 8581                        .buffer_snapshot
 8582                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8583                    {
 8584                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8585                        let indent_len = match indent_size.kind {
 8586                            IndentKind::Space => {
 8587                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8588                            }
 8589                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8590                        };
 8591                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8592                            let indent_len = indent_len.get();
 8593                            new_head = cmp::min(
 8594                                new_head,
 8595                                MultiBufferPoint::new(
 8596                                    old_head.row,
 8597                                    ((old_head.column - 1) / indent_len) * indent_len,
 8598                                ),
 8599                            );
 8600                        }
 8601                    }
 8602
 8603                    selection.set_head(new_head, SelectionGoal::None);
 8604                }
 8605            }
 8606
 8607            this.signature_help_state.set_backspace_pressed(true);
 8608            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8609                s.select(selections)
 8610            });
 8611            this.insert("", window, cx);
 8612            let empty_str: Arc<str> = Arc::from("");
 8613            for (buffer, edits) in linked_ranges {
 8614                let snapshot = buffer.read(cx).snapshot();
 8615                use text::ToPoint as TP;
 8616
 8617                let edits = edits
 8618                    .into_iter()
 8619                    .map(|range| {
 8620                        let end_point = TP::to_point(&range.end, &snapshot);
 8621                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8622
 8623                        if end_point == start_point {
 8624                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8625                                .saturating_sub(1);
 8626                            start_point =
 8627                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8628                        };
 8629
 8630                        (start_point..end_point, empty_str.clone())
 8631                    })
 8632                    .sorted_by_key(|(range, _)| range.start)
 8633                    .collect::<Vec<_>>();
 8634                buffer.update(cx, |this, cx| {
 8635                    this.edit(edits, None, cx);
 8636                })
 8637            }
 8638            this.refresh_inline_completion(true, false, window, cx);
 8639            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8640        });
 8641    }
 8642
 8643    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8644        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8645        self.transact(window, cx, |this, window, cx| {
 8646            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8647                s.move_with(|map, selection| {
 8648                    if selection.is_empty() {
 8649                        let cursor = movement::right(map, selection.head());
 8650                        selection.end = cursor;
 8651                        selection.reversed = true;
 8652                        selection.goal = SelectionGoal::None;
 8653                    }
 8654                })
 8655            });
 8656            this.insert("", window, cx);
 8657            this.refresh_inline_completion(true, false, window, cx);
 8658        });
 8659    }
 8660
 8661    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8662        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8663        if self.move_to_prev_snippet_tabstop(window, cx) {
 8664            return;
 8665        }
 8666        self.outdent(&Outdent, window, cx);
 8667    }
 8668
 8669    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8670        if self.move_to_next_snippet_tabstop(window, cx) {
 8671            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8672            return;
 8673        }
 8674        if self.read_only(cx) {
 8675            return;
 8676        }
 8677        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8678        let mut selections = self.selections.all_adjusted(cx);
 8679        let buffer = self.buffer.read(cx);
 8680        let snapshot = buffer.snapshot(cx);
 8681        let rows_iter = selections.iter().map(|s| s.head().row);
 8682        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8683
 8684        let has_some_cursor_in_whitespace = selections
 8685            .iter()
 8686            .filter(|selection| selection.is_empty())
 8687            .any(|selection| {
 8688                let cursor = selection.head();
 8689                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8690                cursor.column < current_indent.len
 8691            });
 8692
 8693        let mut edits = Vec::new();
 8694        let mut prev_edited_row = 0;
 8695        let mut row_delta = 0;
 8696        for selection in &mut selections {
 8697            if selection.start.row != prev_edited_row {
 8698                row_delta = 0;
 8699            }
 8700            prev_edited_row = selection.end.row;
 8701
 8702            // If the selection is non-empty, then increase the indentation of the selected lines.
 8703            if !selection.is_empty() {
 8704                row_delta =
 8705                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8706                continue;
 8707            }
 8708
 8709            // If the selection is empty and the cursor is in the leading whitespace before the
 8710            // suggested indentation, then auto-indent the line.
 8711            let cursor = selection.head();
 8712            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8713            if let Some(suggested_indent) =
 8714                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8715            {
 8716                // If there exist any empty selection in the leading whitespace, then skip
 8717                // indent for selections at the boundary.
 8718                if has_some_cursor_in_whitespace
 8719                    && cursor.column == current_indent.len
 8720                    && current_indent.len == suggested_indent.len
 8721                {
 8722                    continue;
 8723                }
 8724
 8725                if cursor.column < suggested_indent.len
 8726                    && cursor.column <= current_indent.len
 8727                    && current_indent.len <= suggested_indent.len
 8728                {
 8729                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8730                    selection.end = selection.start;
 8731                    if row_delta == 0 {
 8732                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8733                            cursor.row,
 8734                            current_indent,
 8735                            suggested_indent,
 8736                        ));
 8737                        row_delta = suggested_indent.len - current_indent.len;
 8738                    }
 8739                    continue;
 8740                }
 8741            }
 8742
 8743            // Otherwise, insert a hard or soft tab.
 8744            let settings = buffer.language_settings_at(cursor, cx);
 8745            let tab_size = if settings.hard_tabs {
 8746                IndentSize::tab()
 8747            } else {
 8748                let tab_size = settings.tab_size.get();
 8749                let indent_remainder = snapshot
 8750                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8751                    .flat_map(str::chars)
 8752                    .fold(row_delta % tab_size, |counter: u32, c| {
 8753                        if c == '\t' {
 8754                            0
 8755                        } else {
 8756                            (counter + 1) % tab_size
 8757                        }
 8758                    });
 8759
 8760                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8761                IndentSize::spaces(chars_to_next_tab_stop)
 8762            };
 8763            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8764            selection.end = selection.start;
 8765            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8766            row_delta += tab_size.len;
 8767        }
 8768
 8769        self.transact(window, cx, |this, window, cx| {
 8770            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8771            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8772                s.select(selections)
 8773            });
 8774            this.refresh_inline_completion(true, false, window, cx);
 8775        });
 8776    }
 8777
 8778    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8779        if self.read_only(cx) {
 8780            return;
 8781        }
 8782        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8783        let mut selections = self.selections.all::<Point>(cx);
 8784        let mut prev_edited_row = 0;
 8785        let mut row_delta = 0;
 8786        let mut edits = Vec::new();
 8787        let buffer = self.buffer.read(cx);
 8788        let snapshot = buffer.snapshot(cx);
 8789        for selection in &mut selections {
 8790            if selection.start.row != prev_edited_row {
 8791                row_delta = 0;
 8792            }
 8793            prev_edited_row = selection.end.row;
 8794
 8795            row_delta =
 8796                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8797        }
 8798
 8799        self.transact(window, cx, |this, window, cx| {
 8800            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8801            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8802                s.select(selections)
 8803            });
 8804        });
 8805    }
 8806
 8807    fn indent_selection(
 8808        buffer: &MultiBuffer,
 8809        snapshot: &MultiBufferSnapshot,
 8810        selection: &mut Selection<Point>,
 8811        edits: &mut Vec<(Range<Point>, String)>,
 8812        delta_for_start_row: u32,
 8813        cx: &App,
 8814    ) -> u32 {
 8815        let settings = buffer.language_settings_at(selection.start, cx);
 8816        let tab_size = settings.tab_size.get();
 8817        let indent_kind = if settings.hard_tabs {
 8818            IndentKind::Tab
 8819        } else {
 8820            IndentKind::Space
 8821        };
 8822        let mut start_row = selection.start.row;
 8823        let mut end_row = selection.end.row + 1;
 8824
 8825        // If a selection ends at the beginning of a line, don't indent
 8826        // that last line.
 8827        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8828            end_row -= 1;
 8829        }
 8830
 8831        // Avoid re-indenting a row that has already been indented by a
 8832        // previous selection, but still update this selection's column
 8833        // to reflect that indentation.
 8834        if delta_for_start_row > 0 {
 8835            start_row += 1;
 8836            selection.start.column += delta_for_start_row;
 8837            if selection.end.row == selection.start.row {
 8838                selection.end.column += delta_for_start_row;
 8839            }
 8840        }
 8841
 8842        let mut delta_for_end_row = 0;
 8843        let has_multiple_rows = start_row + 1 != end_row;
 8844        for row in start_row..end_row {
 8845            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8846            let indent_delta = match (current_indent.kind, indent_kind) {
 8847                (IndentKind::Space, IndentKind::Space) => {
 8848                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8849                    IndentSize::spaces(columns_to_next_tab_stop)
 8850                }
 8851                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8852                (_, IndentKind::Tab) => IndentSize::tab(),
 8853            };
 8854
 8855            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8856                0
 8857            } else {
 8858                selection.start.column
 8859            };
 8860            let row_start = Point::new(row, start);
 8861            edits.push((
 8862                row_start..row_start,
 8863                indent_delta.chars().collect::<String>(),
 8864            ));
 8865
 8866            // Update this selection's endpoints to reflect the indentation.
 8867            if row == selection.start.row {
 8868                selection.start.column += indent_delta.len;
 8869            }
 8870            if row == selection.end.row {
 8871                selection.end.column += indent_delta.len;
 8872                delta_for_end_row = indent_delta.len;
 8873            }
 8874        }
 8875
 8876        if selection.start.row == selection.end.row {
 8877            delta_for_start_row + delta_for_end_row
 8878        } else {
 8879            delta_for_end_row
 8880        }
 8881    }
 8882
 8883    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8884        if self.read_only(cx) {
 8885            return;
 8886        }
 8887        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8888        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8889        let selections = self.selections.all::<Point>(cx);
 8890        let mut deletion_ranges = Vec::new();
 8891        let mut last_outdent = None;
 8892        {
 8893            let buffer = self.buffer.read(cx);
 8894            let snapshot = buffer.snapshot(cx);
 8895            for selection in &selections {
 8896                let settings = buffer.language_settings_at(selection.start, cx);
 8897                let tab_size = settings.tab_size.get();
 8898                let mut rows = selection.spanned_rows(false, &display_map);
 8899
 8900                // Avoid re-outdenting a row that has already been outdented by a
 8901                // previous selection.
 8902                if let Some(last_row) = last_outdent {
 8903                    if last_row == rows.start {
 8904                        rows.start = rows.start.next_row();
 8905                    }
 8906                }
 8907                let has_multiple_rows = rows.len() > 1;
 8908                for row in rows.iter_rows() {
 8909                    let indent_size = snapshot.indent_size_for_line(row);
 8910                    if indent_size.len > 0 {
 8911                        let deletion_len = match indent_size.kind {
 8912                            IndentKind::Space => {
 8913                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8914                                if columns_to_prev_tab_stop == 0 {
 8915                                    tab_size
 8916                                } else {
 8917                                    columns_to_prev_tab_stop
 8918                                }
 8919                            }
 8920                            IndentKind::Tab => 1,
 8921                        };
 8922                        let start = if has_multiple_rows
 8923                            || deletion_len > selection.start.column
 8924                            || indent_size.len < selection.start.column
 8925                        {
 8926                            0
 8927                        } else {
 8928                            selection.start.column - deletion_len
 8929                        };
 8930                        deletion_ranges.push(
 8931                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8932                        );
 8933                        last_outdent = Some(row);
 8934                    }
 8935                }
 8936            }
 8937        }
 8938
 8939        self.transact(window, cx, |this, window, cx| {
 8940            this.buffer.update(cx, |buffer, cx| {
 8941                let empty_str: Arc<str> = Arc::default();
 8942                buffer.edit(
 8943                    deletion_ranges
 8944                        .into_iter()
 8945                        .map(|range| (range, empty_str.clone())),
 8946                    None,
 8947                    cx,
 8948                );
 8949            });
 8950            let selections = this.selections.all::<usize>(cx);
 8951            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8952                s.select(selections)
 8953            });
 8954        });
 8955    }
 8956
 8957    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8958        if self.read_only(cx) {
 8959            return;
 8960        }
 8961        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8962        let selections = self
 8963            .selections
 8964            .all::<usize>(cx)
 8965            .into_iter()
 8966            .map(|s| s.range());
 8967
 8968        self.transact(window, cx, |this, window, cx| {
 8969            this.buffer.update(cx, |buffer, cx| {
 8970                buffer.autoindent_ranges(selections, cx);
 8971            });
 8972            let selections = this.selections.all::<usize>(cx);
 8973            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8974                s.select(selections)
 8975            });
 8976        });
 8977    }
 8978
 8979    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8980        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8982        let selections = self.selections.all::<Point>(cx);
 8983
 8984        let mut new_cursors = Vec::new();
 8985        let mut edit_ranges = Vec::new();
 8986        let mut selections = selections.iter().peekable();
 8987        while let Some(selection) = selections.next() {
 8988            let mut rows = selection.spanned_rows(false, &display_map);
 8989            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8990
 8991            // Accumulate contiguous regions of rows that we want to delete.
 8992            while let Some(next_selection) = selections.peek() {
 8993                let next_rows = next_selection.spanned_rows(false, &display_map);
 8994                if next_rows.start <= rows.end {
 8995                    rows.end = next_rows.end;
 8996                    selections.next().unwrap();
 8997                } else {
 8998                    break;
 8999                }
 9000            }
 9001
 9002            let buffer = &display_map.buffer_snapshot;
 9003            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 9004            let edit_end;
 9005            let cursor_buffer_row;
 9006            if buffer.max_point().row >= rows.end.0 {
 9007                // If there's a line after the range, delete the \n from the end of the row range
 9008                // and position the cursor on the next line.
 9009                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 9010                cursor_buffer_row = rows.end;
 9011            } else {
 9012                // If there isn't a line after the range, delete the \n from the line before the
 9013                // start of the row range and position the cursor there.
 9014                edit_start = edit_start.saturating_sub(1);
 9015                edit_end = buffer.len();
 9016                cursor_buffer_row = rows.start.previous_row();
 9017            }
 9018
 9019            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 9020            *cursor.column_mut() =
 9021                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 9022
 9023            new_cursors.push((
 9024                selection.id,
 9025                buffer.anchor_after(cursor.to_point(&display_map)),
 9026            ));
 9027            edit_ranges.push(edit_start..edit_end);
 9028        }
 9029
 9030        self.transact(window, cx, |this, window, cx| {
 9031            let buffer = this.buffer.update(cx, |buffer, cx| {
 9032                let empty_str: Arc<str> = Arc::default();
 9033                buffer.edit(
 9034                    edit_ranges
 9035                        .into_iter()
 9036                        .map(|range| (range, empty_str.clone())),
 9037                    None,
 9038                    cx,
 9039                );
 9040                buffer.snapshot(cx)
 9041            });
 9042            let new_selections = new_cursors
 9043                .into_iter()
 9044                .map(|(id, cursor)| {
 9045                    let cursor = cursor.to_point(&buffer);
 9046                    Selection {
 9047                        id,
 9048                        start: cursor,
 9049                        end: cursor,
 9050                        reversed: false,
 9051                        goal: SelectionGoal::None,
 9052                    }
 9053                })
 9054                .collect();
 9055
 9056            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9057                s.select(new_selections);
 9058            });
 9059        });
 9060    }
 9061
 9062    pub fn join_lines_impl(
 9063        &mut self,
 9064        insert_whitespace: bool,
 9065        window: &mut Window,
 9066        cx: &mut Context<Self>,
 9067    ) {
 9068        if self.read_only(cx) {
 9069            return;
 9070        }
 9071        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9072        for selection in self.selections.all::<Point>(cx) {
 9073            let start = MultiBufferRow(selection.start.row);
 9074            // Treat single line selections as if they include the next line. Otherwise this action
 9075            // would do nothing for single line selections individual cursors.
 9076            let end = if selection.start.row == selection.end.row {
 9077                MultiBufferRow(selection.start.row + 1)
 9078            } else {
 9079                MultiBufferRow(selection.end.row)
 9080            };
 9081
 9082            if let Some(last_row_range) = row_ranges.last_mut() {
 9083                if start <= last_row_range.end {
 9084                    last_row_range.end = end;
 9085                    continue;
 9086                }
 9087            }
 9088            row_ranges.push(start..end);
 9089        }
 9090
 9091        let snapshot = self.buffer.read(cx).snapshot(cx);
 9092        let mut cursor_positions = Vec::new();
 9093        for row_range in &row_ranges {
 9094            let anchor = snapshot.anchor_before(Point::new(
 9095                row_range.end.previous_row().0,
 9096                snapshot.line_len(row_range.end.previous_row()),
 9097            ));
 9098            cursor_positions.push(anchor..anchor);
 9099        }
 9100
 9101        self.transact(window, cx, |this, window, cx| {
 9102            for row_range in row_ranges.into_iter().rev() {
 9103                for row in row_range.iter_rows().rev() {
 9104                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9105                    let next_line_row = row.next_row();
 9106                    let indent = snapshot.indent_size_for_line(next_line_row);
 9107                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9108
 9109                    let replace =
 9110                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9111                            " "
 9112                        } else {
 9113                            ""
 9114                        };
 9115
 9116                    this.buffer.update(cx, |buffer, cx| {
 9117                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9118                    });
 9119                }
 9120            }
 9121
 9122            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9123                s.select_anchor_ranges(cursor_positions)
 9124            });
 9125        });
 9126    }
 9127
 9128    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9129        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9130        self.join_lines_impl(true, window, cx);
 9131    }
 9132
 9133    pub fn sort_lines_case_sensitive(
 9134        &mut self,
 9135        _: &SortLinesCaseSensitive,
 9136        window: &mut Window,
 9137        cx: &mut Context<Self>,
 9138    ) {
 9139        self.manipulate_lines(window, cx, |lines| lines.sort())
 9140    }
 9141
 9142    pub fn sort_lines_case_insensitive(
 9143        &mut self,
 9144        _: &SortLinesCaseInsensitive,
 9145        window: &mut Window,
 9146        cx: &mut Context<Self>,
 9147    ) {
 9148        self.manipulate_lines(window, cx, |lines| {
 9149            lines.sort_by_key(|line| line.to_lowercase())
 9150        })
 9151    }
 9152
 9153    pub fn unique_lines_case_insensitive(
 9154        &mut self,
 9155        _: &UniqueLinesCaseInsensitive,
 9156        window: &mut Window,
 9157        cx: &mut Context<Self>,
 9158    ) {
 9159        self.manipulate_lines(window, cx, |lines| {
 9160            let mut seen = HashSet::default();
 9161            lines.retain(|line| seen.insert(line.to_lowercase()));
 9162        })
 9163    }
 9164
 9165    pub fn unique_lines_case_sensitive(
 9166        &mut self,
 9167        _: &UniqueLinesCaseSensitive,
 9168        window: &mut Window,
 9169        cx: &mut Context<Self>,
 9170    ) {
 9171        self.manipulate_lines(window, cx, |lines| {
 9172            let mut seen = HashSet::default();
 9173            lines.retain(|line| seen.insert(*line));
 9174        })
 9175    }
 9176
 9177    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9178        let Some(project) = self.project.clone() else {
 9179            return;
 9180        };
 9181        self.reload(project, window, cx)
 9182            .detach_and_notify_err(window, cx);
 9183    }
 9184
 9185    pub fn restore_file(
 9186        &mut self,
 9187        _: &::git::RestoreFile,
 9188        window: &mut Window,
 9189        cx: &mut Context<Self>,
 9190    ) {
 9191        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9192        let mut buffer_ids = HashSet::default();
 9193        let snapshot = self.buffer().read(cx).snapshot(cx);
 9194        for selection in self.selections.all::<usize>(cx) {
 9195            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9196        }
 9197
 9198        let buffer = self.buffer().read(cx);
 9199        let ranges = buffer_ids
 9200            .into_iter()
 9201            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9202            .collect::<Vec<_>>();
 9203
 9204        self.restore_hunks_in_ranges(ranges, window, cx);
 9205    }
 9206
 9207    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9208        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9209        let selections = self
 9210            .selections
 9211            .all(cx)
 9212            .into_iter()
 9213            .map(|s| s.range())
 9214            .collect();
 9215        self.restore_hunks_in_ranges(selections, window, cx);
 9216    }
 9217
 9218    pub fn restore_hunks_in_ranges(
 9219        &mut self,
 9220        ranges: Vec<Range<Point>>,
 9221        window: &mut Window,
 9222        cx: &mut Context<Editor>,
 9223    ) {
 9224        let mut revert_changes = HashMap::default();
 9225        let chunk_by = self
 9226            .snapshot(window, cx)
 9227            .hunks_for_ranges(ranges)
 9228            .into_iter()
 9229            .chunk_by(|hunk| hunk.buffer_id);
 9230        for (buffer_id, hunks) in &chunk_by {
 9231            let hunks = hunks.collect::<Vec<_>>();
 9232            for hunk in &hunks {
 9233                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9234            }
 9235            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9236        }
 9237        drop(chunk_by);
 9238        if !revert_changes.is_empty() {
 9239            self.transact(window, cx, |editor, window, cx| {
 9240                editor.restore(revert_changes, window, cx);
 9241            });
 9242        }
 9243    }
 9244
 9245    pub fn open_active_item_in_terminal(
 9246        &mut self,
 9247        _: &OpenInTerminal,
 9248        window: &mut Window,
 9249        cx: &mut Context<Self>,
 9250    ) {
 9251        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9252            let project_path = buffer.read(cx).project_path(cx)?;
 9253            let project = self.project.as_ref()?.read(cx);
 9254            let entry = project.entry_for_path(&project_path, cx)?;
 9255            let parent = match &entry.canonical_path {
 9256                Some(canonical_path) => canonical_path.to_path_buf(),
 9257                None => project.absolute_path(&project_path, cx)?,
 9258            }
 9259            .parent()?
 9260            .to_path_buf();
 9261            Some(parent)
 9262        }) {
 9263            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9264        }
 9265    }
 9266
 9267    fn set_breakpoint_context_menu(
 9268        &mut self,
 9269        display_row: DisplayRow,
 9270        position: Option<Anchor>,
 9271        clicked_point: gpui::Point<Pixels>,
 9272        window: &mut Window,
 9273        cx: &mut Context<Self>,
 9274    ) {
 9275        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9276            return;
 9277        }
 9278        let source = self
 9279            .buffer
 9280            .read(cx)
 9281            .snapshot(cx)
 9282            .anchor_before(Point::new(display_row.0, 0u32));
 9283
 9284        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9285
 9286        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9287            self,
 9288            source,
 9289            clicked_point,
 9290            context_menu,
 9291            window,
 9292            cx,
 9293        );
 9294    }
 9295
 9296    fn add_edit_breakpoint_block(
 9297        &mut self,
 9298        anchor: Anchor,
 9299        breakpoint: &Breakpoint,
 9300        edit_action: BreakpointPromptEditAction,
 9301        window: &mut Window,
 9302        cx: &mut Context<Self>,
 9303    ) {
 9304        let weak_editor = cx.weak_entity();
 9305        let bp_prompt = cx.new(|cx| {
 9306            BreakpointPromptEditor::new(
 9307                weak_editor,
 9308                anchor,
 9309                breakpoint.clone(),
 9310                edit_action,
 9311                window,
 9312                cx,
 9313            )
 9314        });
 9315
 9316        let height = bp_prompt.update(cx, |this, cx| {
 9317            this.prompt
 9318                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9319        });
 9320        let cloned_prompt = bp_prompt.clone();
 9321        let blocks = vec![BlockProperties {
 9322            style: BlockStyle::Sticky,
 9323            placement: BlockPlacement::Above(anchor),
 9324            height: Some(height),
 9325            render: Arc::new(move |cx| {
 9326                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9327                cloned_prompt.clone().into_any_element()
 9328            }),
 9329            priority: 0,
 9330        }];
 9331
 9332        let focus_handle = bp_prompt.focus_handle(cx);
 9333        window.focus(&focus_handle);
 9334
 9335        let block_ids = self.insert_blocks(blocks, None, cx);
 9336        bp_prompt.update(cx, |prompt, _| {
 9337            prompt.add_block_ids(block_ids);
 9338        });
 9339    }
 9340
 9341    pub(crate) fn breakpoint_at_row(
 9342        &self,
 9343        row: u32,
 9344        window: &mut Window,
 9345        cx: &mut Context<Self>,
 9346    ) -> Option<(Anchor, Breakpoint)> {
 9347        let snapshot = self.snapshot(window, cx);
 9348        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9349
 9350        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9351    }
 9352
 9353    pub(crate) fn breakpoint_at_anchor(
 9354        &self,
 9355        breakpoint_position: Anchor,
 9356        snapshot: &EditorSnapshot,
 9357        cx: &mut Context<Self>,
 9358    ) -> Option<(Anchor, Breakpoint)> {
 9359        let project = self.project.clone()?;
 9360
 9361        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9362            snapshot
 9363                .buffer_snapshot
 9364                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9365        })?;
 9366
 9367        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9368        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9369        let buffer_snapshot = buffer.read(cx).snapshot();
 9370
 9371        let row = buffer_snapshot
 9372            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9373            .row;
 9374
 9375        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9376        let anchor_end = snapshot
 9377            .buffer_snapshot
 9378            .anchor_after(Point::new(row, line_len));
 9379
 9380        let bp = self
 9381            .breakpoint_store
 9382            .as_ref()?
 9383            .read_with(cx, |breakpoint_store, cx| {
 9384                breakpoint_store
 9385                    .breakpoints(
 9386                        &buffer,
 9387                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9388                        &buffer_snapshot,
 9389                        cx,
 9390                    )
 9391                    .next()
 9392                    .and_then(|(anchor, bp)| {
 9393                        let breakpoint_row = buffer_snapshot
 9394                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9395                            .row;
 9396
 9397                        if breakpoint_row == row {
 9398                            snapshot
 9399                                .buffer_snapshot
 9400                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9401                                .map(|anchor| (anchor, bp.clone()))
 9402                        } else {
 9403                            None
 9404                        }
 9405                    })
 9406            });
 9407        bp
 9408    }
 9409
 9410    pub fn edit_log_breakpoint(
 9411        &mut self,
 9412        _: &EditLogBreakpoint,
 9413        window: &mut Window,
 9414        cx: &mut Context<Self>,
 9415    ) {
 9416        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9417            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9418                message: None,
 9419                state: BreakpointState::Enabled,
 9420                condition: None,
 9421                hit_condition: None,
 9422            });
 9423
 9424            self.add_edit_breakpoint_block(
 9425                anchor,
 9426                &breakpoint,
 9427                BreakpointPromptEditAction::Log,
 9428                window,
 9429                cx,
 9430            );
 9431        }
 9432    }
 9433
 9434    fn breakpoints_at_cursors(
 9435        &self,
 9436        window: &mut Window,
 9437        cx: &mut Context<Self>,
 9438    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9439        let snapshot = self.snapshot(window, cx);
 9440        let cursors = self
 9441            .selections
 9442            .disjoint_anchors()
 9443            .into_iter()
 9444            .map(|selection| {
 9445                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9446
 9447                let breakpoint_position = self
 9448                    .breakpoint_at_row(cursor_position.row, window, cx)
 9449                    .map(|bp| bp.0)
 9450                    .unwrap_or_else(|| {
 9451                        snapshot
 9452                            .display_snapshot
 9453                            .buffer_snapshot
 9454                            .anchor_after(Point::new(cursor_position.row, 0))
 9455                    });
 9456
 9457                let breakpoint = self
 9458                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9459                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9460
 9461                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9462            })
 9463            // 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.
 9464            .collect::<HashMap<Anchor, _>>();
 9465
 9466        cursors.into_iter().collect()
 9467    }
 9468
 9469    pub fn enable_breakpoint(
 9470        &mut self,
 9471        _: &crate::actions::EnableBreakpoint,
 9472        window: &mut Window,
 9473        cx: &mut Context<Self>,
 9474    ) {
 9475        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9476            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9477                continue;
 9478            };
 9479            self.edit_breakpoint_at_anchor(
 9480                anchor,
 9481                breakpoint,
 9482                BreakpointEditAction::InvertState,
 9483                cx,
 9484            );
 9485        }
 9486    }
 9487
 9488    pub fn disable_breakpoint(
 9489        &mut self,
 9490        _: &crate::actions::DisableBreakpoint,
 9491        window: &mut Window,
 9492        cx: &mut Context<Self>,
 9493    ) {
 9494        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9495            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9496                continue;
 9497            };
 9498            self.edit_breakpoint_at_anchor(
 9499                anchor,
 9500                breakpoint,
 9501                BreakpointEditAction::InvertState,
 9502                cx,
 9503            );
 9504        }
 9505    }
 9506
 9507    pub fn toggle_breakpoint(
 9508        &mut self,
 9509        _: &crate::actions::ToggleBreakpoint,
 9510        window: &mut Window,
 9511        cx: &mut Context<Self>,
 9512    ) {
 9513        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9514            if let Some(breakpoint) = breakpoint {
 9515                self.edit_breakpoint_at_anchor(
 9516                    anchor,
 9517                    breakpoint,
 9518                    BreakpointEditAction::Toggle,
 9519                    cx,
 9520                );
 9521            } else {
 9522                self.edit_breakpoint_at_anchor(
 9523                    anchor,
 9524                    Breakpoint::new_standard(),
 9525                    BreakpointEditAction::Toggle,
 9526                    cx,
 9527                );
 9528            }
 9529        }
 9530    }
 9531
 9532    pub fn edit_breakpoint_at_anchor(
 9533        &mut self,
 9534        breakpoint_position: Anchor,
 9535        breakpoint: Breakpoint,
 9536        edit_action: BreakpointEditAction,
 9537        cx: &mut Context<Self>,
 9538    ) {
 9539        let Some(breakpoint_store) = &self.breakpoint_store else {
 9540            return;
 9541        };
 9542
 9543        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9544            if breakpoint_position == Anchor::min() {
 9545                self.buffer()
 9546                    .read(cx)
 9547                    .excerpt_buffer_ids()
 9548                    .into_iter()
 9549                    .next()
 9550            } else {
 9551                None
 9552            }
 9553        }) else {
 9554            return;
 9555        };
 9556
 9557        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9558            return;
 9559        };
 9560
 9561        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9562            breakpoint_store.toggle_breakpoint(
 9563                buffer,
 9564                (breakpoint_position.text_anchor, breakpoint),
 9565                edit_action,
 9566                cx,
 9567            );
 9568        });
 9569
 9570        cx.notify();
 9571    }
 9572
 9573    #[cfg(any(test, feature = "test-support"))]
 9574    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9575        self.breakpoint_store.clone()
 9576    }
 9577
 9578    pub fn prepare_restore_change(
 9579        &self,
 9580        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9581        hunk: &MultiBufferDiffHunk,
 9582        cx: &mut App,
 9583    ) -> Option<()> {
 9584        if hunk.is_created_file() {
 9585            return None;
 9586        }
 9587        let buffer = self.buffer.read(cx);
 9588        let diff = buffer.diff_for(hunk.buffer_id)?;
 9589        let buffer = buffer.buffer(hunk.buffer_id)?;
 9590        let buffer = buffer.read(cx);
 9591        let original_text = diff
 9592            .read(cx)
 9593            .base_text()
 9594            .as_rope()
 9595            .slice(hunk.diff_base_byte_range.clone());
 9596        let buffer_snapshot = buffer.snapshot();
 9597        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9598        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9599            probe
 9600                .0
 9601                .start
 9602                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9603                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9604        }) {
 9605            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9606            Some(())
 9607        } else {
 9608            None
 9609        }
 9610    }
 9611
 9612    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9613        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9614    }
 9615
 9616    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9617        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9618    }
 9619
 9620    fn manipulate_lines<Fn>(
 9621        &mut self,
 9622        window: &mut Window,
 9623        cx: &mut Context<Self>,
 9624        mut callback: Fn,
 9625    ) where
 9626        Fn: FnMut(&mut Vec<&str>),
 9627    {
 9628        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9629
 9630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9631        let buffer = self.buffer.read(cx).snapshot(cx);
 9632
 9633        let mut edits = Vec::new();
 9634
 9635        let selections = self.selections.all::<Point>(cx);
 9636        let mut selections = selections.iter().peekable();
 9637        let mut contiguous_row_selections = Vec::new();
 9638        let mut new_selections = Vec::new();
 9639        let mut added_lines = 0;
 9640        let mut removed_lines = 0;
 9641
 9642        while let Some(selection) = selections.next() {
 9643            let (start_row, end_row) = consume_contiguous_rows(
 9644                &mut contiguous_row_selections,
 9645                selection,
 9646                &display_map,
 9647                &mut selections,
 9648            );
 9649
 9650            let start_point = Point::new(start_row.0, 0);
 9651            let end_point = Point::new(
 9652                end_row.previous_row().0,
 9653                buffer.line_len(end_row.previous_row()),
 9654            );
 9655            let text = buffer
 9656                .text_for_range(start_point..end_point)
 9657                .collect::<String>();
 9658
 9659            let mut lines = text.split('\n').collect_vec();
 9660
 9661            let lines_before = lines.len();
 9662            callback(&mut lines);
 9663            let lines_after = lines.len();
 9664
 9665            edits.push((start_point..end_point, lines.join("\n")));
 9666
 9667            // Selections must change based on added and removed line count
 9668            let start_row =
 9669                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9670            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9671            new_selections.push(Selection {
 9672                id: selection.id,
 9673                start: start_row,
 9674                end: end_row,
 9675                goal: SelectionGoal::None,
 9676                reversed: selection.reversed,
 9677            });
 9678
 9679            if lines_after > lines_before {
 9680                added_lines += lines_after - lines_before;
 9681            } else if lines_before > lines_after {
 9682                removed_lines += lines_before - lines_after;
 9683            }
 9684        }
 9685
 9686        self.transact(window, cx, |this, window, cx| {
 9687            let buffer = this.buffer.update(cx, |buffer, cx| {
 9688                buffer.edit(edits, None, cx);
 9689                buffer.snapshot(cx)
 9690            });
 9691
 9692            // Recalculate offsets on newly edited buffer
 9693            let new_selections = new_selections
 9694                .iter()
 9695                .map(|s| {
 9696                    let start_point = Point::new(s.start.0, 0);
 9697                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9698                    Selection {
 9699                        id: s.id,
 9700                        start: buffer.point_to_offset(start_point),
 9701                        end: buffer.point_to_offset(end_point),
 9702                        goal: s.goal,
 9703                        reversed: s.reversed,
 9704                    }
 9705                })
 9706                .collect();
 9707
 9708            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9709                s.select(new_selections);
 9710            });
 9711
 9712            this.request_autoscroll(Autoscroll::fit(), cx);
 9713        });
 9714    }
 9715
 9716    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9717        self.manipulate_text(window, cx, |text| {
 9718            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9719            if has_upper_case_characters {
 9720                text.to_lowercase()
 9721            } else {
 9722                text.to_uppercase()
 9723            }
 9724        })
 9725    }
 9726
 9727    pub fn convert_to_upper_case(
 9728        &mut self,
 9729        _: &ConvertToUpperCase,
 9730        window: &mut Window,
 9731        cx: &mut Context<Self>,
 9732    ) {
 9733        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9734    }
 9735
 9736    pub fn convert_to_lower_case(
 9737        &mut self,
 9738        _: &ConvertToLowerCase,
 9739        window: &mut Window,
 9740        cx: &mut Context<Self>,
 9741    ) {
 9742        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9743    }
 9744
 9745    pub fn convert_to_title_case(
 9746        &mut self,
 9747        _: &ConvertToTitleCase,
 9748        window: &mut Window,
 9749        cx: &mut Context<Self>,
 9750    ) {
 9751        self.manipulate_text(window, cx, |text| {
 9752            text.split('\n')
 9753                .map(|line| line.to_case(Case::Title))
 9754                .join("\n")
 9755        })
 9756    }
 9757
 9758    pub fn convert_to_snake_case(
 9759        &mut self,
 9760        _: &ConvertToSnakeCase,
 9761        window: &mut Window,
 9762        cx: &mut Context<Self>,
 9763    ) {
 9764        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9765    }
 9766
 9767    pub fn convert_to_kebab_case(
 9768        &mut self,
 9769        _: &ConvertToKebabCase,
 9770        window: &mut Window,
 9771        cx: &mut Context<Self>,
 9772    ) {
 9773        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9774    }
 9775
 9776    pub fn convert_to_upper_camel_case(
 9777        &mut self,
 9778        _: &ConvertToUpperCamelCase,
 9779        window: &mut Window,
 9780        cx: &mut Context<Self>,
 9781    ) {
 9782        self.manipulate_text(window, cx, |text| {
 9783            text.split('\n')
 9784                .map(|line| line.to_case(Case::UpperCamel))
 9785                .join("\n")
 9786        })
 9787    }
 9788
 9789    pub fn convert_to_lower_camel_case(
 9790        &mut self,
 9791        _: &ConvertToLowerCamelCase,
 9792        window: &mut Window,
 9793        cx: &mut Context<Self>,
 9794    ) {
 9795        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9796    }
 9797
 9798    pub fn convert_to_opposite_case(
 9799        &mut self,
 9800        _: &ConvertToOppositeCase,
 9801        window: &mut Window,
 9802        cx: &mut Context<Self>,
 9803    ) {
 9804        self.manipulate_text(window, cx, |text| {
 9805            text.chars()
 9806                .fold(String::with_capacity(text.len()), |mut t, c| {
 9807                    if c.is_uppercase() {
 9808                        t.extend(c.to_lowercase());
 9809                    } else {
 9810                        t.extend(c.to_uppercase());
 9811                    }
 9812                    t
 9813                })
 9814        })
 9815    }
 9816
 9817    pub fn convert_to_rot13(
 9818        &mut self,
 9819        _: &ConvertToRot13,
 9820        window: &mut Window,
 9821        cx: &mut Context<Self>,
 9822    ) {
 9823        self.manipulate_text(window, cx, |text| {
 9824            text.chars()
 9825                .map(|c| match c {
 9826                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9827                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9828                    _ => c,
 9829                })
 9830                .collect()
 9831        })
 9832    }
 9833
 9834    pub fn convert_to_rot47(
 9835        &mut self,
 9836        _: &ConvertToRot47,
 9837        window: &mut Window,
 9838        cx: &mut Context<Self>,
 9839    ) {
 9840        self.manipulate_text(window, cx, |text| {
 9841            text.chars()
 9842                .map(|c| {
 9843                    let code_point = c as u32;
 9844                    if code_point >= 33 && code_point <= 126 {
 9845                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9846                    }
 9847                    c
 9848                })
 9849                .collect()
 9850        })
 9851    }
 9852
 9853    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9854    where
 9855        Fn: FnMut(&str) -> String,
 9856    {
 9857        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9858        let buffer = self.buffer.read(cx).snapshot(cx);
 9859
 9860        let mut new_selections = Vec::new();
 9861        let mut edits = Vec::new();
 9862        let mut selection_adjustment = 0i32;
 9863
 9864        for selection in self.selections.all::<usize>(cx) {
 9865            let selection_is_empty = selection.is_empty();
 9866
 9867            let (start, end) = if selection_is_empty {
 9868                let word_range = movement::surrounding_word(
 9869                    &display_map,
 9870                    selection.start.to_display_point(&display_map),
 9871                );
 9872                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9873                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9874                (start, end)
 9875            } else {
 9876                (selection.start, selection.end)
 9877            };
 9878
 9879            let text = buffer.text_for_range(start..end).collect::<String>();
 9880            let old_length = text.len() as i32;
 9881            let text = callback(&text);
 9882
 9883            new_selections.push(Selection {
 9884                start: (start as i32 - selection_adjustment) as usize,
 9885                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9886                goal: SelectionGoal::None,
 9887                ..selection
 9888            });
 9889
 9890            selection_adjustment += old_length - text.len() as i32;
 9891
 9892            edits.push((start..end, text));
 9893        }
 9894
 9895        self.transact(window, cx, |this, window, cx| {
 9896            this.buffer.update(cx, |buffer, cx| {
 9897                buffer.edit(edits, None, cx);
 9898            });
 9899
 9900            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9901                s.select(new_selections);
 9902            });
 9903
 9904            this.request_autoscroll(Autoscroll::fit(), cx);
 9905        });
 9906    }
 9907
 9908    pub fn duplicate(
 9909        &mut self,
 9910        upwards: bool,
 9911        whole_lines: bool,
 9912        window: &mut Window,
 9913        cx: &mut Context<Self>,
 9914    ) {
 9915        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9916
 9917        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9918        let buffer = &display_map.buffer_snapshot;
 9919        let selections = self.selections.all::<Point>(cx);
 9920
 9921        let mut edits = Vec::new();
 9922        let mut selections_iter = selections.iter().peekable();
 9923        while let Some(selection) = selections_iter.next() {
 9924            let mut rows = selection.spanned_rows(false, &display_map);
 9925            // duplicate line-wise
 9926            if whole_lines || selection.start == selection.end {
 9927                // Avoid duplicating the same lines twice.
 9928                while let Some(next_selection) = selections_iter.peek() {
 9929                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9930                    if next_rows.start < rows.end {
 9931                        rows.end = next_rows.end;
 9932                        selections_iter.next().unwrap();
 9933                    } else {
 9934                        break;
 9935                    }
 9936                }
 9937
 9938                // Copy the text from the selected row region and splice it either at the start
 9939                // or end of the region.
 9940                let start = Point::new(rows.start.0, 0);
 9941                let end = Point::new(
 9942                    rows.end.previous_row().0,
 9943                    buffer.line_len(rows.end.previous_row()),
 9944                );
 9945                let text = buffer
 9946                    .text_for_range(start..end)
 9947                    .chain(Some("\n"))
 9948                    .collect::<String>();
 9949                let insert_location = if upwards {
 9950                    Point::new(rows.end.0, 0)
 9951                } else {
 9952                    start
 9953                };
 9954                edits.push((insert_location..insert_location, text));
 9955            } else {
 9956                // duplicate character-wise
 9957                let start = selection.start;
 9958                let end = selection.end;
 9959                let text = buffer.text_for_range(start..end).collect::<String>();
 9960                edits.push((selection.end..selection.end, text));
 9961            }
 9962        }
 9963
 9964        self.transact(window, cx, |this, _, cx| {
 9965            this.buffer.update(cx, |buffer, cx| {
 9966                buffer.edit(edits, None, cx);
 9967            });
 9968
 9969            this.request_autoscroll(Autoscroll::fit(), cx);
 9970        });
 9971    }
 9972
 9973    pub fn duplicate_line_up(
 9974        &mut self,
 9975        _: &DuplicateLineUp,
 9976        window: &mut Window,
 9977        cx: &mut Context<Self>,
 9978    ) {
 9979        self.duplicate(true, true, window, cx);
 9980    }
 9981
 9982    pub fn duplicate_line_down(
 9983        &mut self,
 9984        _: &DuplicateLineDown,
 9985        window: &mut Window,
 9986        cx: &mut Context<Self>,
 9987    ) {
 9988        self.duplicate(false, true, window, cx);
 9989    }
 9990
 9991    pub fn duplicate_selection(
 9992        &mut self,
 9993        _: &DuplicateSelection,
 9994        window: &mut Window,
 9995        cx: &mut Context<Self>,
 9996    ) {
 9997        self.duplicate(false, false, window, cx);
 9998    }
 9999
10000    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10001        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10002
10003        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10004        let buffer = self.buffer.read(cx).snapshot(cx);
10005
10006        let mut edits = Vec::new();
10007        let mut unfold_ranges = Vec::new();
10008        let mut refold_creases = Vec::new();
10009
10010        let selections = self.selections.all::<Point>(cx);
10011        let mut selections = selections.iter().peekable();
10012        let mut contiguous_row_selections = Vec::new();
10013        let mut new_selections = Vec::new();
10014
10015        while let Some(selection) = selections.next() {
10016            // Find all the selections that span a contiguous row range
10017            let (start_row, end_row) = consume_contiguous_rows(
10018                &mut contiguous_row_selections,
10019                selection,
10020                &display_map,
10021                &mut selections,
10022            );
10023
10024            // Move the text spanned by the row range to be before the line preceding the row range
10025            if start_row.0 > 0 {
10026                let range_to_move = Point::new(
10027                    start_row.previous_row().0,
10028                    buffer.line_len(start_row.previous_row()),
10029                )
10030                    ..Point::new(
10031                        end_row.previous_row().0,
10032                        buffer.line_len(end_row.previous_row()),
10033                    );
10034                let insertion_point = display_map
10035                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10036                    .0;
10037
10038                // Don't move lines across excerpts
10039                if buffer
10040                    .excerpt_containing(insertion_point..range_to_move.end)
10041                    .is_some()
10042                {
10043                    let text = buffer
10044                        .text_for_range(range_to_move.clone())
10045                        .flat_map(|s| s.chars())
10046                        .skip(1)
10047                        .chain(['\n'])
10048                        .collect::<String>();
10049
10050                    edits.push((
10051                        buffer.anchor_after(range_to_move.start)
10052                            ..buffer.anchor_before(range_to_move.end),
10053                        String::new(),
10054                    ));
10055                    let insertion_anchor = buffer.anchor_after(insertion_point);
10056                    edits.push((insertion_anchor..insertion_anchor, text));
10057
10058                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10059
10060                    // Move selections up
10061                    new_selections.extend(contiguous_row_selections.drain(..).map(
10062                        |mut selection| {
10063                            selection.start.row -= row_delta;
10064                            selection.end.row -= row_delta;
10065                            selection
10066                        },
10067                    ));
10068
10069                    // Move folds up
10070                    unfold_ranges.push(range_to_move.clone());
10071                    for fold in display_map.folds_in_range(
10072                        buffer.anchor_before(range_to_move.start)
10073                            ..buffer.anchor_after(range_to_move.end),
10074                    ) {
10075                        let mut start = fold.range.start.to_point(&buffer);
10076                        let mut end = fold.range.end.to_point(&buffer);
10077                        start.row -= row_delta;
10078                        end.row -= row_delta;
10079                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10080                    }
10081                }
10082            }
10083
10084            // If we didn't move line(s), preserve the existing selections
10085            new_selections.append(&mut contiguous_row_selections);
10086        }
10087
10088        self.transact(window, cx, |this, window, cx| {
10089            this.unfold_ranges(&unfold_ranges, true, true, cx);
10090            this.buffer.update(cx, |buffer, cx| {
10091                for (range, text) in edits {
10092                    buffer.edit([(range, text)], None, cx);
10093                }
10094            });
10095            this.fold_creases(refold_creases, true, window, cx);
10096            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10097                s.select(new_selections);
10098            })
10099        });
10100    }
10101
10102    pub fn move_line_down(
10103        &mut self,
10104        _: &MoveLineDown,
10105        window: &mut Window,
10106        cx: &mut Context<Self>,
10107    ) {
10108        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10109
10110        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10111        let buffer = self.buffer.read(cx).snapshot(cx);
10112
10113        let mut edits = Vec::new();
10114        let mut unfold_ranges = Vec::new();
10115        let mut refold_creases = Vec::new();
10116
10117        let selections = self.selections.all::<Point>(cx);
10118        let mut selections = selections.iter().peekable();
10119        let mut contiguous_row_selections = Vec::new();
10120        let mut new_selections = Vec::new();
10121
10122        while let Some(selection) = selections.next() {
10123            // Find all the selections that span a contiguous row range
10124            let (start_row, end_row) = consume_contiguous_rows(
10125                &mut contiguous_row_selections,
10126                selection,
10127                &display_map,
10128                &mut selections,
10129            );
10130
10131            // Move the text spanned by the row range to be after the last line of the row range
10132            if end_row.0 <= buffer.max_point().row {
10133                let range_to_move =
10134                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10135                let insertion_point = display_map
10136                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10137                    .0;
10138
10139                // Don't move lines across excerpt boundaries
10140                if buffer
10141                    .excerpt_containing(range_to_move.start..insertion_point)
10142                    .is_some()
10143                {
10144                    let mut text = String::from("\n");
10145                    text.extend(buffer.text_for_range(range_to_move.clone()));
10146                    text.pop(); // Drop trailing newline
10147                    edits.push((
10148                        buffer.anchor_after(range_to_move.start)
10149                            ..buffer.anchor_before(range_to_move.end),
10150                        String::new(),
10151                    ));
10152                    let insertion_anchor = buffer.anchor_after(insertion_point);
10153                    edits.push((insertion_anchor..insertion_anchor, text));
10154
10155                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10156
10157                    // Move selections down
10158                    new_selections.extend(contiguous_row_selections.drain(..).map(
10159                        |mut selection| {
10160                            selection.start.row += row_delta;
10161                            selection.end.row += row_delta;
10162                            selection
10163                        },
10164                    ));
10165
10166                    // Move folds down
10167                    unfold_ranges.push(range_to_move.clone());
10168                    for fold in display_map.folds_in_range(
10169                        buffer.anchor_before(range_to_move.start)
10170                            ..buffer.anchor_after(range_to_move.end),
10171                    ) {
10172                        let mut start = fold.range.start.to_point(&buffer);
10173                        let mut end = fold.range.end.to_point(&buffer);
10174                        start.row += row_delta;
10175                        end.row += row_delta;
10176                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10177                    }
10178                }
10179            }
10180
10181            // If we didn't move line(s), preserve the existing selections
10182            new_selections.append(&mut contiguous_row_selections);
10183        }
10184
10185        self.transact(window, cx, |this, window, cx| {
10186            this.unfold_ranges(&unfold_ranges, true, true, cx);
10187            this.buffer.update(cx, |buffer, cx| {
10188                for (range, text) in edits {
10189                    buffer.edit([(range, text)], None, cx);
10190                }
10191            });
10192            this.fold_creases(refold_creases, true, window, cx);
10193            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10194                s.select(new_selections)
10195            });
10196        });
10197    }
10198
10199    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10200        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10201        let text_layout_details = &self.text_layout_details(window);
10202        self.transact(window, cx, |this, window, cx| {
10203            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10204                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10205                s.move_with(|display_map, selection| {
10206                    if !selection.is_empty() {
10207                        return;
10208                    }
10209
10210                    let mut head = selection.head();
10211                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10212                    if head.column() == display_map.line_len(head.row()) {
10213                        transpose_offset = display_map
10214                            .buffer_snapshot
10215                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10216                    }
10217
10218                    if transpose_offset == 0 {
10219                        return;
10220                    }
10221
10222                    *head.column_mut() += 1;
10223                    head = display_map.clip_point(head, Bias::Right);
10224                    let goal = SelectionGoal::HorizontalPosition(
10225                        display_map
10226                            .x_for_display_point(head, text_layout_details)
10227                            .into(),
10228                    );
10229                    selection.collapse_to(head, goal);
10230
10231                    let transpose_start = display_map
10232                        .buffer_snapshot
10233                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10234                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10235                        let transpose_end = display_map
10236                            .buffer_snapshot
10237                            .clip_offset(transpose_offset + 1, Bias::Right);
10238                        if let Some(ch) =
10239                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10240                        {
10241                            edits.push((transpose_start..transpose_offset, String::new()));
10242                            edits.push((transpose_end..transpose_end, ch.to_string()));
10243                        }
10244                    }
10245                });
10246                edits
10247            });
10248            this.buffer
10249                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10250            let selections = this.selections.all::<usize>(cx);
10251            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252                s.select(selections);
10253            });
10254        });
10255    }
10256
10257    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10258        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10259        self.rewrap_impl(RewrapOptions::default(), cx)
10260    }
10261
10262    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10263        let buffer = self.buffer.read(cx).snapshot(cx);
10264        let selections = self.selections.all::<Point>(cx);
10265        let mut selections = selections.iter().peekable();
10266
10267        let mut edits = Vec::new();
10268        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10269
10270        while let Some(selection) = selections.next() {
10271            let mut start_row = selection.start.row;
10272            let mut end_row = selection.end.row;
10273
10274            // Skip selections that overlap with a range that has already been rewrapped.
10275            let selection_range = start_row..end_row;
10276            if rewrapped_row_ranges
10277                .iter()
10278                .any(|range| range.overlaps(&selection_range))
10279            {
10280                continue;
10281            }
10282
10283            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10284
10285            // Since not all lines in the selection may be at the same indent
10286            // level, choose the indent size that is the most common between all
10287            // of the lines.
10288            //
10289            // If there is a tie, we use the deepest indent.
10290            let (indent_size, indent_end) = {
10291                let mut indent_size_occurrences = HashMap::default();
10292                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10293
10294                for row in start_row..=end_row {
10295                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10296                    rows_by_indent_size.entry(indent).or_default().push(row);
10297                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10298                }
10299
10300                let indent_size = indent_size_occurrences
10301                    .into_iter()
10302                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10303                    .map(|(indent, _)| indent)
10304                    .unwrap_or_default();
10305                let row = rows_by_indent_size[&indent_size][0];
10306                let indent_end = Point::new(row, indent_size.len);
10307
10308                (indent_size, indent_end)
10309            };
10310
10311            let mut line_prefix = indent_size.chars().collect::<String>();
10312
10313            let mut inside_comment = false;
10314            if let Some(comment_prefix) =
10315                buffer
10316                    .language_scope_at(selection.head())
10317                    .and_then(|language| {
10318                        language
10319                            .line_comment_prefixes()
10320                            .iter()
10321                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10322                            .cloned()
10323                    })
10324            {
10325                line_prefix.push_str(&comment_prefix);
10326                inside_comment = true;
10327            }
10328
10329            let language_settings = buffer.language_settings_at(selection.head(), cx);
10330            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10331                RewrapBehavior::InComments => inside_comment,
10332                RewrapBehavior::InSelections => !selection.is_empty(),
10333                RewrapBehavior::Anywhere => true,
10334            };
10335
10336            let should_rewrap = options.override_language_settings
10337                || allow_rewrap_based_on_language
10338                || self.hard_wrap.is_some();
10339            if !should_rewrap {
10340                continue;
10341            }
10342
10343            if selection.is_empty() {
10344                'expand_upwards: while start_row > 0 {
10345                    let prev_row = start_row - 1;
10346                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10347                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10348                    {
10349                        start_row = prev_row;
10350                    } else {
10351                        break 'expand_upwards;
10352                    }
10353                }
10354
10355                'expand_downwards: while end_row < buffer.max_point().row {
10356                    let next_row = end_row + 1;
10357                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10358                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10359                    {
10360                        end_row = next_row;
10361                    } else {
10362                        break 'expand_downwards;
10363                    }
10364                }
10365            }
10366
10367            let start = Point::new(start_row, 0);
10368            let start_offset = start.to_offset(&buffer);
10369            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10370            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10371            let Some(lines_without_prefixes) = selection_text
10372                .lines()
10373                .map(|line| {
10374                    line.strip_prefix(&line_prefix)
10375                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10376                        .ok_or_else(|| {
10377                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10378                        })
10379                })
10380                .collect::<Result<Vec<_>, _>>()
10381                .log_err()
10382            else {
10383                continue;
10384            };
10385
10386            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10387                buffer
10388                    .language_settings_at(Point::new(start_row, 0), cx)
10389                    .preferred_line_length as usize
10390            });
10391            let wrapped_text = wrap_with_prefix(
10392                line_prefix,
10393                lines_without_prefixes.join("\n"),
10394                wrap_column,
10395                tab_size,
10396                options.preserve_existing_whitespace,
10397            );
10398
10399            // TODO: should always use char-based diff while still supporting cursor behavior that
10400            // matches vim.
10401            let mut diff_options = DiffOptions::default();
10402            if options.override_language_settings {
10403                diff_options.max_word_diff_len = 0;
10404                diff_options.max_word_diff_line_count = 0;
10405            } else {
10406                diff_options.max_word_diff_len = usize::MAX;
10407                diff_options.max_word_diff_line_count = usize::MAX;
10408            }
10409
10410            for (old_range, new_text) in
10411                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10412            {
10413                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10414                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10415                edits.push((edit_start..edit_end, new_text));
10416            }
10417
10418            rewrapped_row_ranges.push(start_row..=end_row);
10419        }
10420
10421        self.buffer
10422            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10423    }
10424
10425    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10426        let mut text = String::new();
10427        let buffer = self.buffer.read(cx).snapshot(cx);
10428        let mut selections = self.selections.all::<Point>(cx);
10429        let mut clipboard_selections = Vec::with_capacity(selections.len());
10430        {
10431            let max_point = buffer.max_point();
10432            let mut is_first = true;
10433            for selection in &mut selections {
10434                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10435                if is_entire_line {
10436                    selection.start = Point::new(selection.start.row, 0);
10437                    if !selection.is_empty() && selection.end.column == 0 {
10438                        selection.end = cmp::min(max_point, selection.end);
10439                    } else {
10440                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10441                    }
10442                    selection.goal = SelectionGoal::None;
10443                }
10444                if is_first {
10445                    is_first = false;
10446                } else {
10447                    text += "\n";
10448                }
10449                let mut len = 0;
10450                for chunk in buffer.text_for_range(selection.start..selection.end) {
10451                    text.push_str(chunk);
10452                    len += chunk.len();
10453                }
10454                clipboard_selections.push(ClipboardSelection {
10455                    len,
10456                    is_entire_line,
10457                    first_line_indent: buffer
10458                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10459                        .len,
10460                });
10461            }
10462        }
10463
10464        self.transact(window, cx, |this, window, cx| {
10465            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10466                s.select(selections);
10467            });
10468            this.insert("", window, cx);
10469        });
10470        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10471    }
10472
10473    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10474        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10475        let item = self.cut_common(window, cx);
10476        cx.write_to_clipboard(item);
10477    }
10478
10479    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10480        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10481        self.change_selections(None, window, cx, |s| {
10482            s.move_with(|snapshot, sel| {
10483                if sel.is_empty() {
10484                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10485                }
10486            });
10487        });
10488        let item = self.cut_common(window, cx);
10489        cx.set_global(KillRing(item))
10490    }
10491
10492    pub fn kill_ring_yank(
10493        &mut self,
10494        _: &KillRingYank,
10495        window: &mut Window,
10496        cx: &mut Context<Self>,
10497    ) {
10498        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10499        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10500            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10501                (kill_ring.text().to_string(), kill_ring.metadata_json())
10502            } else {
10503                return;
10504            }
10505        } else {
10506            return;
10507        };
10508        self.do_paste(&text, metadata, false, window, cx);
10509    }
10510
10511    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10512        self.do_copy(true, cx);
10513    }
10514
10515    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10516        self.do_copy(false, cx);
10517    }
10518
10519    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10520        let selections = self.selections.all::<Point>(cx);
10521        let buffer = self.buffer.read(cx).read(cx);
10522        let mut text = String::new();
10523
10524        let mut clipboard_selections = Vec::with_capacity(selections.len());
10525        {
10526            let max_point = buffer.max_point();
10527            let mut is_first = true;
10528            for selection in &selections {
10529                let mut start = selection.start;
10530                let mut end = selection.end;
10531                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10532                if is_entire_line {
10533                    start = Point::new(start.row, 0);
10534                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10535                }
10536
10537                let mut trimmed_selections = Vec::new();
10538                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10539                    let row = MultiBufferRow(start.row);
10540                    let first_indent = buffer.indent_size_for_line(row);
10541                    if first_indent.len == 0 || start.column > first_indent.len {
10542                        trimmed_selections.push(start..end);
10543                    } else {
10544                        trimmed_selections.push(
10545                            Point::new(row.0, first_indent.len)
10546                                ..Point::new(row.0, buffer.line_len(row)),
10547                        );
10548                        for row in start.row + 1..=end.row {
10549                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10550                            if row == end.row {
10551                                line_len = end.column;
10552                            }
10553                            if line_len == 0 {
10554                                trimmed_selections
10555                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10556                                continue;
10557                            }
10558                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10559                            if row_indent_size.len >= first_indent.len {
10560                                trimmed_selections.push(
10561                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10562                                );
10563                            } else {
10564                                trimmed_selections.clear();
10565                                trimmed_selections.push(start..end);
10566                                break;
10567                            }
10568                        }
10569                    }
10570                } else {
10571                    trimmed_selections.push(start..end);
10572                }
10573
10574                for trimmed_range in trimmed_selections {
10575                    if is_first {
10576                        is_first = false;
10577                    } else {
10578                        text += "\n";
10579                    }
10580                    let mut len = 0;
10581                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10582                        text.push_str(chunk);
10583                        len += chunk.len();
10584                    }
10585                    clipboard_selections.push(ClipboardSelection {
10586                        len,
10587                        is_entire_line,
10588                        first_line_indent: buffer
10589                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10590                            .len,
10591                    });
10592                }
10593            }
10594        }
10595
10596        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10597            text,
10598            clipboard_selections,
10599        ));
10600    }
10601
10602    pub fn do_paste(
10603        &mut self,
10604        text: &String,
10605        clipboard_selections: Option<Vec<ClipboardSelection>>,
10606        handle_entire_lines: bool,
10607        window: &mut Window,
10608        cx: &mut Context<Self>,
10609    ) {
10610        if self.read_only(cx) {
10611            return;
10612        }
10613
10614        let clipboard_text = Cow::Borrowed(text);
10615
10616        self.transact(window, cx, |this, window, cx| {
10617            if let Some(mut clipboard_selections) = clipboard_selections {
10618                let old_selections = this.selections.all::<usize>(cx);
10619                let all_selections_were_entire_line =
10620                    clipboard_selections.iter().all(|s| s.is_entire_line);
10621                let first_selection_indent_column =
10622                    clipboard_selections.first().map(|s| s.first_line_indent);
10623                if clipboard_selections.len() != old_selections.len() {
10624                    clipboard_selections.drain(..);
10625                }
10626                let cursor_offset = this.selections.last::<usize>(cx).head();
10627                let mut auto_indent_on_paste = true;
10628
10629                this.buffer.update(cx, |buffer, cx| {
10630                    let snapshot = buffer.read(cx);
10631                    auto_indent_on_paste = snapshot
10632                        .language_settings_at(cursor_offset, cx)
10633                        .auto_indent_on_paste;
10634
10635                    let mut start_offset = 0;
10636                    let mut edits = Vec::new();
10637                    let mut original_indent_columns = Vec::new();
10638                    for (ix, selection) in old_selections.iter().enumerate() {
10639                        let to_insert;
10640                        let entire_line;
10641                        let original_indent_column;
10642                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10643                            let end_offset = start_offset + clipboard_selection.len;
10644                            to_insert = &clipboard_text[start_offset..end_offset];
10645                            entire_line = clipboard_selection.is_entire_line;
10646                            start_offset = end_offset + 1;
10647                            original_indent_column = Some(clipboard_selection.first_line_indent);
10648                        } else {
10649                            to_insert = clipboard_text.as_str();
10650                            entire_line = all_selections_were_entire_line;
10651                            original_indent_column = first_selection_indent_column
10652                        }
10653
10654                        // If the corresponding selection was empty when this slice of the
10655                        // clipboard text was written, then the entire line containing the
10656                        // selection was copied. If this selection is also currently empty,
10657                        // then paste the line before the current line of the buffer.
10658                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10659                            let column = selection.start.to_point(&snapshot).column as usize;
10660                            let line_start = selection.start - column;
10661                            line_start..line_start
10662                        } else {
10663                            selection.range()
10664                        };
10665
10666                        edits.push((range, to_insert));
10667                        original_indent_columns.push(original_indent_column);
10668                    }
10669                    drop(snapshot);
10670
10671                    buffer.edit(
10672                        edits,
10673                        if auto_indent_on_paste {
10674                            Some(AutoindentMode::Block {
10675                                original_indent_columns,
10676                            })
10677                        } else {
10678                            None
10679                        },
10680                        cx,
10681                    );
10682                });
10683
10684                let selections = this.selections.all::<usize>(cx);
10685                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686                    s.select(selections)
10687                });
10688            } else {
10689                this.insert(&clipboard_text, window, cx);
10690            }
10691        });
10692    }
10693
10694    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10695        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10696        if let Some(item) = cx.read_from_clipboard() {
10697            let entries = item.entries();
10698
10699            match entries.first() {
10700                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10701                // of all the pasted entries.
10702                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10703                    .do_paste(
10704                        clipboard_string.text(),
10705                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10706                        true,
10707                        window,
10708                        cx,
10709                    ),
10710                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10711            }
10712        }
10713    }
10714
10715    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10716        if self.read_only(cx) {
10717            return;
10718        }
10719
10720        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10721
10722        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10723            if let Some((selections, _)) =
10724                self.selection_history.transaction(transaction_id).cloned()
10725            {
10726                self.change_selections(None, window, cx, |s| {
10727                    s.select_anchors(selections.to_vec());
10728                });
10729            } else {
10730                log::error!(
10731                    "No entry in selection_history found for undo. \
10732                     This may correspond to a bug where undo does not update the selection. \
10733                     If this is occurring, please add details to \
10734                     https://github.com/zed-industries/zed/issues/22692"
10735                );
10736            }
10737            self.request_autoscroll(Autoscroll::fit(), cx);
10738            self.unmark_text(window, cx);
10739            self.refresh_inline_completion(true, false, window, cx);
10740            cx.emit(EditorEvent::Edited { transaction_id });
10741            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10742        }
10743    }
10744
10745    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10746        if self.read_only(cx) {
10747            return;
10748        }
10749
10750        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10751
10752        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10753            if let Some((_, Some(selections))) =
10754                self.selection_history.transaction(transaction_id).cloned()
10755            {
10756                self.change_selections(None, window, cx, |s| {
10757                    s.select_anchors(selections.to_vec());
10758                });
10759            } else {
10760                log::error!(
10761                    "No entry in selection_history found for redo. \
10762                     This may correspond to a bug where undo does not update the selection. \
10763                     If this is occurring, please add details to \
10764                     https://github.com/zed-industries/zed/issues/22692"
10765                );
10766            }
10767            self.request_autoscroll(Autoscroll::fit(), cx);
10768            self.unmark_text(window, cx);
10769            self.refresh_inline_completion(true, false, window, cx);
10770            cx.emit(EditorEvent::Edited { transaction_id });
10771        }
10772    }
10773
10774    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10775        self.buffer
10776            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10777    }
10778
10779    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10780        self.buffer
10781            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10782    }
10783
10784    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10785        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10786        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10787            s.move_with(|map, selection| {
10788                let cursor = if selection.is_empty() {
10789                    movement::left(map, selection.start)
10790                } else {
10791                    selection.start
10792                };
10793                selection.collapse_to(cursor, SelectionGoal::None);
10794            });
10795        })
10796    }
10797
10798    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10799        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10800        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10801            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10802        })
10803    }
10804
10805    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10806        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10807        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10808            s.move_with(|map, selection| {
10809                let cursor = if selection.is_empty() {
10810                    movement::right(map, selection.end)
10811                } else {
10812                    selection.end
10813                };
10814                selection.collapse_to(cursor, SelectionGoal::None)
10815            });
10816        })
10817    }
10818
10819    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10820        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10822            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10823        })
10824    }
10825
10826    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10827        if self.take_rename(true, window, cx).is_some() {
10828            return;
10829        }
10830
10831        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10832            cx.propagate();
10833            return;
10834        }
10835
10836        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10837
10838        let text_layout_details = &self.text_layout_details(window);
10839        let selection_count = self.selections.count();
10840        let first_selection = self.selections.first_anchor();
10841
10842        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10843            s.move_with(|map, selection| {
10844                if !selection.is_empty() {
10845                    selection.goal = SelectionGoal::None;
10846                }
10847                let (cursor, goal) = movement::up(
10848                    map,
10849                    selection.start,
10850                    selection.goal,
10851                    false,
10852                    text_layout_details,
10853                );
10854                selection.collapse_to(cursor, goal);
10855            });
10856        });
10857
10858        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10859        {
10860            cx.propagate();
10861        }
10862    }
10863
10864    pub fn move_up_by_lines(
10865        &mut self,
10866        action: &MoveUpByLines,
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::up_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 move_down_by_lines(
10902        &mut self,
10903        action: &MoveDownByLines,
10904        window: &mut Window,
10905        cx: &mut Context<Self>,
10906    ) {
10907        if self.take_rename(true, window, cx).is_some() {
10908            return;
10909        }
10910
10911        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10912            cx.propagate();
10913            return;
10914        }
10915
10916        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10917
10918        let text_layout_details = &self.text_layout_details(window);
10919
10920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10921            s.move_with(|map, selection| {
10922                if !selection.is_empty() {
10923                    selection.goal = SelectionGoal::None;
10924                }
10925                let (cursor, goal) = movement::down_by_rows(
10926                    map,
10927                    selection.start,
10928                    action.lines,
10929                    selection.goal,
10930                    false,
10931                    text_layout_details,
10932                );
10933                selection.collapse_to(cursor, goal);
10934            });
10935        })
10936    }
10937
10938    pub fn select_down_by_lines(
10939        &mut self,
10940        action: &SelectDownByLines,
10941        window: &mut Window,
10942        cx: &mut Context<Self>,
10943    ) {
10944        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10945        let text_layout_details = &self.text_layout_details(window);
10946        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947            s.move_heads_with(|map, head, goal| {
10948                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10949            })
10950        })
10951    }
10952
10953    pub fn select_up_by_lines(
10954        &mut self,
10955        action: &SelectUpByLines,
10956        window: &mut Window,
10957        cx: &mut Context<Self>,
10958    ) {
10959        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10960        let text_layout_details = &self.text_layout_details(window);
10961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10962            s.move_heads_with(|map, head, goal| {
10963                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10964            })
10965        })
10966    }
10967
10968    pub fn select_page_up(
10969        &mut self,
10970        _: &SelectPageUp,
10971        window: &mut Window,
10972        cx: &mut Context<Self>,
10973    ) {
10974        let Some(row_count) = self.visible_row_count() else {
10975            return;
10976        };
10977
10978        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10979
10980        let text_layout_details = &self.text_layout_details(window);
10981
10982        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10983            s.move_heads_with(|map, head, goal| {
10984                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10985            })
10986        })
10987    }
10988
10989    pub fn move_page_up(
10990        &mut self,
10991        action: &MovePageUp,
10992        window: &mut Window,
10993        cx: &mut Context<Self>,
10994    ) {
10995        if self.take_rename(true, window, cx).is_some() {
10996            return;
10997        }
10998
10999        if self
11000            .context_menu
11001            .borrow_mut()
11002            .as_mut()
11003            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11004            .unwrap_or(false)
11005        {
11006            return;
11007        }
11008
11009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11010            cx.propagate();
11011            return;
11012        }
11013
11014        let Some(row_count) = self.visible_row_count() else {
11015            return;
11016        };
11017
11018        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11019
11020        let autoscroll = if action.center_cursor {
11021            Autoscroll::center()
11022        } else {
11023            Autoscroll::fit()
11024        };
11025
11026        let text_layout_details = &self.text_layout_details(window);
11027
11028        self.change_selections(Some(autoscroll), window, cx, |s| {
11029            s.move_with(|map, selection| {
11030                if !selection.is_empty() {
11031                    selection.goal = SelectionGoal::None;
11032                }
11033                let (cursor, goal) = movement::up_by_rows(
11034                    map,
11035                    selection.end,
11036                    row_count,
11037                    selection.goal,
11038                    false,
11039                    text_layout_details,
11040                );
11041                selection.collapse_to(cursor, goal);
11042            });
11043        });
11044    }
11045
11046    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11047        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11048        let text_layout_details = &self.text_layout_details(window);
11049        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11050            s.move_heads_with(|map, head, goal| {
11051                movement::up(map, head, goal, false, text_layout_details)
11052            })
11053        })
11054    }
11055
11056    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11057        self.take_rename(true, window, cx);
11058
11059        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11060            cx.propagate();
11061            return;
11062        }
11063
11064        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11065
11066        let text_layout_details = &self.text_layout_details(window);
11067        let selection_count = self.selections.count();
11068        let first_selection = self.selections.first_anchor();
11069
11070        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11071            s.move_with(|map, selection| {
11072                if !selection.is_empty() {
11073                    selection.goal = SelectionGoal::None;
11074                }
11075                let (cursor, goal) = movement::down(
11076                    map,
11077                    selection.end,
11078                    selection.goal,
11079                    false,
11080                    text_layout_details,
11081                );
11082                selection.collapse_to(cursor, goal);
11083            });
11084        });
11085
11086        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11087        {
11088            cx.propagate();
11089        }
11090    }
11091
11092    pub fn select_page_down(
11093        &mut self,
11094        _: &SelectPageDown,
11095        window: &mut Window,
11096        cx: &mut Context<Self>,
11097    ) {
11098        let Some(row_count) = self.visible_row_count() else {
11099            return;
11100        };
11101
11102        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11103
11104        let text_layout_details = &self.text_layout_details(window);
11105
11106        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11107            s.move_heads_with(|map, head, goal| {
11108                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11109            })
11110        })
11111    }
11112
11113    pub fn move_page_down(
11114        &mut self,
11115        action: &MovePageDown,
11116        window: &mut Window,
11117        cx: &mut Context<Self>,
11118    ) {
11119        if self.take_rename(true, window, cx).is_some() {
11120            return;
11121        }
11122
11123        if self
11124            .context_menu
11125            .borrow_mut()
11126            .as_mut()
11127            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11128            .unwrap_or(false)
11129        {
11130            return;
11131        }
11132
11133        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11134            cx.propagate();
11135            return;
11136        }
11137
11138        let Some(row_count) = self.visible_row_count() else {
11139            return;
11140        };
11141
11142        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11143
11144        let autoscroll = if action.center_cursor {
11145            Autoscroll::center()
11146        } else {
11147            Autoscroll::fit()
11148        };
11149
11150        let text_layout_details = &self.text_layout_details(window);
11151        self.change_selections(Some(autoscroll), window, cx, |s| {
11152            s.move_with(|map, selection| {
11153                if !selection.is_empty() {
11154                    selection.goal = SelectionGoal::None;
11155                }
11156                let (cursor, goal) = movement::down_by_rows(
11157                    map,
11158                    selection.end,
11159                    row_count,
11160                    selection.goal,
11161                    false,
11162                    text_layout_details,
11163                );
11164                selection.collapse_to(cursor, goal);
11165            });
11166        });
11167    }
11168
11169    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11170        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11171        let text_layout_details = &self.text_layout_details(window);
11172        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11173            s.move_heads_with(|map, head, goal| {
11174                movement::down(map, head, goal, false, text_layout_details)
11175            })
11176        });
11177    }
11178
11179    pub fn context_menu_first(
11180        &mut self,
11181        _: &ContextMenuFirst,
11182        _window: &mut Window,
11183        cx: &mut Context<Self>,
11184    ) {
11185        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11186            context_menu.select_first(self.completion_provider.as_deref(), cx);
11187        }
11188    }
11189
11190    pub fn context_menu_prev(
11191        &mut self,
11192        _: &ContextMenuPrevious,
11193        _window: &mut Window,
11194        cx: &mut Context<Self>,
11195    ) {
11196        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11197            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11198        }
11199    }
11200
11201    pub fn context_menu_next(
11202        &mut self,
11203        _: &ContextMenuNext,
11204        _window: &mut Window,
11205        cx: &mut Context<Self>,
11206    ) {
11207        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11208            context_menu.select_next(self.completion_provider.as_deref(), cx);
11209        }
11210    }
11211
11212    pub fn context_menu_last(
11213        &mut self,
11214        _: &ContextMenuLast,
11215        _window: &mut Window,
11216        cx: &mut Context<Self>,
11217    ) {
11218        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11219            context_menu.select_last(self.completion_provider.as_deref(), cx);
11220        }
11221    }
11222
11223    pub fn move_to_previous_word_start(
11224        &mut self,
11225        _: &MoveToPreviousWordStart,
11226        window: &mut Window,
11227        cx: &mut Context<Self>,
11228    ) {
11229        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11230        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11231            s.move_cursors_with(|map, head, _| {
11232                (
11233                    movement::previous_word_start(map, head),
11234                    SelectionGoal::None,
11235                )
11236            });
11237        })
11238    }
11239
11240    pub fn move_to_previous_subword_start(
11241        &mut self,
11242        _: &MoveToPreviousSubwordStart,
11243        window: &mut Window,
11244        cx: &mut Context<Self>,
11245    ) {
11246        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11247        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11248            s.move_cursors_with(|map, head, _| {
11249                (
11250                    movement::previous_subword_start(map, head),
11251                    SelectionGoal::None,
11252                )
11253            });
11254        })
11255    }
11256
11257    pub fn select_to_previous_word_start(
11258        &mut self,
11259        _: &SelectToPreviousWordStart,
11260        window: &mut Window,
11261        cx: &mut Context<Self>,
11262    ) {
11263        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11264        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11265            s.move_heads_with(|map, head, _| {
11266                (
11267                    movement::previous_word_start(map, head),
11268                    SelectionGoal::None,
11269                )
11270            });
11271        })
11272    }
11273
11274    pub fn select_to_previous_subword_start(
11275        &mut self,
11276        _: &SelectToPreviousSubwordStart,
11277        window: &mut Window,
11278        cx: &mut Context<Self>,
11279    ) {
11280        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11281        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11282            s.move_heads_with(|map, head, _| {
11283                (
11284                    movement::previous_subword_start(map, head),
11285                    SelectionGoal::None,
11286                )
11287            });
11288        })
11289    }
11290
11291    pub fn delete_to_previous_word_start(
11292        &mut self,
11293        action: &DeleteToPreviousWordStart,
11294        window: &mut Window,
11295        cx: &mut Context<Self>,
11296    ) {
11297        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11298        self.transact(window, cx, |this, window, cx| {
11299            this.select_autoclose_pair(window, cx);
11300            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11301                s.move_with(|map, selection| {
11302                    if selection.is_empty() {
11303                        let cursor = if action.ignore_newlines {
11304                            movement::previous_word_start(map, selection.head())
11305                        } else {
11306                            movement::previous_word_start_or_newline(map, selection.head())
11307                        };
11308                        selection.set_head(cursor, SelectionGoal::None);
11309                    }
11310                });
11311            });
11312            this.insert("", window, cx);
11313        });
11314    }
11315
11316    pub fn delete_to_previous_subword_start(
11317        &mut self,
11318        _: &DeleteToPreviousSubwordStart,
11319        window: &mut Window,
11320        cx: &mut Context<Self>,
11321    ) {
11322        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11323        self.transact(window, cx, |this, window, cx| {
11324            this.select_autoclose_pair(window, cx);
11325            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326                s.move_with(|map, selection| {
11327                    if selection.is_empty() {
11328                        let cursor = movement::previous_subword_start(map, selection.head());
11329                        selection.set_head(cursor, SelectionGoal::None);
11330                    }
11331                });
11332            });
11333            this.insert("", window, cx);
11334        });
11335    }
11336
11337    pub fn move_to_next_word_end(
11338        &mut self,
11339        _: &MoveToNextWordEnd,
11340        window: &mut Window,
11341        cx: &mut Context<Self>,
11342    ) {
11343        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11344        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11345            s.move_cursors_with(|map, head, _| {
11346                (movement::next_word_end(map, head), SelectionGoal::None)
11347            });
11348        })
11349    }
11350
11351    pub fn move_to_next_subword_end(
11352        &mut self,
11353        _: &MoveToNextSubwordEnd,
11354        window: &mut Window,
11355        cx: &mut Context<Self>,
11356    ) {
11357        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11358        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11359            s.move_cursors_with(|map, head, _| {
11360                (movement::next_subword_end(map, head), SelectionGoal::None)
11361            });
11362        })
11363    }
11364
11365    pub fn select_to_next_word_end(
11366        &mut self,
11367        _: &SelectToNextWordEnd,
11368        window: &mut Window,
11369        cx: &mut Context<Self>,
11370    ) {
11371        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11372        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11373            s.move_heads_with(|map, head, _| {
11374                (movement::next_word_end(map, head), SelectionGoal::None)
11375            });
11376        })
11377    }
11378
11379    pub fn select_to_next_subword_end(
11380        &mut self,
11381        _: &SelectToNextSubwordEnd,
11382        window: &mut Window,
11383        cx: &mut Context<Self>,
11384    ) {
11385        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11386        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11387            s.move_heads_with(|map, head, _| {
11388                (movement::next_subword_end(map, head), SelectionGoal::None)
11389            });
11390        })
11391    }
11392
11393    pub fn delete_to_next_word_end(
11394        &mut self,
11395        action: &DeleteToNextWordEnd,
11396        window: &mut Window,
11397        cx: &mut Context<Self>,
11398    ) {
11399        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11400        self.transact(window, cx, |this, window, cx| {
11401            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11402                s.move_with(|map, selection| {
11403                    if selection.is_empty() {
11404                        let cursor = if action.ignore_newlines {
11405                            movement::next_word_end(map, selection.head())
11406                        } else {
11407                            movement::next_word_end_or_newline(map, selection.head())
11408                        };
11409                        selection.set_head(cursor, SelectionGoal::None);
11410                    }
11411                });
11412            });
11413            this.insert("", window, cx);
11414        });
11415    }
11416
11417    pub fn delete_to_next_subword_end(
11418        &mut self,
11419        _: &DeleteToNextSubwordEnd,
11420        window: &mut Window,
11421        cx: &mut Context<Self>,
11422    ) {
11423        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11424        self.transact(window, cx, |this, window, cx| {
11425            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11426                s.move_with(|map, selection| {
11427                    if selection.is_empty() {
11428                        let cursor = movement::next_subword_end(map, selection.head());
11429                        selection.set_head(cursor, SelectionGoal::None);
11430                    }
11431                });
11432            });
11433            this.insert("", window, cx);
11434        });
11435    }
11436
11437    pub fn move_to_beginning_of_line(
11438        &mut self,
11439        action: &MoveToBeginningOfLine,
11440        window: &mut Window,
11441        cx: &mut Context<Self>,
11442    ) {
11443        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11444        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11445            s.move_cursors_with(|map, head, _| {
11446                (
11447                    movement::indented_line_beginning(
11448                        map,
11449                        head,
11450                        action.stop_at_soft_wraps,
11451                        action.stop_at_indent,
11452                    ),
11453                    SelectionGoal::None,
11454                )
11455            });
11456        })
11457    }
11458
11459    pub fn select_to_beginning_of_line(
11460        &mut self,
11461        action: &SelectToBeginningOfLine,
11462        window: &mut Window,
11463        cx: &mut Context<Self>,
11464    ) {
11465        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11466        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11467            s.move_heads_with(|map, head, _| {
11468                (
11469                    movement::indented_line_beginning(
11470                        map,
11471                        head,
11472                        action.stop_at_soft_wraps,
11473                        action.stop_at_indent,
11474                    ),
11475                    SelectionGoal::None,
11476                )
11477            });
11478        });
11479    }
11480
11481    pub fn delete_to_beginning_of_line(
11482        &mut self,
11483        action: &DeleteToBeginningOfLine,
11484        window: &mut Window,
11485        cx: &mut Context<Self>,
11486    ) {
11487        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11488        self.transact(window, cx, |this, window, cx| {
11489            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11490                s.move_with(|_, selection| {
11491                    selection.reversed = true;
11492                });
11493            });
11494
11495            this.select_to_beginning_of_line(
11496                &SelectToBeginningOfLine {
11497                    stop_at_soft_wraps: false,
11498                    stop_at_indent: action.stop_at_indent,
11499                },
11500                window,
11501                cx,
11502            );
11503            this.backspace(&Backspace, window, cx);
11504        });
11505    }
11506
11507    pub fn move_to_end_of_line(
11508        &mut self,
11509        action: &MoveToEndOfLine,
11510        window: &mut Window,
11511        cx: &mut Context<Self>,
11512    ) {
11513        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11514        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11515            s.move_cursors_with(|map, head, _| {
11516                (
11517                    movement::line_end(map, head, action.stop_at_soft_wraps),
11518                    SelectionGoal::None,
11519                )
11520            });
11521        })
11522    }
11523
11524    pub fn select_to_end_of_line(
11525        &mut self,
11526        action: &SelectToEndOfLine,
11527        window: &mut Window,
11528        cx: &mut Context<Self>,
11529    ) {
11530        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11531        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11532            s.move_heads_with(|map, head, _| {
11533                (
11534                    movement::line_end(map, head, action.stop_at_soft_wraps),
11535                    SelectionGoal::None,
11536                )
11537            });
11538        })
11539    }
11540
11541    pub fn delete_to_end_of_line(
11542        &mut self,
11543        _: &DeleteToEndOfLine,
11544        window: &mut Window,
11545        cx: &mut Context<Self>,
11546    ) {
11547        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11548        self.transact(window, cx, |this, window, cx| {
11549            this.select_to_end_of_line(
11550                &SelectToEndOfLine {
11551                    stop_at_soft_wraps: false,
11552                },
11553                window,
11554                cx,
11555            );
11556            this.delete(&Delete, window, cx);
11557        });
11558    }
11559
11560    pub fn cut_to_end_of_line(
11561        &mut self,
11562        _: &CutToEndOfLine,
11563        window: &mut Window,
11564        cx: &mut Context<Self>,
11565    ) {
11566        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11567        self.transact(window, cx, |this, window, cx| {
11568            this.select_to_end_of_line(
11569                &SelectToEndOfLine {
11570                    stop_at_soft_wraps: false,
11571                },
11572                window,
11573                cx,
11574            );
11575            this.cut(&Cut, window, cx);
11576        });
11577    }
11578
11579    pub fn move_to_start_of_paragraph(
11580        &mut self,
11581        _: &MoveToStartOfParagraph,
11582        window: &mut Window,
11583        cx: &mut Context<Self>,
11584    ) {
11585        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11586            cx.propagate();
11587            return;
11588        }
11589        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11590        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11591            s.move_with(|map, selection| {
11592                selection.collapse_to(
11593                    movement::start_of_paragraph(map, selection.head(), 1),
11594                    SelectionGoal::None,
11595                )
11596            });
11597        })
11598    }
11599
11600    pub fn move_to_end_of_paragraph(
11601        &mut self,
11602        _: &MoveToEndOfParagraph,
11603        window: &mut Window,
11604        cx: &mut Context<Self>,
11605    ) {
11606        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11607            cx.propagate();
11608            return;
11609        }
11610        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11611        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11612            s.move_with(|map, selection| {
11613                selection.collapse_to(
11614                    movement::end_of_paragraph(map, selection.head(), 1),
11615                    SelectionGoal::None,
11616                )
11617            });
11618        })
11619    }
11620
11621    pub fn select_to_start_of_paragraph(
11622        &mut self,
11623        _: &SelectToStartOfParagraph,
11624        window: &mut Window,
11625        cx: &mut Context<Self>,
11626    ) {
11627        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11628            cx.propagate();
11629            return;
11630        }
11631        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11632        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11633            s.move_heads_with(|map, head, _| {
11634                (
11635                    movement::start_of_paragraph(map, head, 1),
11636                    SelectionGoal::None,
11637                )
11638            });
11639        })
11640    }
11641
11642    pub fn select_to_end_of_paragraph(
11643        &mut self,
11644        _: &SelectToEndOfParagraph,
11645        window: &mut Window,
11646        cx: &mut Context<Self>,
11647    ) {
11648        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11649            cx.propagate();
11650            return;
11651        }
11652        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11653        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11654            s.move_heads_with(|map, head, _| {
11655                (
11656                    movement::end_of_paragraph(map, head, 1),
11657                    SelectionGoal::None,
11658                )
11659            });
11660        })
11661    }
11662
11663    pub fn move_to_start_of_excerpt(
11664        &mut self,
11665        _: &MoveToStartOfExcerpt,
11666        window: &mut Window,
11667        cx: &mut Context<Self>,
11668    ) {
11669        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11670            cx.propagate();
11671            return;
11672        }
11673        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11675            s.move_with(|map, selection| {
11676                selection.collapse_to(
11677                    movement::start_of_excerpt(
11678                        map,
11679                        selection.head(),
11680                        workspace::searchable::Direction::Prev,
11681                    ),
11682                    SelectionGoal::None,
11683                )
11684            });
11685        })
11686    }
11687
11688    pub fn move_to_start_of_next_excerpt(
11689        &mut self,
11690        _: &MoveToStartOfNextExcerpt,
11691        window: &mut Window,
11692        cx: &mut Context<Self>,
11693    ) {
11694        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11695            cx.propagate();
11696            return;
11697        }
11698
11699        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11700            s.move_with(|map, selection| {
11701                selection.collapse_to(
11702                    movement::start_of_excerpt(
11703                        map,
11704                        selection.head(),
11705                        workspace::searchable::Direction::Next,
11706                    ),
11707                    SelectionGoal::None,
11708                )
11709            });
11710        })
11711    }
11712
11713    pub fn move_to_end_of_excerpt(
11714        &mut self,
11715        _: &MoveToEndOfExcerpt,
11716        window: &mut Window,
11717        cx: &mut Context<Self>,
11718    ) {
11719        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11720            cx.propagate();
11721            return;
11722        }
11723        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11724        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11725            s.move_with(|map, selection| {
11726                selection.collapse_to(
11727                    movement::end_of_excerpt(
11728                        map,
11729                        selection.head(),
11730                        workspace::searchable::Direction::Next,
11731                    ),
11732                    SelectionGoal::None,
11733                )
11734            });
11735        })
11736    }
11737
11738    pub fn move_to_end_of_previous_excerpt(
11739        &mut self,
11740        _: &MoveToEndOfPreviousExcerpt,
11741        window: &mut Window,
11742        cx: &mut Context<Self>,
11743    ) {
11744        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11745            cx.propagate();
11746            return;
11747        }
11748        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11750            s.move_with(|map, selection| {
11751                selection.collapse_to(
11752                    movement::end_of_excerpt(
11753                        map,
11754                        selection.head(),
11755                        workspace::searchable::Direction::Prev,
11756                    ),
11757                    SelectionGoal::None,
11758                )
11759            });
11760        })
11761    }
11762
11763    pub fn select_to_start_of_excerpt(
11764        &mut self,
11765        _: &SelectToStartOfExcerpt,
11766        window: &mut Window,
11767        cx: &mut Context<Self>,
11768    ) {
11769        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11770            cx.propagate();
11771            return;
11772        }
11773        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11774        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11775            s.move_heads_with(|map, head, _| {
11776                (
11777                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11778                    SelectionGoal::None,
11779                )
11780            });
11781        })
11782    }
11783
11784    pub fn select_to_start_of_next_excerpt(
11785        &mut self,
11786        _: &SelectToStartOfNextExcerpt,
11787        window: &mut Window,
11788        cx: &mut Context<Self>,
11789    ) {
11790        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11791            cx.propagate();
11792            return;
11793        }
11794        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11795        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11796            s.move_heads_with(|map, head, _| {
11797                (
11798                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11799                    SelectionGoal::None,
11800                )
11801            });
11802        })
11803    }
11804
11805    pub fn select_to_end_of_excerpt(
11806        &mut self,
11807        _: &SelectToEndOfExcerpt,
11808        window: &mut Window,
11809        cx: &mut Context<Self>,
11810    ) {
11811        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11812            cx.propagate();
11813            return;
11814        }
11815        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11816        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11817            s.move_heads_with(|map, head, _| {
11818                (
11819                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11820                    SelectionGoal::None,
11821                )
11822            });
11823        })
11824    }
11825
11826    pub fn select_to_end_of_previous_excerpt(
11827        &mut self,
11828        _: &SelectToEndOfPreviousExcerpt,
11829        window: &mut Window,
11830        cx: &mut Context<Self>,
11831    ) {
11832        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11833            cx.propagate();
11834            return;
11835        }
11836        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11837        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11838            s.move_heads_with(|map, head, _| {
11839                (
11840                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11841                    SelectionGoal::None,
11842                )
11843            });
11844        })
11845    }
11846
11847    pub fn move_to_beginning(
11848        &mut self,
11849        _: &MoveToBeginning,
11850        window: &mut Window,
11851        cx: &mut Context<Self>,
11852    ) {
11853        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11854            cx.propagate();
11855            return;
11856        }
11857        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11858        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11859            s.select_ranges(vec![0..0]);
11860        });
11861    }
11862
11863    pub fn select_to_beginning(
11864        &mut self,
11865        _: &SelectToBeginning,
11866        window: &mut Window,
11867        cx: &mut Context<Self>,
11868    ) {
11869        let mut selection = self.selections.last::<Point>(cx);
11870        selection.set_head(Point::zero(), SelectionGoal::None);
11871        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11872        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11873            s.select(vec![selection]);
11874        });
11875    }
11876
11877    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11878        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11879            cx.propagate();
11880            return;
11881        }
11882        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11883        let cursor = self.buffer.read(cx).read(cx).len();
11884        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11885            s.select_ranges(vec![cursor..cursor])
11886        });
11887    }
11888
11889    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11890        self.nav_history = nav_history;
11891    }
11892
11893    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11894        self.nav_history.as_ref()
11895    }
11896
11897    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11898        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11899    }
11900
11901    fn push_to_nav_history(
11902        &mut self,
11903        cursor_anchor: Anchor,
11904        new_position: Option<Point>,
11905        is_deactivate: bool,
11906        cx: &mut Context<Self>,
11907    ) {
11908        if let Some(nav_history) = self.nav_history.as_mut() {
11909            let buffer = self.buffer.read(cx).read(cx);
11910            let cursor_position = cursor_anchor.to_point(&buffer);
11911            let scroll_state = self.scroll_manager.anchor();
11912            let scroll_top_row = scroll_state.top_row(&buffer);
11913            drop(buffer);
11914
11915            if let Some(new_position) = new_position {
11916                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11917                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11918                    return;
11919                }
11920            }
11921
11922            nav_history.push(
11923                Some(NavigationData {
11924                    cursor_anchor,
11925                    cursor_position,
11926                    scroll_anchor: scroll_state,
11927                    scroll_top_row,
11928                }),
11929                cx,
11930            );
11931            cx.emit(EditorEvent::PushedToNavHistory {
11932                anchor: cursor_anchor,
11933                is_deactivate,
11934            })
11935        }
11936    }
11937
11938    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11939        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11940        let buffer = self.buffer.read(cx).snapshot(cx);
11941        let mut selection = self.selections.first::<usize>(cx);
11942        selection.set_head(buffer.len(), SelectionGoal::None);
11943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11944            s.select(vec![selection]);
11945        });
11946    }
11947
11948    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11949        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11950        let end = self.buffer.read(cx).read(cx).len();
11951        self.change_selections(None, window, cx, |s| {
11952            s.select_ranges(vec![0..end]);
11953        });
11954    }
11955
11956    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11957        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11958        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11959        let mut selections = self.selections.all::<Point>(cx);
11960        let max_point = display_map.buffer_snapshot.max_point();
11961        for selection in &mut selections {
11962            let rows = selection.spanned_rows(true, &display_map);
11963            selection.start = Point::new(rows.start.0, 0);
11964            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11965            selection.reversed = false;
11966        }
11967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11968            s.select(selections);
11969        });
11970    }
11971
11972    pub fn split_selection_into_lines(
11973        &mut self,
11974        _: &SplitSelectionIntoLines,
11975        window: &mut Window,
11976        cx: &mut Context<Self>,
11977    ) {
11978        let selections = self
11979            .selections
11980            .all::<Point>(cx)
11981            .into_iter()
11982            .map(|selection| selection.start..selection.end)
11983            .collect::<Vec<_>>();
11984        self.unfold_ranges(&selections, true, true, cx);
11985
11986        let mut new_selection_ranges = Vec::new();
11987        {
11988            let buffer = self.buffer.read(cx).read(cx);
11989            for selection in selections {
11990                for row in selection.start.row..selection.end.row {
11991                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11992                    new_selection_ranges.push(cursor..cursor);
11993                }
11994
11995                let is_multiline_selection = selection.start.row != selection.end.row;
11996                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11997                // so this action feels more ergonomic when paired with other selection operations
11998                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11999                if !should_skip_last {
12000                    new_selection_ranges.push(selection.end..selection.end);
12001                }
12002            }
12003        }
12004        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12005            s.select_ranges(new_selection_ranges);
12006        });
12007    }
12008
12009    pub fn add_selection_above(
12010        &mut self,
12011        _: &AddSelectionAbove,
12012        window: &mut Window,
12013        cx: &mut Context<Self>,
12014    ) {
12015        self.add_selection(true, window, cx);
12016    }
12017
12018    pub fn add_selection_below(
12019        &mut self,
12020        _: &AddSelectionBelow,
12021        window: &mut Window,
12022        cx: &mut Context<Self>,
12023    ) {
12024        self.add_selection(false, window, cx);
12025    }
12026
12027    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12028        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12029
12030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12031        let mut selections = self.selections.all::<Point>(cx);
12032        let text_layout_details = self.text_layout_details(window);
12033        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12034            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12035            let range = oldest_selection.display_range(&display_map).sorted();
12036
12037            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12038            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12039            let positions = start_x.min(end_x)..start_x.max(end_x);
12040
12041            selections.clear();
12042            let mut stack = Vec::new();
12043            for row in range.start.row().0..=range.end.row().0 {
12044                if let Some(selection) = self.selections.build_columnar_selection(
12045                    &display_map,
12046                    DisplayRow(row),
12047                    &positions,
12048                    oldest_selection.reversed,
12049                    &text_layout_details,
12050                ) {
12051                    stack.push(selection.id);
12052                    selections.push(selection);
12053                }
12054            }
12055
12056            if above {
12057                stack.reverse();
12058            }
12059
12060            AddSelectionsState { above, stack }
12061        });
12062
12063        let last_added_selection = *state.stack.last().unwrap();
12064        let mut new_selections = Vec::new();
12065        if above == state.above {
12066            let end_row = if above {
12067                DisplayRow(0)
12068            } else {
12069                display_map.max_point().row()
12070            };
12071
12072            'outer: for selection in selections {
12073                if selection.id == last_added_selection {
12074                    let range = selection.display_range(&display_map).sorted();
12075                    debug_assert_eq!(range.start.row(), range.end.row());
12076                    let mut row = range.start.row();
12077                    let positions =
12078                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12079                            px(start)..px(end)
12080                        } else {
12081                            let start_x =
12082                                display_map.x_for_display_point(range.start, &text_layout_details);
12083                            let end_x =
12084                                display_map.x_for_display_point(range.end, &text_layout_details);
12085                            start_x.min(end_x)..start_x.max(end_x)
12086                        };
12087
12088                    while row != end_row {
12089                        if above {
12090                            row.0 -= 1;
12091                        } else {
12092                            row.0 += 1;
12093                        }
12094
12095                        if let Some(new_selection) = self.selections.build_columnar_selection(
12096                            &display_map,
12097                            row,
12098                            &positions,
12099                            selection.reversed,
12100                            &text_layout_details,
12101                        ) {
12102                            state.stack.push(new_selection.id);
12103                            if above {
12104                                new_selections.push(new_selection);
12105                                new_selections.push(selection);
12106                            } else {
12107                                new_selections.push(selection);
12108                                new_selections.push(new_selection);
12109                            }
12110
12111                            continue 'outer;
12112                        }
12113                    }
12114                }
12115
12116                new_selections.push(selection);
12117            }
12118        } else {
12119            new_selections = selections;
12120            new_selections.retain(|s| s.id != last_added_selection);
12121            state.stack.pop();
12122        }
12123
12124        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12125            s.select(new_selections);
12126        });
12127        if state.stack.len() > 1 {
12128            self.add_selections_state = Some(state);
12129        }
12130    }
12131
12132    pub fn select_next_match_internal(
12133        &mut self,
12134        display_map: &DisplaySnapshot,
12135        replace_newest: bool,
12136        autoscroll: Option<Autoscroll>,
12137        window: &mut Window,
12138        cx: &mut Context<Self>,
12139    ) -> Result<()> {
12140        fn select_next_match_ranges(
12141            this: &mut Editor,
12142            range: Range<usize>,
12143            reversed: bool,
12144            replace_newest: bool,
12145            auto_scroll: Option<Autoscroll>,
12146            window: &mut Window,
12147            cx: &mut Context<Editor>,
12148        ) {
12149            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12150            this.change_selections(auto_scroll, window, cx, |s| {
12151                if replace_newest {
12152                    s.delete(s.newest_anchor().id);
12153                }
12154                if reversed {
12155                    s.insert_range(range.end..range.start);
12156                } else {
12157                    s.insert_range(range);
12158                }
12159            });
12160        }
12161
12162        let buffer = &display_map.buffer_snapshot;
12163        let mut selections = self.selections.all::<usize>(cx);
12164        if let Some(mut select_next_state) = self.select_next_state.take() {
12165            let query = &select_next_state.query;
12166            if !select_next_state.done {
12167                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12168                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12169                let mut next_selected_range = None;
12170
12171                let bytes_after_last_selection =
12172                    buffer.bytes_in_range(last_selection.end..buffer.len());
12173                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12174                let query_matches = query
12175                    .stream_find_iter(bytes_after_last_selection)
12176                    .map(|result| (last_selection.end, result))
12177                    .chain(
12178                        query
12179                            .stream_find_iter(bytes_before_first_selection)
12180                            .map(|result| (0, result)),
12181                    );
12182
12183                for (start_offset, query_match) in query_matches {
12184                    let query_match = query_match.unwrap(); // can only fail due to I/O
12185                    let offset_range =
12186                        start_offset + query_match.start()..start_offset + query_match.end();
12187                    let display_range = offset_range.start.to_display_point(display_map)
12188                        ..offset_range.end.to_display_point(display_map);
12189
12190                    if !select_next_state.wordwise
12191                        || (!movement::is_inside_word(display_map, display_range.start)
12192                            && !movement::is_inside_word(display_map, display_range.end))
12193                    {
12194                        // TODO: This is n^2, because we might check all the selections
12195                        if !selections
12196                            .iter()
12197                            .any(|selection| selection.range().overlaps(&offset_range))
12198                        {
12199                            next_selected_range = Some(offset_range);
12200                            break;
12201                        }
12202                    }
12203                }
12204
12205                if let Some(next_selected_range) = next_selected_range {
12206                    select_next_match_ranges(
12207                        self,
12208                        next_selected_range,
12209                        last_selection.reversed,
12210                        replace_newest,
12211                        autoscroll,
12212                        window,
12213                        cx,
12214                    );
12215                } else {
12216                    select_next_state.done = true;
12217                }
12218            }
12219
12220            self.select_next_state = Some(select_next_state);
12221        } else {
12222            let mut only_carets = true;
12223            let mut same_text_selected = true;
12224            let mut selected_text = None;
12225
12226            let mut selections_iter = selections.iter().peekable();
12227            while let Some(selection) = selections_iter.next() {
12228                if selection.start != selection.end {
12229                    only_carets = false;
12230                }
12231
12232                if same_text_selected {
12233                    if selected_text.is_none() {
12234                        selected_text =
12235                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12236                    }
12237
12238                    if let Some(next_selection) = selections_iter.peek() {
12239                        if next_selection.range().len() == selection.range().len() {
12240                            let next_selected_text = buffer
12241                                .text_for_range(next_selection.range())
12242                                .collect::<String>();
12243                            if Some(next_selected_text) != selected_text {
12244                                same_text_selected = false;
12245                                selected_text = None;
12246                            }
12247                        } else {
12248                            same_text_selected = false;
12249                            selected_text = None;
12250                        }
12251                    }
12252                }
12253            }
12254
12255            if only_carets {
12256                for selection in &mut selections {
12257                    let word_range = movement::surrounding_word(
12258                        display_map,
12259                        selection.start.to_display_point(display_map),
12260                    );
12261                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12262                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12263                    selection.goal = SelectionGoal::None;
12264                    selection.reversed = false;
12265                    select_next_match_ranges(
12266                        self,
12267                        selection.start..selection.end,
12268                        selection.reversed,
12269                        replace_newest,
12270                        autoscroll,
12271                        window,
12272                        cx,
12273                    );
12274                }
12275
12276                if selections.len() == 1 {
12277                    let selection = selections
12278                        .last()
12279                        .expect("ensured that there's only one selection");
12280                    let query = buffer
12281                        .text_for_range(selection.start..selection.end)
12282                        .collect::<String>();
12283                    let is_empty = query.is_empty();
12284                    let select_state = SelectNextState {
12285                        query: AhoCorasick::new(&[query])?,
12286                        wordwise: true,
12287                        done: is_empty,
12288                    };
12289                    self.select_next_state = Some(select_state);
12290                } else {
12291                    self.select_next_state = None;
12292                }
12293            } else if let Some(selected_text) = selected_text {
12294                self.select_next_state = Some(SelectNextState {
12295                    query: AhoCorasick::new(&[selected_text])?,
12296                    wordwise: false,
12297                    done: false,
12298                });
12299                self.select_next_match_internal(
12300                    display_map,
12301                    replace_newest,
12302                    autoscroll,
12303                    window,
12304                    cx,
12305                )?;
12306            }
12307        }
12308        Ok(())
12309    }
12310
12311    pub fn select_all_matches(
12312        &mut self,
12313        _action: &SelectAllMatches,
12314        window: &mut Window,
12315        cx: &mut Context<Self>,
12316    ) -> Result<()> {
12317        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12318
12319        self.push_to_selection_history();
12320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12321
12322        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12323        let Some(select_next_state) = self.select_next_state.as_mut() else {
12324            return Ok(());
12325        };
12326        if select_next_state.done {
12327            return Ok(());
12328        }
12329
12330        let mut new_selections = Vec::new();
12331
12332        let reversed = self.selections.oldest::<usize>(cx).reversed;
12333        let buffer = &display_map.buffer_snapshot;
12334        let query_matches = select_next_state
12335            .query
12336            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12337
12338        for query_match in query_matches.into_iter() {
12339            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12340            let offset_range = if reversed {
12341                query_match.end()..query_match.start()
12342            } else {
12343                query_match.start()..query_match.end()
12344            };
12345            let display_range = offset_range.start.to_display_point(&display_map)
12346                ..offset_range.end.to_display_point(&display_map);
12347
12348            if !select_next_state.wordwise
12349                || (!movement::is_inside_word(&display_map, display_range.start)
12350                    && !movement::is_inside_word(&display_map, display_range.end))
12351            {
12352                new_selections.push(offset_range.start..offset_range.end);
12353            }
12354        }
12355
12356        select_next_state.done = true;
12357        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12358        self.change_selections(None, window, cx, |selections| {
12359            selections.select_ranges(new_selections)
12360        });
12361
12362        Ok(())
12363    }
12364
12365    pub fn select_next(
12366        &mut self,
12367        action: &SelectNext,
12368        window: &mut Window,
12369        cx: &mut Context<Self>,
12370    ) -> Result<()> {
12371        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12372        self.push_to_selection_history();
12373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12374        self.select_next_match_internal(
12375            &display_map,
12376            action.replace_newest,
12377            Some(Autoscroll::newest()),
12378            window,
12379            cx,
12380        )?;
12381        Ok(())
12382    }
12383
12384    pub fn select_previous(
12385        &mut self,
12386        action: &SelectPrevious,
12387        window: &mut Window,
12388        cx: &mut Context<Self>,
12389    ) -> Result<()> {
12390        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12391        self.push_to_selection_history();
12392        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12393        let buffer = &display_map.buffer_snapshot;
12394        let mut selections = self.selections.all::<usize>(cx);
12395        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12396            let query = &select_prev_state.query;
12397            if !select_prev_state.done {
12398                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12399                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12400                let mut next_selected_range = None;
12401                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12402                let bytes_before_last_selection =
12403                    buffer.reversed_bytes_in_range(0..last_selection.start);
12404                let bytes_after_first_selection =
12405                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12406                let query_matches = query
12407                    .stream_find_iter(bytes_before_last_selection)
12408                    .map(|result| (last_selection.start, result))
12409                    .chain(
12410                        query
12411                            .stream_find_iter(bytes_after_first_selection)
12412                            .map(|result| (buffer.len(), result)),
12413                    );
12414                for (end_offset, query_match) in query_matches {
12415                    let query_match = query_match.unwrap(); // can only fail due to I/O
12416                    let offset_range =
12417                        end_offset - query_match.end()..end_offset - query_match.start();
12418                    let display_range = offset_range.start.to_display_point(&display_map)
12419                        ..offset_range.end.to_display_point(&display_map);
12420
12421                    if !select_prev_state.wordwise
12422                        || (!movement::is_inside_word(&display_map, display_range.start)
12423                            && !movement::is_inside_word(&display_map, display_range.end))
12424                    {
12425                        next_selected_range = Some(offset_range);
12426                        break;
12427                    }
12428                }
12429
12430                if let Some(next_selected_range) = next_selected_range {
12431                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12432                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12433                        if action.replace_newest {
12434                            s.delete(s.newest_anchor().id);
12435                        }
12436                        if last_selection.reversed {
12437                            s.insert_range(next_selected_range.end..next_selected_range.start);
12438                        } else {
12439                            s.insert_range(next_selected_range);
12440                        }
12441                    });
12442                } else {
12443                    select_prev_state.done = true;
12444                }
12445            }
12446
12447            self.select_prev_state = Some(select_prev_state);
12448        } else {
12449            let mut only_carets = true;
12450            let mut same_text_selected = true;
12451            let mut selected_text = None;
12452
12453            let mut selections_iter = selections.iter().peekable();
12454            while let Some(selection) = selections_iter.next() {
12455                if selection.start != selection.end {
12456                    only_carets = false;
12457                }
12458
12459                if same_text_selected {
12460                    if selected_text.is_none() {
12461                        selected_text =
12462                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12463                    }
12464
12465                    if let Some(next_selection) = selections_iter.peek() {
12466                        if next_selection.range().len() == selection.range().len() {
12467                            let next_selected_text = buffer
12468                                .text_for_range(next_selection.range())
12469                                .collect::<String>();
12470                            if Some(next_selected_text) != selected_text {
12471                                same_text_selected = false;
12472                                selected_text = None;
12473                            }
12474                        } else {
12475                            same_text_selected = false;
12476                            selected_text = None;
12477                        }
12478                    }
12479                }
12480            }
12481
12482            if only_carets {
12483                for selection in &mut selections {
12484                    let word_range = movement::surrounding_word(
12485                        &display_map,
12486                        selection.start.to_display_point(&display_map),
12487                    );
12488                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12489                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12490                    selection.goal = SelectionGoal::None;
12491                    selection.reversed = false;
12492                }
12493                if selections.len() == 1 {
12494                    let selection = selections
12495                        .last()
12496                        .expect("ensured that there's only one selection");
12497                    let query = buffer
12498                        .text_for_range(selection.start..selection.end)
12499                        .collect::<String>();
12500                    let is_empty = query.is_empty();
12501                    let select_state = SelectNextState {
12502                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12503                        wordwise: true,
12504                        done: is_empty,
12505                    };
12506                    self.select_prev_state = Some(select_state);
12507                } else {
12508                    self.select_prev_state = None;
12509                }
12510
12511                self.unfold_ranges(
12512                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12513                    false,
12514                    true,
12515                    cx,
12516                );
12517                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12518                    s.select(selections);
12519                });
12520            } else if let Some(selected_text) = selected_text {
12521                self.select_prev_state = Some(SelectNextState {
12522                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12523                    wordwise: false,
12524                    done: false,
12525                });
12526                self.select_previous(action, window, cx)?;
12527            }
12528        }
12529        Ok(())
12530    }
12531
12532    pub fn find_next_match(
12533        &mut self,
12534        _: &FindNextMatch,
12535        window: &mut Window,
12536        cx: &mut Context<Self>,
12537    ) -> Result<()> {
12538        let selections = self.selections.disjoint_anchors();
12539        match selections.first() {
12540            Some(first) if selections.len() >= 2 => {
12541                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12542                    s.select_ranges([first.range()]);
12543                });
12544            }
12545            _ => self.select_next(
12546                &SelectNext {
12547                    replace_newest: true,
12548                },
12549                window,
12550                cx,
12551            )?,
12552        }
12553        Ok(())
12554    }
12555
12556    pub fn find_previous_match(
12557        &mut self,
12558        _: &FindPreviousMatch,
12559        window: &mut Window,
12560        cx: &mut Context<Self>,
12561    ) -> Result<()> {
12562        let selections = self.selections.disjoint_anchors();
12563        match selections.last() {
12564            Some(last) if selections.len() >= 2 => {
12565                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12566                    s.select_ranges([last.range()]);
12567                });
12568            }
12569            _ => self.select_previous(
12570                &SelectPrevious {
12571                    replace_newest: true,
12572                },
12573                window,
12574                cx,
12575            )?,
12576        }
12577        Ok(())
12578    }
12579
12580    pub fn toggle_comments(
12581        &mut self,
12582        action: &ToggleComments,
12583        window: &mut Window,
12584        cx: &mut Context<Self>,
12585    ) {
12586        if self.read_only(cx) {
12587            return;
12588        }
12589        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12590        let text_layout_details = &self.text_layout_details(window);
12591        self.transact(window, cx, |this, window, cx| {
12592            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12593            let mut edits = Vec::new();
12594            let mut selection_edit_ranges = Vec::new();
12595            let mut last_toggled_row = None;
12596            let snapshot = this.buffer.read(cx).read(cx);
12597            let empty_str: Arc<str> = Arc::default();
12598            let mut suffixes_inserted = Vec::new();
12599            let ignore_indent = action.ignore_indent;
12600
12601            fn comment_prefix_range(
12602                snapshot: &MultiBufferSnapshot,
12603                row: MultiBufferRow,
12604                comment_prefix: &str,
12605                comment_prefix_whitespace: &str,
12606                ignore_indent: bool,
12607            ) -> Range<Point> {
12608                let indent_size = if ignore_indent {
12609                    0
12610                } else {
12611                    snapshot.indent_size_for_line(row).len
12612                };
12613
12614                let start = Point::new(row.0, indent_size);
12615
12616                let mut line_bytes = snapshot
12617                    .bytes_in_range(start..snapshot.max_point())
12618                    .flatten()
12619                    .copied();
12620
12621                // If this line currently begins with the line comment prefix, then record
12622                // the range containing the prefix.
12623                if line_bytes
12624                    .by_ref()
12625                    .take(comment_prefix.len())
12626                    .eq(comment_prefix.bytes())
12627                {
12628                    // Include any whitespace that matches the comment prefix.
12629                    let matching_whitespace_len = line_bytes
12630                        .zip(comment_prefix_whitespace.bytes())
12631                        .take_while(|(a, b)| a == b)
12632                        .count() as u32;
12633                    let end = Point::new(
12634                        start.row,
12635                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12636                    );
12637                    start..end
12638                } else {
12639                    start..start
12640                }
12641            }
12642
12643            fn comment_suffix_range(
12644                snapshot: &MultiBufferSnapshot,
12645                row: MultiBufferRow,
12646                comment_suffix: &str,
12647                comment_suffix_has_leading_space: bool,
12648            ) -> Range<Point> {
12649                let end = Point::new(row.0, snapshot.line_len(row));
12650                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12651
12652                let mut line_end_bytes = snapshot
12653                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12654                    .flatten()
12655                    .copied();
12656
12657                let leading_space_len = if suffix_start_column > 0
12658                    && line_end_bytes.next() == Some(b' ')
12659                    && comment_suffix_has_leading_space
12660                {
12661                    1
12662                } else {
12663                    0
12664                };
12665
12666                // If this line currently begins with the line comment prefix, then record
12667                // the range containing the prefix.
12668                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12669                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12670                    start..end
12671                } else {
12672                    end..end
12673                }
12674            }
12675
12676            // TODO: Handle selections that cross excerpts
12677            for selection in &mut selections {
12678                let start_column = snapshot
12679                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12680                    .len;
12681                let language = if let Some(language) =
12682                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12683                {
12684                    language
12685                } else {
12686                    continue;
12687                };
12688
12689                selection_edit_ranges.clear();
12690
12691                // If multiple selections contain a given row, avoid processing that
12692                // row more than once.
12693                let mut start_row = MultiBufferRow(selection.start.row);
12694                if last_toggled_row == Some(start_row) {
12695                    start_row = start_row.next_row();
12696                }
12697                let end_row =
12698                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12699                        MultiBufferRow(selection.end.row - 1)
12700                    } else {
12701                        MultiBufferRow(selection.end.row)
12702                    };
12703                last_toggled_row = Some(end_row);
12704
12705                if start_row > end_row {
12706                    continue;
12707                }
12708
12709                // If the language has line comments, toggle those.
12710                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12711
12712                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12713                if ignore_indent {
12714                    full_comment_prefixes = full_comment_prefixes
12715                        .into_iter()
12716                        .map(|s| Arc::from(s.trim_end()))
12717                        .collect();
12718                }
12719
12720                if !full_comment_prefixes.is_empty() {
12721                    let first_prefix = full_comment_prefixes
12722                        .first()
12723                        .expect("prefixes is non-empty");
12724                    let prefix_trimmed_lengths = full_comment_prefixes
12725                        .iter()
12726                        .map(|p| p.trim_end_matches(' ').len())
12727                        .collect::<SmallVec<[usize; 4]>>();
12728
12729                    let mut all_selection_lines_are_comments = true;
12730
12731                    for row in start_row.0..=end_row.0 {
12732                        let row = MultiBufferRow(row);
12733                        if start_row < end_row && snapshot.is_line_blank(row) {
12734                            continue;
12735                        }
12736
12737                        let prefix_range = full_comment_prefixes
12738                            .iter()
12739                            .zip(prefix_trimmed_lengths.iter().copied())
12740                            .map(|(prefix, trimmed_prefix_len)| {
12741                                comment_prefix_range(
12742                                    snapshot.deref(),
12743                                    row,
12744                                    &prefix[..trimmed_prefix_len],
12745                                    &prefix[trimmed_prefix_len..],
12746                                    ignore_indent,
12747                                )
12748                            })
12749                            .max_by_key(|range| range.end.column - range.start.column)
12750                            .expect("prefixes is non-empty");
12751
12752                        if prefix_range.is_empty() {
12753                            all_selection_lines_are_comments = false;
12754                        }
12755
12756                        selection_edit_ranges.push(prefix_range);
12757                    }
12758
12759                    if all_selection_lines_are_comments {
12760                        edits.extend(
12761                            selection_edit_ranges
12762                                .iter()
12763                                .cloned()
12764                                .map(|range| (range, empty_str.clone())),
12765                        );
12766                    } else {
12767                        let min_column = selection_edit_ranges
12768                            .iter()
12769                            .map(|range| range.start.column)
12770                            .min()
12771                            .unwrap_or(0);
12772                        edits.extend(selection_edit_ranges.iter().map(|range| {
12773                            let position = Point::new(range.start.row, min_column);
12774                            (position..position, first_prefix.clone())
12775                        }));
12776                    }
12777                } else if let Some((full_comment_prefix, comment_suffix)) =
12778                    language.block_comment_delimiters()
12779                {
12780                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12781                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12782                    let prefix_range = comment_prefix_range(
12783                        snapshot.deref(),
12784                        start_row,
12785                        comment_prefix,
12786                        comment_prefix_whitespace,
12787                        ignore_indent,
12788                    );
12789                    let suffix_range = comment_suffix_range(
12790                        snapshot.deref(),
12791                        end_row,
12792                        comment_suffix.trim_start_matches(' '),
12793                        comment_suffix.starts_with(' '),
12794                    );
12795
12796                    if prefix_range.is_empty() || suffix_range.is_empty() {
12797                        edits.push((
12798                            prefix_range.start..prefix_range.start,
12799                            full_comment_prefix.clone(),
12800                        ));
12801                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12802                        suffixes_inserted.push((end_row, comment_suffix.len()));
12803                    } else {
12804                        edits.push((prefix_range, empty_str.clone()));
12805                        edits.push((suffix_range, empty_str.clone()));
12806                    }
12807                } else {
12808                    continue;
12809                }
12810            }
12811
12812            drop(snapshot);
12813            this.buffer.update(cx, |buffer, cx| {
12814                buffer.edit(edits, None, cx);
12815            });
12816
12817            // Adjust selections so that they end before any comment suffixes that
12818            // were inserted.
12819            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12820            let mut selections = this.selections.all::<Point>(cx);
12821            let snapshot = this.buffer.read(cx).read(cx);
12822            for selection in &mut selections {
12823                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12824                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12825                        Ordering::Less => {
12826                            suffixes_inserted.next();
12827                            continue;
12828                        }
12829                        Ordering::Greater => break,
12830                        Ordering::Equal => {
12831                            if selection.end.column == snapshot.line_len(row) {
12832                                if selection.is_empty() {
12833                                    selection.start.column -= suffix_len as u32;
12834                                }
12835                                selection.end.column -= suffix_len as u32;
12836                            }
12837                            break;
12838                        }
12839                    }
12840                }
12841            }
12842
12843            drop(snapshot);
12844            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12845                s.select(selections)
12846            });
12847
12848            let selections = this.selections.all::<Point>(cx);
12849            let selections_on_single_row = selections.windows(2).all(|selections| {
12850                selections[0].start.row == selections[1].start.row
12851                    && selections[0].end.row == selections[1].end.row
12852                    && selections[0].start.row == selections[0].end.row
12853            });
12854            let selections_selecting = selections
12855                .iter()
12856                .any(|selection| selection.start != selection.end);
12857            let advance_downwards = action.advance_downwards
12858                && selections_on_single_row
12859                && !selections_selecting
12860                && !matches!(this.mode, EditorMode::SingleLine { .. });
12861
12862            if advance_downwards {
12863                let snapshot = this.buffer.read(cx).snapshot(cx);
12864
12865                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12866                    s.move_cursors_with(|display_snapshot, display_point, _| {
12867                        let mut point = display_point.to_point(display_snapshot);
12868                        point.row += 1;
12869                        point = snapshot.clip_point(point, Bias::Left);
12870                        let display_point = point.to_display_point(display_snapshot);
12871                        let goal = SelectionGoal::HorizontalPosition(
12872                            display_snapshot
12873                                .x_for_display_point(display_point, text_layout_details)
12874                                .into(),
12875                        );
12876                        (display_point, goal)
12877                    })
12878                });
12879            }
12880        });
12881    }
12882
12883    pub fn select_enclosing_symbol(
12884        &mut self,
12885        _: &SelectEnclosingSymbol,
12886        window: &mut Window,
12887        cx: &mut Context<Self>,
12888    ) {
12889        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12890
12891        let buffer = self.buffer.read(cx).snapshot(cx);
12892        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12893
12894        fn update_selection(
12895            selection: &Selection<usize>,
12896            buffer_snap: &MultiBufferSnapshot,
12897        ) -> Option<Selection<usize>> {
12898            let cursor = selection.head();
12899            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12900            for symbol in symbols.iter().rev() {
12901                let start = symbol.range.start.to_offset(buffer_snap);
12902                let end = symbol.range.end.to_offset(buffer_snap);
12903                let new_range = start..end;
12904                if start < selection.start || end > selection.end {
12905                    return Some(Selection {
12906                        id: selection.id,
12907                        start: new_range.start,
12908                        end: new_range.end,
12909                        goal: SelectionGoal::None,
12910                        reversed: selection.reversed,
12911                    });
12912                }
12913            }
12914            None
12915        }
12916
12917        let mut selected_larger_symbol = false;
12918        let new_selections = old_selections
12919            .iter()
12920            .map(|selection| match update_selection(selection, &buffer) {
12921                Some(new_selection) => {
12922                    if new_selection.range() != selection.range() {
12923                        selected_larger_symbol = true;
12924                    }
12925                    new_selection
12926                }
12927                None => selection.clone(),
12928            })
12929            .collect::<Vec<_>>();
12930
12931        if selected_larger_symbol {
12932            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12933                s.select(new_selections);
12934            });
12935        }
12936    }
12937
12938    pub fn select_larger_syntax_node(
12939        &mut self,
12940        _: &SelectLargerSyntaxNode,
12941        window: &mut Window,
12942        cx: &mut Context<Self>,
12943    ) {
12944        let Some(visible_row_count) = self.visible_row_count() else {
12945            return;
12946        };
12947        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12948        if old_selections.is_empty() {
12949            return;
12950        }
12951
12952        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12953
12954        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12955        let buffer = self.buffer.read(cx).snapshot(cx);
12956
12957        let mut selected_larger_node = false;
12958        let mut new_selections = old_selections
12959            .iter()
12960            .map(|selection| {
12961                let old_range = selection.start..selection.end;
12962
12963                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12964                    // manually select word at selection
12965                    if ["string_content", "inline"].contains(&node.kind()) {
12966                        let word_range = {
12967                            let display_point = buffer
12968                                .offset_to_point(old_range.start)
12969                                .to_display_point(&display_map);
12970                            let Range { start, end } =
12971                                movement::surrounding_word(&display_map, display_point);
12972                            start.to_point(&display_map).to_offset(&buffer)
12973                                ..end.to_point(&display_map).to_offset(&buffer)
12974                        };
12975                        // ignore if word is already selected
12976                        if !word_range.is_empty() && old_range != word_range {
12977                            let last_word_range = {
12978                                let display_point = buffer
12979                                    .offset_to_point(old_range.end)
12980                                    .to_display_point(&display_map);
12981                                let Range { start, end } =
12982                                    movement::surrounding_word(&display_map, display_point);
12983                                start.to_point(&display_map).to_offset(&buffer)
12984                                    ..end.to_point(&display_map).to_offset(&buffer)
12985                            };
12986                            // only select word if start and end point belongs to same word
12987                            if word_range == last_word_range {
12988                                selected_larger_node = true;
12989                                return Selection {
12990                                    id: selection.id,
12991                                    start: word_range.start,
12992                                    end: word_range.end,
12993                                    goal: SelectionGoal::None,
12994                                    reversed: selection.reversed,
12995                                };
12996                            }
12997                        }
12998                    }
12999                }
13000
13001                let mut new_range = old_range.clone();
13002                while let Some((_node, containing_range)) =
13003                    buffer.syntax_ancestor(new_range.clone())
13004                {
13005                    new_range = match containing_range {
13006                        MultiOrSingleBufferOffsetRange::Single(_) => break,
13007                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
13008                    };
13009                    if !display_map.intersects_fold(new_range.start)
13010                        && !display_map.intersects_fold(new_range.end)
13011                    {
13012                        break;
13013                    }
13014                }
13015
13016                selected_larger_node |= new_range != old_range;
13017                Selection {
13018                    id: selection.id,
13019                    start: new_range.start,
13020                    end: new_range.end,
13021                    goal: SelectionGoal::None,
13022                    reversed: selection.reversed,
13023                }
13024            })
13025            .collect::<Vec<_>>();
13026
13027        if !selected_larger_node {
13028            return; // don't put this call in the history
13029        }
13030
13031        // scroll based on transformation done to the last selection created by the user
13032        let (last_old, last_new) = old_selections
13033            .last()
13034            .zip(new_selections.last().cloned())
13035            .expect("old_selections isn't empty");
13036
13037        // revert selection
13038        let is_selection_reversed = {
13039            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13040            new_selections.last_mut().expect("checked above").reversed =
13041                should_newest_selection_be_reversed;
13042            should_newest_selection_be_reversed
13043        };
13044
13045        if selected_larger_node {
13046            self.select_syntax_node_history.disable_clearing = true;
13047            self.change_selections(None, window, cx, |s| {
13048                s.select(new_selections.clone());
13049            });
13050            self.select_syntax_node_history.disable_clearing = false;
13051        }
13052
13053        let start_row = last_new.start.to_display_point(&display_map).row().0;
13054        let end_row = last_new.end.to_display_point(&display_map).row().0;
13055        let selection_height = end_row - start_row + 1;
13056        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13057
13058        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13059        let scroll_behavior = if fits_on_the_screen {
13060            self.request_autoscroll(Autoscroll::fit(), cx);
13061            SelectSyntaxNodeScrollBehavior::FitSelection
13062        } else if is_selection_reversed {
13063            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13064            SelectSyntaxNodeScrollBehavior::CursorTop
13065        } else {
13066            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13067            SelectSyntaxNodeScrollBehavior::CursorBottom
13068        };
13069
13070        self.select_syntax_node_history.push((
13071            old_selections,
13072            scroll_behavior,
13073            is_selection_reversed,
13074        ));
13075    }
13076
13077    pub fn select_smaller_syntax_node(
13078        &mut self,
13079        _: &SelectSmallerSyntaxNode,
13080        window: &mut Window,
13081        cx: &mut Context<Self>,
13082    ) {
13083        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13084
13085        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13086            self.select_syntax_node_history.pop()
13087        {
13088            if let Some(selection) = selections.last_mut() {
13089                selection.reversed = is_selection_reversed;
13090            }
13091
13092            self.select_syntax_node_history.disable_clearing = true;
13093            self.change_selections(None, window, cx, |s| {
13094                s.select(selections.to_vec());
13095            });
13096            self.select_syntax_node_history.disable_clearing = false;
13097
13098            match scroll_behavior {
13099                SelectSyntaxNodeScrollBehavior::CursorTop => {
13100                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13101                }
13102                SelectSyntaxNodeScrollBehavior::FitSelection => {
13103                    self.request_autoscroll(Autoscroll::fit(), cx);
13104                }
13105                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13106                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13107                }
13108            }
13109        }
13110    }
13111
13112    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13113        if !EditorSettings::get_global(cx).gutter.runnables {
13114            self.clear_tasks();
13115            return Task::ready(());
13116        }
13117        let project = self.project.as_ref().map(Entity::downgrade);
13118        let task_sources = self.lsp_task_sources(cx);
13119        cx.spawn_in(window, async move |editor, cx| {
13120            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13121            let Some(project) = project.and_then(|p| p.upgrade()) else {
13122                return;
13123            };
13124            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13125                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13126            }) else {
13127                return;
13128            };
13129
13130            let hide_runnables = project
13131                .update(cx, |project, cx| {
13132                    // Do not display any test indicators in non-dev server remote projects.
13133                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13134                })
13135                .unwrap_or(true);
13136            if hide_runnables {
13137                return;
13138            }
13139            let new_rows =
13140                cx.background_spawn({
13141                    let snapshot = display_snapshot.clone();
13142                    async move {
13143                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13144                    }
13145                })
13146                    .await;
13147            let Ok(lsp_tasks) =
13148                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13149            else {
13150                return;
13151            };
13152            let lsp_tasks = lsp_tasks.await;
13153
13154            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13155                lsp_tasks
13156                    .into_iter()
13157                    .flat_map(|(kind, tasks)| {
13158                        tasks.into_iter().filter_map(move |(location, task)| {
13159                            Some((kind.clone(), location?, task))
13160                        })
13161                    })
13162                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13163                        let buffer = location.target.buffer;
13164                        let buffer_snapshot = buffer.read(cx).snapshot();
13165                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13166                            |(excerpt_id, snapshot, _)| {
13167                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13168                                    display_snapshot
13169                                        .buffer_snapshot
13170                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13171                                } else {
13172                                    None
13173                                }
13174                            },
13175                        );
13176                        if let Some(offset) = offset {
13177                            let task_buffer_range =
13178                                location.target.range.to_point(&buffer_snapshot);
13179                            let context_buffer_range =
13180                                task_buffer_range.to_offset(&buffer_snapshot);
13181                            let context_range = BufferOffset(context_buffer_range.start)
13182                                ..BufferOffset(context_buffer_range.end);
13183
13184                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13185                                .or_insert_with(|| RunnableTasks {
13186                                    templates: Vec::new(),
13187                                    offset,
13188                                    column: task_buffer_range.start.column,
13189                                    extra_variables: HashMap::default(),
13190                                    context_range,
13191                                })
13192                                .templates
13193                                .push((kind, task.original_task().clone()));
13194                        }
13195
13196                        acc
13197                    })
13198            }) else {
13199                return;
13200            };
13201
13202            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13203            editor
13204                .update(cx, |editor, _| {
13205                    editor.clear_tasks();
13206                    for (key, mut value) in rows {
13207                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13208                            value.templates.extend(lsp_tasks.templates);
13209                        }
13210
13211                        editor.insert_tasks(key, value);
13212                    }
13213                    for (key, value) in lsp_tasks_by_rows {
13214                        editor.insert_tasks(key, value);
13215                    }
13216                })
13217                .ok();
13218        })
13219    }
13220    fn fetch_runnable_ranges(
13221        snapshot: &DisplaySnapshot,
13222        range: Range<Anchor>,
13223    ) -> Vec<language::RunnableRange> {
13224        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13225    }
13226
13227    fn runnable_rows(
13228        project: Entity<Project>,
13229        snapshot: DisplaySnapshot,
13230        runnable_ranges: Vec<RunnableRange>,
13231        mut cx: AsyncWindowContext,
13232    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13233        runnable_ranges
13234            .into_iter()
13235            .filter_map(|mut runnable| {
13236                let tasks = cx
13237                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13238                    .ok()?;
13239                if tasks.is_empty() {
13240                    return None;
13241                }
13242
13243                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13244
13245                let row = snapshot
13246                    .buffer_snapshot
13247                    .buffer_line_for_row(MultiBufferRow(point.row))?
13248                    .1
13249                    .start
13250                    .row;
13251
13252                let context_range =
13253                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13254                Some((
13255                    (runnable.buffer_id, row),
13256                    RunnableTasks {
13257                        templates: tasks,
13258                        offset: snapshot
13259                            .buffer_snapshot
13260                            .anchor_before(runnable.run_range.start),
13261                        context_range,
13262                        column: point.column,
13263                        extra_variables: runnable.extra_captures,
13264                    },
13265                ))
13266            })
13267            .collect()
13268    }
13269
13270    fn templates_with_tags(
13271        project: &Entity<Project>,
13272        runnable: &mut Runnable,
13273        cx: &mut App,
13274    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13275        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13276            let (worktree_id, file) = project
13277                .buffer_for_id(runnable.buffer, cx)
13278                .and_then(|buffer| buffer.read(cx).file())
13279                .map(|file| (file.worktree_id(cx), file.clone()))
13280                .unzip();
13281
13282            (
13283                project.task_store().read(cx).task_inventory().cloned(),
13284                worktree_id,
13285                file,
13286            )
13287        });
13288
13289        let mut templates_with_tags = mem::take(&mut runnable.tags)
13290            .into_iter()
13291            .flat_map(|RunnableTag(tag)| {
13292                inventory
13293                    .as_ref()
13294                    .into_iter()
13295                    .flat_map(|inventory| {
13296                        inventory.read(cx).list_tasks(
13297                            file.clone(),
13298                            Some(runnable.language.clone()),
13299                            worktree_id,
13300                            cx,
13301                        )
13302                    })
13303                    .filter(move |(_, template)| {
13304                        template.tags.iter().any(|source_tag| source_tag == &tag)
13305                    })
13306            })
13307            .sorted_by_key(|(kind, _)| kind.to_owned())
13308            .collect::<Vec<_>>();
13309        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13310            // Strongest source wins; if we have worktree tag binding, prefer that to
13311            // global and language bindings;
13312            // if we have a global binding, prefer that to language binding.
13313            let first_mismatch = templates_with_tags
13314                .iter()
13315                .position(|(tag_source, _)| tag_source != leading_tag_source);
13316            if let Some(index) = first_mismatch {
13317                templates_with_tags.truncate(index);
13318            }
13319        }
13320
13321        templates_with_tags
13322    }
13323
13324    pub fn move_to_enclosing_bracket(
13325        &mut self,
13326        _: &MoveToEnclosingBracket,
13327        window: &mut Window,
13328        cx: &mut Context<Self>,
13329    ) {
13330        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13331        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13332            s.move_offsets_with(|snapshot, selection| {
13333                let Some(enclosing_bracket_ranges) =
13334                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13335                else {
13336                    return;
13337                };
13338
13339                let mut best_length = usize::MAX;
13340                let mut best_inside = false;
13341                let mut best_in_bracket_range = false;
13342                let mut best_destination = None;
13343                for (open, close) in enclosing_bracket_ranges {
13344                    let close = close.to_inclusive();
13345                    let length = close.end() - open.start;
13346                    let inside = selection.start >= open.end && selection.end <= *close.start();
13347                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13348                        || close.contains(&selection.head());
13349
13350                    // If best is next to a bracket and current isn't, skip
13351                    if !in_bracket_range && best_in_bracket_range {
13352                        continue;
13353                    }
13354
13355                    // Prefer smaller lengths unless best is inside and current isn't
13356                    if length > best_length && (best_inside || !inside) {
13357                        continue;
13358                    }
13359
13360                    best_length = length;
13361                    best_inside = inside;
13362                    best_in_bracket_range = in_bracket_range;
13363                    best_destination = Some(
13364                        if close.contains(&selection.start) && close.contains(&selection.end) {
13365                            if inside { open.end } else { open.start }
13366                        } else if inside {
13367                            *close.start()
13368                        } else {
13369                            *close.end()
13370                        },
13371                    );
13372                }
13373
13374                if let Some(destination) = best_destination {
13375                    selection.collapse_to(destination, SelectionGoal::None);
13376                }
13377            })
13378        });
13379    }
13380
13381    pub fn undo_selection(
13382        &mut self,
13383        _: &UndoSelection,
13384        window: &mut Window,
13385        cx: &mut Context<Self>,
13386    ) {
13387        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13388        self.end_selection(window, cx);
13389        self.selection_history.mode = SelectionHistoryMode::Undoing;
13390        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13391            self.change_selections(None, window, cx, |s| {
13392                s.select_anchors(entry.selections.to_vec())
13393            });
13394            self.select_next_state = entry.select_next_state;
13395            self.select_prev_state = entry.select_prev_state;
13396            self.add_selections_state = entry.add_selections_state;
13397            self.request_autoscroll(Autoscroll::newest(), cx);
13398        }
13399        self.selection_history.mode = SelectionHistoryMode::Normal;
13400    }
13401
13402    pub fn redo_selection(
13403        &mut self,
13404        _: &RedoSelection,
13405        window: &mut Window,
13406        cx: &mut Context<Self>,
13407    ) {
13408        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13409        self.end_selection(window, cx);
13410        self.selection_history.mode = SelectionHistoryMode::Redoing;
13411        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13412            self.change_selections(None, window, cx, |s| {
13413                s.select_anchors(entry.selections.to_vec())
13414            });
13415            self.select_next_state = entry.select_next_state;
13416            self.select_prev_state = entry.select_prev_state;
13417            self.add_selections_state = entry.add_selections_state;
13418            self.request_autoscroll(Autoscroll::newest(), cx);
13419        }
13420        self.selection_history.mode = SelectionHistoryMode::Normal;
13421    }
13422
13423    pub fn expand_excerpts(
13424        &mut self,
13425        action: &ExpandExcerpts,
13426        _: &mut Window,
13427        cx: &mut Context<Self>,
13428    ) {
13429        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13430    }
13431
13432    pub fn expand_excerpts_down(
13433        &mut self,
13434        action: &ExpandExcerptsDown,
13435        _: &mut Window,
13436        cx: &mut Context<Self>,
13437    ) {
13438        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13439    }
13440
13441    pub fn expand_excerpts_up(
13442        &mut self,
13443        action: &ExpandExcerptsUp,
13444        _: &mut Window,
13445        cx: &mut Context<Self>,
13446    ) {
13447        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13448    }
13449
13450    pub fn expand_excerpts_for_direction(
13451        &mut self,
13452        lines: u32,
13453        direction: ExpandExcerptDirection,
13454
13455        cx: &mut Context<Self>,
13456    ) {
13457        let selections = self.selections.disjoint_anchors();
13458
13459        let lines = if lines == 0 {
13460            EditorSettings::get_global(cx).expand_excerpt_lines
13461        } else {
13462            lines
13463        };
13464
13465        self.buffer.update(cx, |buffer, cx| {
13466            let snapshot = buffer.snapshot(cx);
13467            let mut excerpt_ids = selections
13468                .iter()
13469                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13470                .collect::<Vec<_>>();
13471            excerpt_ids.sort();
13472            excerpt_ids.dedup();
13473            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13474        })
13475    }
13476
13477    pub fn expand_excerpt(
13478        &mut self,
13479        excerpt: ExcerptId,
13480        direction: ExpandExcerptDirection,
13481        window: &mut Window,
13482        cx: &mut Context<Self>,
13483    ) {
13484        let current_scroll_position = self.scroll_position(cx);
13485        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13486        let mut should_scroll_up = false;
13487
13488        if direction == ExpandExcerptDirection::Down {
13489            let multi_buffer = self.buffer.read(cx);
13490            let snapshot = multi_buffer.snapshot(cx);
13491            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13492                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13493                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13494                        let buffer_snapshot = buffer.read(cx).snapshot();
13495                        let excerpt_end_row =
13496                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13497                        let last_row = buffer_snapshot.max_point().row;
13498                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13499                        should_scroll_up = lines_below >= lines_to_expand;
13500                    }
13501                }
13502            }
13503        }
13504
13505        self.buffer.update(cx, |buffer, cx| {
13506            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13507        });
13508
13509        if should_scroll_up {
13510            let new_scroll_position =
13511                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13512            self.set_scroll_position(new_scroll_position, window, cx);
13513        }
13514    }
13515
13516    pub fn go_to_singleton_buffer_point(
13517        &mut self,
13518        point: Point,
13519        window: &mut Window,
13520        cx: &mut Context<Self>,
13521    ) {
13522        self.go_to_singleton_buffer_range(point..point, window, cx);
13523    }
13524
13525    pub fn go_to_singleton_buffer_range(
13526        &mut self,
13527        range: Range<Point>,
13528        window: &mut Window,
13529        cx: &mut Context<Self>,
13530    ) {
13531        let multibuffer = self.buffer().read(cx);
13532        let Some(buffer) = multibuffer.as_singleton() else {
13533            return;
13534        };
13535        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13536            return;
13537        };
13538        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13539            return;
13540        };
13541        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13542            s.select_anchor_ranges([start..end])
13543        });
13544    }
13545
13546    pub fn go_to_diagnostic(
13547        &mut self,
13548        _: &GoToDiagnostic,
13549        window: &mut Window,
13550        cx: &mut Context<Self>,
13551    ) {
13552        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13553        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13554    }
13555
13556    pub fn go_to_prev_diagnostic(
13557        &mut self,
13558        _: &GoToPreviousDiagnostic,
13559        window: &mut Window,
13560        cx: &mut Context<Self>,
13561    ) {
13562        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13563        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13564    }
13565
13566    pub fn go_to_diagnostic_impl(
13567        &mut self,
13568        direction: Direction,
13569        window: &mut Window,
13570        cx: &mut Context<Self>,
13571    ) {
13572        let buffer = self.buffer.read(cx).snapshot(cx);
13573        let selection = self.selections.newest::<usize>(cx);
13574
13575        let mut active_group_id = None;
13576        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13577            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13578                active_group_id = Some(active_group.group_id);
13579            }
13580        }
13581
13582        fn filtered(
13583            snapshot: EditorSnapshot,
13584            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13585        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13586            diagnostics
13587                .filter(|entry| entry.range.start != entry.range.end)
13588                .filter(|entry| !entry.diagnostic.is_unnecessary)
13589                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13590        }
13591
13592        let snapshot = self.snapshot(window, cx);
13593        let before = filtered(
13594            snapshot.clone(),
13595            buffer
13596                .diagnostics_in_range(0..selection.start)
13597                .filter(|entry| entry.range.start <= selection.start),
13598        );
13599        let after = filtered(
13600            snapshot,
13601            buffer
13602                .diagnostics_in_range(selection.start..buffer.len())
13603                .filter(|entry| entry.range.start >= selection.start),
13604        );
13605
13606        let mut found: Option<DiagnosticEntry<usize>> = None;
13607        if direction == Direction::Prev {
13608            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13609            {
13610                for diagnostic in prev_diagnostics.into_iter().rev() {
13611                    if diagnostic.range.start != selection.start
13612                        || active_group_id
13613                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13614                    {
13615                        found = Some(diagnostic);
13616                        break 'outer;
13617                    }
13618                }
13619            }
13620        } else {
13621            for diagnostic in after.chain(before) {
13622                if diagnostic.range.start != selection.start
13623                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13624                {
13625                    found = Some(diagnostic);
13626                    break;
13627                }
13628            }
13629        }
13630        let Some(next_diagnostic) = found else {
13631            return;
13632        };
13633
13634        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13635            return;
13636        };
13637        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13638            s.select_ranges(vec![
13639                next_diagnostic.range.start..next_diagnostic.range.start,
13640            ])
13641        });
13642        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13643        self.refresh_inline_completion(false, true, window, cx);
13644    }
13645
13646    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13647        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13648        let snapshot = self.snapshot(window, cx);
13649        let selection = self.selections.newest::<Point>(cx);
13650        self.go_to_hunk_before_or_after_position(
13651            &snapshot,
13652            selection.head(),
13653            Direction::Next,
13654            window,
13655            cx,
13656        );
13657    }
13658
13659    pub fn go_to_hunk_before_or_after_position(
13660        &mut self,
13661        snapshot: &EditorSnapshot,
13662        position: Point,
13663        direction: Direction,
13664        window: &mut Window,
13665        cx: &mut Context<Editor>,
13666    ) {
13667        let row = if direction == Direction::Next {
13668            self.hunk_after_position(snapshot, position)
13669                .map(|hunk| hunk.row_range.start)
13670        } else {
13671            self.hunk_before_position(snapshot, position)
13672        };
13673
13674        if let Some(row) = row {
13675            let destination = Point::new(row.0, 0);
13676            let autoscroll = Autoscroll::center();
13677
13678            self.unfold_ranges(&[destination..destination], false, false, cx);
13679            self.change_selections(Some(autoscroll), window, cx, |s| {
13680                s.select_ranges([destination..destination]);
13681            });
13682        }
13683    }
13684
13685    fn hunk_after_position(
13686        &mut self,
13687        snapshot: &EditorSnapshot,
13688        position: Point,
13689    ) -> Option<MultiBufferDiffHunk> {
13690        snapshot
13691            .buffer_snapshot
13692            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13693            .find(|hunk| hunk.row_range.start.0 > position.row)
13694            .or_else(|| {
13695                snapshot
13696                    .buffer_snapshot
13697                    .diff_hunks_in_range(Point::zero()..position)
13698                    .find(|hunk| hunk.row_range.end.0 < position.row)
13699            })
13700    }
13701
13702    fn go_to_prev_hunk(
13703        &mut self,
13704        _: &GoToPreviousHunk,
13705        window: &mut Window,
13706        cx: &mut Context<Self>,
13707    ) {
13708        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13709        let snapshot = self.snapshot(window, cx);
13710        let selection = self.selections.newest::<Point>(cx);
13711        self.go_to_hunk_before_or_after_position(
13712            &snapshot,
13713            selection.head(),
13714            Direction::Prev,
13715            window,
13716            cx,
13717        );
13718    }
13719
13720    fn hunk_before_position(
13721        &mut self,
13722        snapshot: &EditorSnapshot,
13723        position: Point,
13724    ) -> Option<MultiBufferRow> {
13725        snapshot
13726            .buffer_snapshot
13727            .diff_hunk_before(position)
13728            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13729    }
13730
13731    fn go_to_next_change(
13732        &mut self,
13733        _: &GoToNextChange,
13734        window: &mut Window,
13735        cx: &mut Context<Self>,
13736    ) {
13737        if let Some(selections) = self
13738            .change_list
13739            .next_change(1, Direction::Next)
13740            .map(|s| s.to_vec())
13741        {
13742            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13743                let map = s.display_map();
13744                s.select_display_ranges(selections.iter().map(|a| {
13745                    let point = a.to_display_point(&map);
13746                    point..point
13747                }))
13748            })
13749        }
13750    }
13751
13752    fn go_to_previous_change(
13753        &mut self,
13754        _: &GoToPreviousChange,
13755        window: &mut Window,
13756        cx: &mut Context<Self>,
13757    ) {
13758        if let Some(selections) = self
13759            .change_list
13760            .next_change(1, Direction::Prev)
13761            .map(|s| s.to_vec())
13762        {
13763            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13764                let map = s.display_map();
13765                s.select_display_ranges(selections.iter().map(|a| {
13766                    let point = a.to_display_point(&map);
13767                    point..point
13768                }))
13769            })
13770        }
13771    }
13772
13773    fn go_to_line<T: 'static>(
13774        &mut self,
13775        position: Anchor,
13776        highlight_color: Option<Hsla>,
13777        window: &mut Window,
13778        cx: &mut Context<Self>,
13779    ) {
13780        let snapshot = self.snapshot(window, cx).display_snapshot;
13781        let position = position.to_point(&snapshot.buffer_snapshot);
13782        let start = snapshot
13783            .buffer_snapshot
13784            .clip_point(Point::new(position.row, 0), Bias::Left);
13785        let end = start + Point::new(1, 0);
13786        let start = snapshot.buffer_snapshot.anchor_before(start);
13787        let end = snapshot.buffer_snapshot.anchor_before(end);
13788
13789        self.highlight_rows::<T>(
13790            start..end,
13791            highlight_color
13792                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13793            Default::default(),
13794            cx,
13795        );
13796        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13797    }
13798
13799    pub fn go_to_definition(
13800        &mut self,
13801        _: &GoToDefinition,
13802        window: &mut Window,
13803        cx: &mut Context<Self>,
13804    ) -> Task<Result<Navigated>> {
13805        let definition =
13806            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13807        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13808        cx.spawn_in(window, async move |editor, cx| {
13809            if definition.await? == Navigated::Yes {
13810                return Ok(Navigated::Yes);
13811            }
13812            match fallback_strategy {
13813                GoToDefinitionFallback::None => Ok(Navigated::No),
13814                GoToDefinitionFallback::FindAllReferences => {
13815                    match editor.update_in(cx, |editor, window, cx| {
13816                        editor.find_all_references(&FindAllReferences, window, cx)
13817                    })? {
13818                        Some(references) => references.await,
13819                        None => Ok(Navigated::No),
13820                    }
13821                }
13822            }
13823        })
13824    }
13825
13826    pub fn go_to_declaration(
13827        &mut self,
13828        _: &GoToDeclaration,
13829        window: &mut Window,
13830        cx: &mut Context<Self>,
13831    ) -> Task<Result<Navigated>> {
13832        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13833    }
13834
13835    pub fn go_to_declaration_split(
13836        &mut self,
13837        _: &GoToDeclaration,
13838        window: &mut Window,
13839        cx: &mut Context<Self>,
13840    ) -> Task<Result<Navigated>> {
13841        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13842    }
13843
13844    pub fn go_to_implementation(
13845        &mut self,
13846        _: &GoToImplementation,
13847        window: &mut Window,
13848        cx: &mut Context<Self>,
13849    ) -> Task<Result<Navigated>> {
13850        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13851    }
13852
13853    pub fn go_to_implementation_split(
13854        &mut self,
13855        _: &GoToImplementationSplit,
13856        window: &mut Window,
13857        cx: &mut Context<Self>,
13858    ) -> Task<Result<Navigated>> {
13859        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13860    }
13861
13862    pub fn go_to_type_definition(
13863        &mut self,
13864        _: &GoToTypeDefinition,
13865        window: &mut Window,
13866        cx: &mut Context<Self>,
13867    ) -> Task<Result<Navigated>> {
13868        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13869    }
13870
13871    pub fn go_to_definition_split(
13872        &mut self,
13873        _: &GoToDefinitionSplit,
13874        window: &mut Window,
13875        cx: &mut Context<Self>,
13876    ) -> Task<Result<Navigated>> {
13877        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13878    }
13879
13880    pub fn go_to_type_definition_split(
13881        &mut self,
13882        _: &GoToTypeDefinitionSplit,
13883        window: &mut Window,
13884        cx: &mut Context<Self>,
13885    ) -> Task<Result<Navigated>> {
13886        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13887    }
13888
13889    fn go_to_definition_of_kind(
13890        &mut self,
13891        kind: GotoDefinitionKind,
13892        split: bool,
13893        window: &mut Window,
13894        cx: &mut Context<Self>,
13895    ) -> Task<Result<Navigated>> {
13896        let Some(provider) = self.semantics_provider.clone() else {
13897            return Task::ready(Ok(Navigated::No));
13898        };
13899        let head = self.selections.newest::<usize>(cx).head();
13900        let buffer = self.buffer.read(cx);
13901        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13902            text_anchor
13903        } else {
13904            return Task::ready(Ok(Navigated::No));
13905        };
13906
13907        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13908            return Task::ready(Ok(Navigated::No));
13909        };
13910
13911        cx.spawn_in(window, async move |editor, cx| {
13912            let definitions = definitions.await?;
13913            let navigated = editor
13914                .update_in(cx, |editor, window, cx| {
13915                    editor.navigate_to_hover_links(
13916                        Some(kind),
13917                        definitions
13918                            .into_iter()
13919                            .filter(|location| {
13920                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13921                            })
13922                            .map(HoverLink::Text)
13923                            .collect::<Vec<_>>(),
13924                        split,
13925                        window,
13926                        cx,
13927                    )
13928                })?
13929                .await?;
13930            anyhow::Ok(navigated)
13931        })
13932    }
13933
13934    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13935        let selection = self.selections.newest_anchor();
13936        let head = selection.head();
13937        let tail = selection.tail();
13938
13939        let Some((buffer, start_position)) =
13940            self.buffer.read(cx).text_anchor_for_position(head, cx)
13941        else {
13942            return;
13943        };
13944
13945        let end_position = if head != tail {
13946            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13947                return;
13948            };
13949            Some(pos)
13950        } else {
13951            None
13952        };
13953
13954        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13955            let url = if let Some(end_pos) = end_position {
13956                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13957            } else {
13958                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13959            };
13960
13961            if let Some(url) = url {
13962                editor.update(cx, |_, cx| {
13963                    cx.open_url(&url);
13964                })
13965            } else {
13966                Ok(())
13967            }
13968        });
13969
13970        url_finder.detach();
13971    }
13972
13973    pub fn open_selected_filename(
13974        &mut self,
13975        _: &OpenSelectedFilename,
13976        window: &mut Window,
13977        cx: &mut Context<Self>,
13978    ) {
13979        let Some(workspace) = self.workspace() else {
13980            return;
13981        };
13982
13983        let position = self.selections.newest_anchor().head();
13984
13985        let Some((buffer, buffer_position)) =
13986            self.buffer.read(cx).text_anchor_for_position(position, cx)
13987        else {
13988            return;
13989        };
13990
13991        let project = self.project.clone();
13992
13993        cx.spawn_in(window, async move |_, cx| {
13994            let result = find_file(&buffer, project, buffer_position, cx).await;
13995
13996            if let Some((_, path)) = result {
13997                workspace
13998                    .update_in(cx, |workspace, window, cx| {
13999                        workspace.open_resolved_path(path, window, cx)
14000                    })?
14001                    .await?;
14002            }
14003            anyhow::Ok(())
14004        })
14005        .detach();
14006    }
14007
14008    pub(crate) fn navigate_to_hover_links(
14009        &mut self,
14010        kind: Option<GotoDefinitionKind>,
14011        mut definitions: Vec<HoverLink>,
14012        split: bool,
14013        window: &mut Window,
14014        cx: &mut Context<Editor>,
14015    ) -> Task<Result<Navigated>> {
14016        // If there is one definition, just open it directly
14017        if definitions.len() == 1 {
14018            let definition = definitions.pop().unwrap();
14019
14020            enum TargetTaskResult {
14021                Location(Option<Location>),
14022                AlreadyNavigated,
14023            }
14024
14025            let target_task = match definition {
14026                HoverLink::Text(link) => {
14027                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14028                }
14029                HoverLink::InlayHint(lsp_location, server_id) => {
14030                    let computation =
14031                        self.compute_target_location(lsp_location, server_id, window, cx);
14032                    cx.background_spawn(async move {
14033                        let location = computation.await?;
14034                        Ok(TargetTaskResult::Location(location))
14035                    })
14036                }
14037                HoverLink::Url(url) => {
14038                    cx.open_url(&url);
14039                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14040                }
14041                HoverLink::File(path) => {
14042                    if let Some(workspace) = self.workspace() {
14043                        cx.spawn_in(window, async move |_, cx| {
14044                            workspace
14045                                .update_in(cx, |workspace, window, cx| {
14046                                    workspace.open_resolved_path(path, window, cx)
14047                                })?
14048                                .await
14049                                .map(|_| TargetTaskResult::AlreadyNavigated)
14050                        })
14051                    } else {
14052                        Task::ready(Ok(TargetTaskResult::Location(None)))
14053                    }
14054                }
14055            };
14056            cx.spawn_in(window, async move |editor, cx| {
14057                let target = match target_task.await.context("target resolution task")? {
14058                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14059                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14060                    TargetTaskResult::Location(Some(target)) => target,
14061                };
14062
14063                editor.update_in(cx, |editor, window, cx| {
14064                    let Some(workspace) = editor.workspace() else {
14065                        return Navigated::No;
14066                    };
14067                    let pane = workspace.read(cx).active_pane().clone();
14068
14069                    let range = target.range.to_point(target.buffer.read(cx));
14070                    let range = editor.range_for_match(&range);
14071                    let range = collapse_multiline_range(range);
14072
14073                    if !split
14074                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14075                    {
14076                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14077                    } else {
14078                        window.defer(cx, move |window, cx| {
14079                            let target_editor: Entity<Self> =
14080                                workspace.update(cx, |workspace, cx| {
14081                                    let pane = if split {
14082                                        workspace.adjacent_pane(window, cx)
14083                                    } else {
14084                                        workspace.active_pane().clone()
14085                                    };
14086
14087                                    workspace.open_project_item(
14088                                        pane,
14089                                        target.buffer.clone(),
14090                                        true,
14091                                        true,
14092                                        window,
14093                                        cx,
14094                                    )
14095                                });
14096                            target_editor.update(cx, |target_editor, cx| {
14097                                // When selecting a definition in a different buffer, disable the nav history
14098                                // to avoid creating a history entry at the previous cursor location.
14099                                pane.update(cx, |pane, _| pane.disable_history());
14100                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14101                                pane.update(cx, |pane, _| pane.enable_history());
14102                            });
14103                        });
14104                    }
14105                    Navigated::Yes
14106                })
14107            })
14108        } else if !definitions.is_empty() {
14109            cx.spawn_in(window, async move |editor, cx| {
14110                let (title, location_tasks, workspace) = editor
14111                    .update_in(cx, |editor, window, cx| {
14112                        let tab_kind = match kind {
14113                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14114                            _ => "Definitions",
14115                        };
14116                        let title = definitions
14117                            .iter()
14118                            .find_map(|definition| match definition {
14119                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14120                                    let buffer = origin.buffer.read(cx);
14121                                    format!(
14122                                        "{} for {}",
14123                                        tab_kind,
14124                                        buffer
14125                                            .text_for_range(origin.range.clone())
14126                                            .collect::<String>()
14127                                    )
14128                                }),
14129                                HoverLink::InlayHint(_, _) => None,
14130                                HoverLink::Url(_) => None,
14131                                HoverLink::File(_) => None,
14132                            })
14133                            .unwrap_or(tab_kind.to_string());
14134                        let location_tasks = definitions
14135                            .into_iter()
14136                            .map(|definition| match definition {
14137                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14138                                HoverLink::InlayHint(lsp_location, server_id) => editor
14139                                    .compute_target_location(lsp_location, server_id, window, cx),
14140                                HoverLink::Url(_) => Task::ready(Ok(None)),
14141                                HoverLink::File(_) => Task::ready(Ok(None)),
14142                            })
14143                            .collect::<Vec<_>>();
14144                        (title, location_tasks, editor.workspace().clone())
14145                    })
14146                    .context("location tasks preparation")?;
14147
14148                let locations = future::join_all(location_tasks)
14149                    .await
14150                    .into_iter()
14151                    .filter_map(|location| location.transpose())
14152                    .collect::<Result<_>>()
14153                    .context("location tasks")?;
14154
14155                let Some(workspace) = workspace else {
14156                    return Ok(Navigated::No);
14157                };
14158                let opened = workspace
14159                    .update_in(cx, |workspace, window, cx| {
14160                        Self::open_locations_in_multibuffer(
14161                            workspace,
14162                            locations,
14163                            title,
14164                            split,
14165                            MultibufferSelectionMode::First,
14166                            window,
14167                            cx,
14168                        )
14169                    })
14170                    .ok();
14171
14172                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14173            })
14174        } else {
14175            Task::ready(Ok(Navigated::No))
14176        }
14177    }
14178
14179    fn compute_target_location(
14180        &self,
14181        lsp_location: lsp::Location,
14182        server_id: LanguageServerId,
14183        window: &mut Window,
14184        cx: &mut Context<Self>,
14185    ) -> Task<anyhow::Result<Option<Location>>> {
14186        let Some(project) = self.project.clone() else {
14187            return Task::ready(Ok(None));
14188        };
14189
14190        cx.spawn_in(window, async move |editor, cx| {
14191            let location_task = editor.update(cx, |_, cx| {
14192                project.update(cx, |project, cx| {
14193                    let language_server_name = project
14194                        .language_server_statuses(cx)
14195                        .find(|(id, _)| server_id == *id)
14196                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14197                    language_server_name.map(|language_server_name| {
14198                        project.open_local_buffer_via_lsp(
14199                            lsp_location.uri.clone(),
14200                            server_id,
14201                            language_server_name,
14202                            cx,
14203                        )
14204                    })
14205                })
14206            })?;
14207            let location = match location_task {
14208                Some(task) => Some({
14209                    let target_buffer_handle = task.await.context("open local buffer")?;
14210                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14211                        let target_start = target_buffer
14212                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14213                        let target_end = target_buffer
14214                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14215                        target_buffer.anchor_after(target_start)
14216                            ..target_buffer.anchor_before(target_end)
14217                    })?;
14218                    Location {
14219                        buffer: target_buffer_handle,
14220                        range,
14221                    }
14222                }),
14223                None => None,
14224            };
14225            Ok(location)
14226        })
14227    }
14228
14229    pub fn find_all_references(
14230        &mut self,
14231        _: &FindAllReferences,
14232        window: &mut Window,
14233        cx: &mut Context<Self>,
14234    ) -> Option<Task<Result<Navigated>>> {
14235        let selection = self.selections.newest::<usize>(cx);
14236        let multi_buffer = self.buffer.read(cx);
14237        let head = selection.head();
14238
14239        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14240        let head_anchor = multi_buffer_snapshot.anchor_at(
14241            head,
14242            if head < selection.tail() {
14243                Bias::Right
14244            } else {
14245                Bias::Left
14246            },
14247        );
14248
14249        match self
14250            .find_all_references_task_sources
14251            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14252        {
14253            Ok(_) => {
14254                log::info!(
14255                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14256                );
14257                return None;
14258            }
14259            Err(i) => {
14260                self.find_all_references_task_sources.insert(i, head_anchor);
14261            }
14262        }
14263
14264        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14265        let workspace = self.workspace()?;
14266        let project = workspace.read(cx).project().clone();
14267        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14268        Some(cx.spawn_in(window, async move |editor, cx| {
14269            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14270                if let Ok(i) = editor
14271                    .find_all_references_task_sources
14272                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14273                {
14274                    editor.find_all_references_task_sources.remove(i);
14275                }
14276            });
14277
14278            let locations = references.await?;
14279            if locations.is_empty() {
14280                return anyhow::Ok(Navigated::No);
14281            }
14282
14283            workspace.update_in(cx, |workspace, window, cx| {
14284                let title = locations
14285                    .first()
14286                    .as_ref()
14287                    .map(|location| {
14288                        let buffer = location.buffer.read(cx);
14289                        format!(
14290                            "References to `{}`",
14291                            buffer
14292                                .text_for_range(location.range.clone())
14293                                .collect::<String>()
14294                        )
14295                    })
14296                    .unwrap();
14297                Self::open_locations_in_multibuffer(
14298                    workspace,
14299                    locations,
14300                    title,
14301                    false,
14302                    MultibufferSelectionMode::First,
14303                    window,
14304                    cx,
14305                );
14306                Navigated::Yes
14307            })
14308        }))
14309    }
14310
14311    /// Opens a multibuffer with the given project locations in it
14312    pub fn open_locations_in_multibuffer(
14313        workspace: &mut Workspace,
14314        mut locations: Vec<Location>,
14315        title: String,
14316        split: bool,
14317        multibuffer_selection_mode: MultibufferSelectionMode,
14318        window: &mut Window,
14319        cx: &mut Context<Workspace>,
14320    ) {
14321        // If there are multiple definitions, open them in a multibuffer
14322        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14323        let mut locations = locations.into_iter().peekable();
14324        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14325        let capability = workspace.project().read(cx).capability();
14326
14327        let excerpt_buffer = cx.new(|cx| {
14328            let mut multibuffer = MultiBuffer::new(capability);
14329            while let Some(location) = locations.next() {
14330                let buffer = location.buffer.read(cx);
14331                let mut ranges_for_buffer = Vec::new();
14332                let range = location.range.to_point(buffer);
14333                ranges_for_buffer.push(range.clone());
14334
14335                while let Some(next_location) = locations.peek() {
14336                    if next_location.buffer == location.buffer {
14337                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14338                        locations.next();
14339                    } else {
14340                        break;
14341                    }
14342                }
14343
14344                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14345                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14346                    PathKey::for_buffer(&location.buffer, cx),
14347                    location.buffer.clone(),
14348                    ranges_for_buffer,
14349                    DEFAULT_MULTIBUFFER_CONTEXT,
14350                    cx,
14351                );
14352                ranges.extend(new_ranges)
14353            }
14354
14355            multibuffer.with_title(title)
14356        });
14357
14358        let editor = cx.new(|cx| {
14359            Editor::for_multibuffer(
14360                excerpt_buffer,
14361                Some(workspace.project().clone()),
14362                window,
14363                cx,
14364            )
14365        });
14366        editor.update(cx, |editor, cx| {
14367            match multibuffer_selection_mode {
14368                MultibufferSelectionMode::First => {
14369                    if let Some(first_range) = ranges.first() {
14370                        editor.change_selections(None, window, cx, |selections| {
14371                            selections.clear_disjoint();
14372                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14373                        });
14374                    }
14375                    editor.highlight_background::<Self>(
14376                        &ranges,
14377                        |theme| theme.editor_highlighted_line_background,
14378                        cx,
14379                    );
14380                }
14381                MultibufferSelectionMode::All => {
14382                    editor.change_selections(None, window, cx, |selections| {
14383                        selections.clear_disjoint();
14384                        selections.select_anchor_ranges(ranges);
14385                    });
14386                }
14387            }
14388            editor.register_buffers_with_language_servers(cx);
14389        });
14390
14391        let item = Box::new(editor);
14392        let item_id = item.item_id();
14393
14394        if split {
14395            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14396        } else {
14397            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14398                let (preview_item_id, preview_item_idx) =
14399                    workspace.active_pane().update(cx, |pane, _| {
14400                        (pane.preview_item_id(), pane.preview_item_idx())
14401                    });
14402
14403                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14404
14405                if let Some(preview_item_id) = preview_item_id {
14406                    workspace.active_pane().update(cx, |pane, cx| {
14407                        pane.remove_item(preview_item_id, false, false, window, cx);
14408                    });
14409                }
14410            } else {
14411                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14412            }
14413        }
14414        workspace.active_pane().update(cx, |pane, cx| {
14415            pane.set_preview_item_id(Some(item_id), cx);
14416        });
14417    }
14418
14419    pub fn rename(
14420        &mut self,
14421        _: &Rename,
14422        window: &mut Window,
14423        cx: &mut Context<Self>,
14424    ) -> Option<Task<Result<()>>> {
14425        use language::ToOffset as _;
14426
14427        let provider = self.semantics_provider.clone()?;
14428        let selection = self.selections.newest_anchor().clone();
14429        let (cursor_buffer, cursor_buffer_position) = self
14430            .buffer
14431            .read(cx)
14432            .text_anchor_for_position(selection.head(), cx)?;
14433        let (tail_buffer, cursor_buffer_position_end) = self
14434            .buffer
14435            .read(cx)
14436            .text_anchor_for_position(selection.tail(), cx)?;
14437        if tail_buffer != cursor_buffer {
14438            return None;
14439        }
14440
14441        let snapshot = cursor_buffer.read(cx).snapshot();
14442        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14443        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14444        let prepare_rename = provider
14445            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14446            .unwrap_or_else(|| Task::ready(Ok(None)));
14447        drop(snapshot);
14448
14449        Some(cx.spawn_in(window, async move |this, cx| {
14450            let rename_range = if let Some(range) = prepare_rename.await? {
14451                Some(range)
14452            } else {
14453                this.update(cx, |this, cx| {
14454                    let buffer = this.buffer.read(cx).snapshot(cx);
14455                    let mut buffer_highlights = this
14456                        .document_highlights_for_position(selection.head(), &buffer)
14457                        .filter(|highlight| {
14458                            highlight.start.excerpt_id == selection.head().excerpt_id
14459                                && highlight.end.excerpt_id == selection.head().excerpt_id
14460                        });
14461                    buffer_highlights
14462                        .next()
14463                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14464                })?
14465            };
14466            if let Some(rename_range) = rename_range {
14467                this.update_in(cx, |this, window, cx| {
14468                    let snapshot = cursor_buffer.read(cx).snapshot();
14469                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14470                    let cursor_offset_in_rename_range =
14471                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14472                    let cursor_offset_in_rename_range_end =
14473                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14474
14475                    this.take_rename(false, window, cx);
14476                    let buffer = this.buffer.read(cx).read(cx);
14477                    let cursor_offset = selection.head().to_offset(&buffer);
14478                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14479                    let rename_end = rename_start + rename_buffer_range.len();
14480                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14481                    let mut old_highlight_id = None;
14482                    let old_name: Arc<str> = buffer
14483                        .chunks(rename_start..rename_end, true)
14484                        .map(|chunk| {
14485                            if old_highlight_id.is_none() {
14486                                old_highlight_id = chunk.syntax_highlight_id;
14487                            }
14488                            chunk.text
14489                        })
14490                        .collect::<String>()
14491                        .into();
14492
14493                    drop(buffer);
14494
14495                    // Position the selection in the rename editor so that it matches the current selection.
14496                    this.show_local_selections = false;
14497                    let rename_editor = cx.new(|cx| {
14498                        let mut editor = Editor::single_line(window, cx);
14499                        editor.buffer.update(cx, |buffer, cx| {
14500                            buffer.edit([(0..0, old_name.clone())], None, cx)
14501                        });
14502                        let rename_selection_range = match cursor_offset_in_rename_range
14503                            .cmp(&cursor_offset_in_rename_range_end)
14504                        {
14505                            Ordering::Equal => {
14506                                editor.select_all(&SelectAll, window, cx);
14507                                return editor;
14508                            }
14509                            Ordering::Less => {
14510                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14511                            }
14512                            Ordering::Greater => {
14513                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14514                            }
14515                        };
14516                        if rename_selection_range.end > old_name.len() {
14517                            editor.select_all(&SelectAll, window, cx);
14518                        } else {
14519                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14520                                s.select_ranges([rename_selection_range]);
14521                            });
14522                        }
14523                        editor
14524                    });
14525                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14526                        if e == &EditorEvent::Focused {
14527                            cx.emit(EditorEvent::FocusedIn)
14528                        }
14529                    })
14530                    .detach();
14531
14532                    let write_highlights =
14533                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14534                    let read_highlights =
14535                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14536                    let ranges = write_highlights
14537                        .iter()
14538                        .flat_map(|(_, ranges)| ranges.iter())
14539                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14540                        .cloned()
14541                        .collect();
14542
14543                    this.highlight_text::<Rename>(
14544                        ranges,
14545                        HighlightStyle {
14546                            fade_out: Some(0.6),
14547                            ..Default::default()
14548                        },
14549                        cx,
14550                    );
14551                    let rename_focus_handle = rename_editor.focus_handle(cx);
14552                    window.focus(&rename_focus_handle);
14553                    let block_id = this.insert_blocks(
14554                        [BlockProperties {
14555                            style: BlockStyle::Flex,
14556                            placement: BlockPlacement::Below(range.start),
14557                            height: Some(1),
14558                            render: Arc::new({
14559                                let rename_editor = rename_editor.clone();
14560                                move |cx: &mut BlockContext| {
14561                                    let mut text_style = cx.editor_style.text.clone();
14562                                    if let Some(highlight_style) = old_highlight_id
14563                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14564                                    {
14565                                        text_style = text_style.highlight(highlight_style);
14566                                    }
14567                                    div()
14568                                        .block_mouse_down()
14569                                        .pl(cx.anchor_x)
14570                                        .child(EditorElement::new(
14571                                            &rename_editor,
14572                                            EditorStyle {
14573                                                background: cx.theme().system().transparent,
14574                                                local_player: cx.editor_style.local_player,
14575                                                text: text_style,
14576                                                scrollbar_width: cx.editor_style.scrollbar_width,
14577                                                syntax: cx.editor_style.syntax.clone(),
14578                                                status: cx.editor_style.status.clone(),
14579                                                inlay_hints_style: HighlightStyle {
14580                                                    font_weight: Some(FontWeight::BOLD),
14581                                                    ..make_inlay_hints_style(cx.app)
14582                                                },
14583                                                inline_completion_styles: make_suggestion_styles(
14584                                                    cx.app,
14585                                                ),
14586                                                ..EditorStyle::default()
14587                                            },
14588                                        ))
14589                                        .into_any_element()
14590                                }
14591                            }),
14592                            priority: 0,
14593                        }],
14594                        Some(Autoscroll::fit()),
14595                        cx,
14596                    )[0];
14597                    this.pending_rename = Some(RenameState {
14598                        range,
14599                        old_name,
14600                        editor: rename_editor,
14601                        block_id,
14602                    });
14603                })?;
14604            }
14605
14606            Ok(())
14607        }))
14608    }
14609
14610    pub fn confirm_rename(
14611        &mut self,
14612        _: &ConfirmRename,
14613        window: &mut Window,
14614        cx: &mut Context<Self>,
14615    ) -> Option<Task<Result<()>>> {
14616        let rename = self.take_rename(false, window, cx)?;
14617        let workspace = self.workspace()?.downgrade();
14618        let (buffer, start) = self
14619            .buffer
14620            .read(cx)
14621            .text_anchor_for_position(rename.range.start, cx)?;
14622        let (end_buffer, _) = self
14623            .buffer
14624            .read(cx)
14625            .text_anchor_for_position(rename.range.end, cx)?;
14626        if buffer != end_buffer {
14627            return None;
14628        }
14629
14630        let old_name = rename.old_name;
14631        let new_name = rename.editor.read(cx).text(cx);
14632
14633        let rename = self.semantics_provider.as_ref()?.perform_rename(
14634            &buffer,
14635            start,
14636            new_name.clone(),
14637            cx,
14638        )?;
14639
14640        Some(cx.spawn_in(window, async move |editor, cx| {
14641            let project_transaction = rename.await?;
14642            Self::open_project_transaction(
14643                &editor,
14644                workspace,
14645                project_transaction,
14646                format!("Rename: {}{}", old_name, new_name),
14647                cx,
14648            )
14649            .await?;
14650
14651            editor.update(cx, |editor, cx| {
14652                editor.refresh_document_highlights(cx);
14653            })?;
14654            Ok(())
14655        }))
14656    }
14657
14658    fn take_rename(
14659        &mut self,
14660        moving_cursor: bool,
14661        window: &mut Window,
14662        cx: &mut Context<Self>,
14663    ) -> Option<RenameState> {
14664        let rename = self.pending_rename.take()?;
14665        if rename.editor.focus_handle(cx).is_focused(window) {
14666            window.focus(&self.focus_handle);
14667        }
14668
14669        self.remove_blocks(
14670            [rename.block_id].into_iter().collect(),
14671            Some(Autoscroll::fit()),
14672            cx,
14673        );
14674        self.clear_highlights::<Rename>(cx);
14675        self.show_local_selections = true;
14676
14677        if moving_cursor {
14678            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14679                editor.selections.newest::<usize>(cx).head()
14680            });
14681
14682            // Update the selection to match the position of the selection inside
14683            // the rename editor.
14684            let snapshot = self.buffer.read(cx).read(cx);
14685            let rename_range = rename.range.to_offset(&snapshot);
14686            let cursor_in_editor = snapshot
14687                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14688                .min(rename_range.end);
14689            drop(snapshot);
14690
14691            self.change_selections(None, window, cx, |s| {
14692                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14693            });
14694        } else {
14695            self.refresh_document_highlights(cx);
14696        }
14697
14698        Some(rename)
14699    }
14700
14701    pub fn pending_rename(&self) -> Option<&RenameState> {
14702        self.pending_rename.as_ref()
14703    }
14704
14705    fn format(
14706        &mut self,
14707        _: &Format,
14708        window: &mut Window,
14709        cx: &mut Context<Self>,
14710    ) -> Option<Task<Result<()>>> {
14711        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14712
14713        let project = match &self.project {
14714            Some(project) => project.clone(),
14715            None => return None,
14716        };
14717
14718        Some(self.perform_format(
14719            project,
14720            FormatTrigger::Manual,
14721            FormatTarget::Buffers,
14722            window,
14723            cx,
14724        ))
14725    }
14726
14727    fn format_selections(
14728        &mut self,
14729        _: &FormatSelections,
14730        window: &mut Window,
14731        cx: &mut Context<Self>,
14732    ) -> Option<Task<Result<()>>> {
14733        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14734
14735        let project = match &self.project {
14736            Some(project) => project.clone(),
14737            None => return None,
14738        };
14739
14740        let ranges = self
14741            .selections
14742            .all_adjusted(cx)
14743            .into_iter()
14744            .map(|selection| selection.range())
14745            .collect_vec();
14746
14747        Some(self.perform_format(
14748            project,
14749            FormatTrigger::Manual,
14750            FormatTarget::Ranges(ranges),
14751            window,
14752            cx,
14753        ))
14754    }
14755
14756    fn perform_format(
14757        &mut self,
14758        project: Entity<Project>,
14759        trigger: FormatTrigger,
14760        target: FormatTarget,
14761        window: &mut Window,
14762        cx: &mut Context<Self>,
14763    ) -> Task<Result<()>> {
14764        let buffer = self.buffer.clone();
14765        let (buffers, target) = match target {
14766            FormatTarget::Buffers => {
14767                let mut buffers = buffer.read(cx).all_buffers();
14768                if trigger == FormatTrigger::Save {
14769                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14770                }
14771                (buffers, LspFormatTarget::Buffers)
14772            }
14773            FormatTarget::Ranges(selection_ranges) => {
14774                let multi_buffer = buffer.read(cx);
14775                let snapshot = multi_buffer.read(cx);
14776                let mut buffers = HashSet::default();
14777                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14778                    BTreeMap::new();
14779                for selection_range in selection_ranges {
14780                    for (buffer, buffer_range, _) in
14781                        snapshot.range_to_buffer_ranges(selection_range)
14782                    {
14783                        let buffer_id = buffer.remote_id();
14784                        let start = buffer.anchor_before(buffer_range.start);
14785                        let end = buffer.anchor_after(buffer_range.end);
14786                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14787                        buffer_id_to_ranges
14788                            .entry(buffer_id)
14789                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14790                            .or_insert_with(|| vec![start..end]);
14791                    }
14792                }
14793                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14794            }
14795        };
14796
14797        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14798        let selections_prev = transaction_id_prev
14799            .and_then(|transaction_id_prev| {
14800                // default to selections as they were after the last edit, if we have them,
14801                // instead of how they are now.
14802                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14803                // will take you back to where you made the last edit, instead of staying where you scrolled
14804                self.selection_history
14805                    .transaction(transaction_id_prev)
14806                    .map(|t| t.0.clone())
14807            })
14808            .unwrap_or_else(|| {
14809                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14810                self.selections.disjoint_anchors()
14811            });
14812
14813        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14814        let format = project.update(cx, |project, cx| {
14815            project.format(buffers, target, true, trigger, cx)
14816        });
14817
14818        cx.spawn_in(window, async move |editor, cx| {
14819            let transaction = futures::select_biased! {
14820                transaction = format.log_err().fuse() => transaction,
14821                () = timeout => {
14822                    log::warn!("timed out waiting for formatting");
14823                    None
14824                }
14825            };
14826
14827            buffer
14828                .update(cx, |buffer, cx| {
14829                    if let Some(transaction) = transaction {
14830                        if !buffer.is_singleton() {
14831                            buffer.push_transaction(&transaction.0, cx);
14832                        }
14833                    }
14834                    cx.notify();
14835                })
14836                .ok();
14837
14838            if let Some(transaction_id_now) =
14839                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14840            {
14841                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14842                if has_new_transaction {
14843                    _ = editor.update(cx, |editor, _| {
14844                        editor
14845                            .selection_history
14846                            .insert_transaction(transaction_id_now, selections_prev);
14847                    });
14848                }
14849            }
14850
14851            Ok(())
14852        })
14853    }
14854
14855    fn organize_imports(
14856        &mut self,
14857        _: &OrganizeImports,
14858        window: &mut Window,
14859        cx: &mut Context<Self>,
14860    ) -> Option<Task<Result<()>>> {
14861        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14862        let project = match &self.project {
14863            Some(project) => project.clone(),
14864            None => return None,
14865        };
14866        Some(self.perform_code_action_kind(
14867            project,
14868            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14869            window,
14870            cx,
14871        ))
14872    }
14873
14874    fn perform_code_action_kind(
14875        &mut self,
14876        project: Entity<Project>,
14877        kind: CodeActionKind,
14878        window: &mut Window,
14879        cx: &mut Context<Self>,
14880    ) -> Task<Result<()>> {
14881        let buffer = self.buffer.clone();
14882        let buffers = buffer.read(cx).all_buffers();
14883        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14884        let apply_action = project.update(cx, |project, cx| {
14885            project.apply_code_action_kind(buffers, kind, true, cx)
14886        });
14887        cx.spawn_in(window, async move |_, cx| {
14888            let transaction = futures::select_biased! {
14889                () = timeout => {
14890                    log::warn!("timed out waiting for executing code action");
14891                    None
14892                }
14893                transaction = apply_action.log_err().fuse() => transaction,
14894            };
14895            buffer
14896                .update(cx, |buffer, cx| {
14897                    // check if we need this
14898                    if let Some(transaction) = transaction {
14899                        if !buffer.is_singleton() {
14900                            buffer.push_transaction(&transaction.0, cx);
14901                        }
14902                    }
14903                    cx.notify();
14904                })
14905                .ok();
14906            Ok(())
14907        })
14908    }
14909
14910    fn restart_language_server(
14911        &mut self,
14912        _: &RestartLanguageServer,
14913        _: &mut Window,
14914        cx: &mut Context<Self>,
14915    ) {
14916        if let Some(project) = self.project.clone() {
14917            self.buffer.update(cx, |multi_buffer, cx| {
14918                project.update(cx, |project, cx| {
14919                    project.restart_language_servers_for_buffers(
14920                        multi_buffer.all_buffers().into_iter().collect(),
14921                        cx,
14922                    );
14923                });
14924            })
14925        }
14926    }
14927
14928    fn stop_language_server(
14929        &mut self,
14930        _: &StopLanguageServer,
14931        _: &mut Window,
14932        cx: &mut Context<Self>,
14933    ) {
14934        if let Some(project) = self.project.clone() {
14935            self.buffer.update(cx, |multi_buffer, cx| {
14936                project.update(cx, |project, cx| {
14937                    project.stop_language_servers_for_buffers(
14938                        multi_buffer.all_buffers().into_iter().collect(),
14939                        cx,
14940                    );
14941                    cx.emit(project::Event::RefreshInlayHints);
14942                });
14943            });
14944        }
14945    }
14946
14947    fn cancel_language_server_work(
14948        workspace: &mut Workspace,
14949        _: &actions::CancelLanguageServerWork,
14950        _: &mut Window,
14951        cx: &mut Context<Workspace>,
14952    ) {
14953        let project = workspace.project();
14954        let buffers = workspace
14955            .active_item(cx)
14956            .and_then(|item| item.act_as::<Editor>(cx))
14957            .map_or(HashSet::default(), |editor| {
14958                editor.read(cx).buffer.read(cx).all_buffers()
14959            });
14960        project.update(cx, |project, cx| {
14961            project.cancel_language_server_work_for_buffers(buffers, cx);
14962        });
14963    }
14964
14965    fn show_character_palette(
14966        &mut self,
14967        _: &ShowCharacterPalette,
14968        window: &mut Window,
14969        _: &mut Context<Self>,
14970    ) {
14971        window.show_character_palette();
14972    }
14973
14974    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14975        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14976            let buffer = self.buffer.read(cx).snapshot(cx);
14977            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14978            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14979            let is_valid = buffer
14980                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14981                .any(|entry| {
14982                    entry.diagnostic.is_primary
14983                        && !entry.range.is_empty()
14984                        && entry.range.start == primary_range_start
14985                        && entry.diagnostic.message == active_diagnostics.active_message
14986                });
14987
14988            if !is_valid {
14989                self.dismiss_diagnostics(cx);
14990            }
14991        }
14992    }
14993
14994    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14995        match &self.active_diagnostics {
14996            ActiveDiagnostic::Group(group) => Some(group),
14997            _ => None,
14998        }
14999    }
15000
15001    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15002        self.dismiss_diagnostics(cx);
15003        self.active_diagnostics = ActiveDiagnostic::All;
15004    }
15005
15006    fn activate_diagnostics(
15007        &mut self,
15008        buffer_id: BufferId,
15009        diagnostic: DiagnosticEntry<usize>,
15010        window: &mut Window,
15011        cx: &mut Context<Self>,
15012    ) {
15013        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15014            return;
15015        }
15016        self.dismiss_diagnostics(cx);
15017        let snapshot = self.snapshot(window, cx);
15018        let buffer = self.buffer.read(cx).snapshot(cx);
15019        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15020            return;
15021        };
15022
15023        let diagnostic_group = buffer
15024            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15025            .collect::<Vec<_>>();
15026
15027        let blocks =
15028            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15029
15030        let blocks = self.display_map.update(cx, |display_map, cx| {
15031            display_map.insert_blocks(blocks, cx).into_iter().collect()
15032        });
15033        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15034            active_range: buffer.anchor_before(diagnostic.range.start)
15035                ..buffer.anchor_after(diagnostic.range.end),
15036            active_message: diagnostic.diagnostic.message.clone(),
15037            group_id: diagnostic.diagnostic.group_id,
15038            blocks,
15039        });
15040        cx.notify();
15041    }
15042
15043    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15044        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15045            return;
15046        };
15047
15048        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15049        if let ActiveDiagnostic::Group(group) = prev {
15050            self.display_map.update(cx, |display_map, cx| {
15051                display_map.remove_blocks(group.blocks, cx);
15052            });
15053            cx.notify();
15054        }
15055    }
15056
15057    /// Disable inline diagnostics rendering for this editor.
15058    pub fn disable_inline_diagnostics(&mut self) {
15059        self.inline_diagnostics_enabled = false;
15060        self.inline_diagnostics_update = Task::ready(());
15061        self.inline_diagnostics.clear();
15062    }
15063
15064    pub fn inline_diagnostics_enabled(&self) -> bool {
15065        self.inline_diagnostics_enabled
15066    }
15067
15068    pub fn show_inline_diagnostics(&self) -> bool {
15069        self.show_inline_diagnostics
15070    }
15071
15072    pub fn toggle_inline_diagnostics(
15073        &mut self,
15074        _: &ToggleInlineDiagnostics,
15075        window: &mut Window,
15076        cx: &mut Context<Editor>,
15077    ) {
15078        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15079        self.refresh_inline_diagnostics(false, window, cx);
15080    }
15081
15082    fn refresh_inline_diagnostics(
15083        &mut self,
15084        debounce: bool,
15085        window: &mut Window,
15086        cx: &mut Context<Self>,
15087    ) {
15088        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15089            self.inline_diagnostics_update = Task::ready(());
15090            self.inline_diagnostics.clear();
15091            return;
15092        }
15093
15094        let debounce_ms = ProjectSettings::get_global(cx)
15095            .diagnostics
15096            .inline
15097            .update_debounce_ms;
15098        let debounce = if debounce && debounce_ms > 0 {
15099            Some(Duration::from_millis(debounce_ms))
15100        } else {
15101            None
15102        };
15103        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15104            let editor = editor.upgrade().unwrap();
15105
15106            if let Some(debounce) = debounce {
15107                cx.background_executor().timer(debounce).await;
15108            }
15109            let Some(snapshot) = editor
15110                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15111                .ok()
15112            else {
15113                return;
15114            };
15115
15116            let new_inline_diagnostics = cx
15117                .background_spawn(async move {
15118                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15119                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15120                        let message = diagnostic_entry
15121                            .diagnostic
15122                            .message
15123                            .split_once('\n')
15124                            .map(|(line, _)| line)
15125                            .map(SharedString::new)
15126                            .unwrap_or_else(|| {
15127                                SharedString::from(diagnostic_entry.diagnostic.message)
15128                            });
15129                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15130                        let (Ok(i) | Err(i)) = inline_diagnostics
15131                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15132                        inline_diagnostics.insert(
15133                            i,
15134                            (
15135                                start_anchor,
15136                                InlineDiagnostic {
15137                                    message,
15138                                    group_id: diagnostic_entry.diagnostic.group_id,
15139                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15140                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15141                                    severity: diagnostic_entry.diagnostic.severity,
15142                                },
15143                            ),
15144                        );
15145                    }
15146                    inline_diagnostics
15147                })
15148                .await;
15149
15150            editor
15151                .update(cx, |editor, cx| {
15152                    editor.inline_diagnostics = new_inline_diagnostics;
15153                    cx.notify();
15154                })
15155                .ok();
15156        });
15157    }
15158
15159    pub fn set_selections_from_remote(
15160        &mut self,
15161        selections: Vec<Selection<Anchor>>,
15162        pending_selection: Option<Selection<Anchor>>,
15163        window: &mut Window,
15164        cx: &mut Context<Self>,
15165    ) {
15166        let old_cursor_position = self.selections.newest_anchor().head();
15167        self.selections.change_with(cx, |s| {
15168            s.select_anchors(selections);
15169            if let Some(pending_selection) = pending_selection {
15170                s.set_pending(pending_selection, SelectMode::Character);
15171            } else {
15172                s.clear_pending();
15173            }
15174        });
15175        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15176    }
15177
15178    fn push_to_selection_history(&mut self) {
15179        self.selection_history.push(SelectionHistoryEntry {
15180            selections: self.selections.disjoint_anchors(),
15181            select_next_state: self.select_next_state.clone(),
15182            select_prev_state: self.select_prev_state.clone(),
15183            add_selections_state: self.add_selections_state.clone(),
15184        });
15185    }
15186
15187    pub fn transact(
15188        &mut self,
15189        window: &mut Window,
15190        cx: &mut Context<Self>,
15191        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15192    ) -> Option<TransactionId> {
15193        self.start_transaction_at(Instant::now(), window, cx);
15194        update(self, window, cx);
15195        self.end_transaction_at(Instant::now(), cx)
15196    }
15197
15198    pub fn start_transaction_at(
15199        &mut self,
15200        now: Instant,
15201        window: &mut Window,
15202        cx: &mut Context<Self>,
15203    ) {
15204        self.end_selection(window, cx);
15205        if let Some(tx_id) = self
15206            .buffer
15207            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15208        {
15209            self.selection_history
15210                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15211            cx.emit(EditorEvent::TransactionBegun {
15212                transaction_id: tx_id,
15213            })
15214        }
15215    }
15216
15217    pub fn end_transaction_at(
15218        &mut self,
15219        now: Instant,
15220        cx: &mut Context<Self>,
15221    ) -> Option<TransactionId> {
15222        if let Some(transaction_id) = self
15223            .buffer
15224            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15225        {
15226            if let Some((_, end_selections)) =
15227                self.selection_history.transaction_mut(transaction_id)
15228            {
15229                *end_selections = Some(self.selections.disjoint_anchors());
15230            } else {
15231                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15232            }
15233
15234            cx.emit(EditorEvent::Edited { transaction_id });
15235            Some(transaction_id)
15236        } else {
15237            None
15238        }
15239    }
15240
15241    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15242        if self.selection_mark_mode {
15243            self.change_selections(None, window, cx, |s| {
15244                s.move_with(|_, sel| {
15245                    sel.collapse_to(sel.head(), SelectionGoal::None);
15246                });
15247            })
15248        }
15249        self.selection_mark_mode = true;
15250        cx.notify();
15251    }
15252
15253    pub fn swap_selection_ends(
15254        &mut self,
15255        _: &actions::SwapSelectionEnds,
15256        window: &mut Window,
15257        cx: &mut Context<Self>,
15258    ) {
15259        self.change_selections(None, window, cx, |s| {
15260            s.move_with(|_, sel| {
15261                if sel.start != sel.end {
15262                    sel.reversed = !sel.reversed
15263                }
15264            });
15265        });
15266        self.request_autoscroll(Autoscroll::newest(), cx);
15267        cx.notify();
15268    }
15269
15270    pub fn toggle_fold(
15271        &mut self,
15272        _: &actions::ToggleFold,
15273        window: &mut Window,
15274        cx: &mut Context<Self>,
15275    ) {
15276        if self.is_singleton(cx) {
15277            let selection = self.selections.newest::<Point>(cx);
15278
15279            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15280            let range = if selection.is_empty() {
15281                let point = selection.head().to_display_point(&display_map);
15282                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15283                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15284                    .to_point(&display_map);
15285                start..end
15286            } else {
15287                selection.range()
15288            };
15289            if display_map.folds_in_range(range).next().is_some() {
15290                self.unfold_lines(&Default::default(), window, cx)
15291            } else {
15292                self.fold(&Default::default(), window, cx)
15293            }
15294        } else {
15295            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15296            let buffer_ids: HashSet<_> = self
15297                .selections
15298                .disjoint_anchor_ranges()
15299                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15300                .collect();
15301
15302            let should_unfold = buffer_ids
15303                .iter()
15304                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15305
15306            for buffer_id in buffer_ids {
15307                if should_unfold {
15308                    self.unfold_buffer(buffer_id, cx);
15309                } else {
15310                    self.fold_buffer(buffer_id, cx);
15311                }
15312            }
15313        }
15314    }
15315
15316    pub fn toggle_fold_recursive(
15317        &mut self,
15318        _: &actions::ToggleFoldRecursive,
15319        window: &mut Window,
15320        cx: &mut Context<Self>,
15321    ) {
15322        let selection = self.selections.newest::<Point>(cx);
15323
15324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15325        let range = if selection.is_empty() {
15326            let point = selection.head().to_display_point(&display_map);
15327            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15328            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15329                .to_point(&display_map);
15330            start..end
15331        } else {
15332            selection.range()
15333        };
15334        if display_map.folds_in_range(range).next().is_some() {
15335            self.unfold_recursive(&Default::default(), window, cx)
15336        } else {
15337            self.fold_recursive(&Default::default(), window, cx)
15338        }
15339    }
15340
15341    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15342        if self.is_singleton(cx) {
15343            let mut to_fold = Vec::new();
15344            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15345            let selections = self.selections.all_adjusted(cx);
15346
15347            for selection in selections {
15348                let range = selection.range().sorted();
15349                let buffer_start_row = range.start.row;
15350
15351                if range.start.row != range.end.row {
15352                    let mut found = false;
15353                    let mut row = range.start.row;
15354                    while row <= range.end.row {
15355                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15356                        {
15357                            found = true;
15358                            row = crease.range().end.row + 1;
15359                            to_fold.push(crease);
15360                        } else {
15361                            row += 1
15362                        }
15363                    }
15364                    if found {
15365                        continue;
15366                    }
15367                }
15368
15369                for row in (0..=range.start.row).rev() {
15370                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15371                        if crease.range().end.row >= buffer_start_row {
15372                            to_fold.push(crease);
15373                            if row <= range.start.row {
15374                                break;
15375                            }
15376                        }
15377                    }
15378                }
15379            }
15380
15381            self.fold_creases(to_fold, true, window, cx);
15382        } else {
15383            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15384            let buffer_ids = self
15385                .selections
15386                .disjoint_anchor_ranges()
15387                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15388                .collect::<HashSet<_>>();
15389            for buffer_id in buffer_ids {
15390                self.fold_buffer(buffer_id, cx);
15391            }
15392        }
15393    }
15394
15395    fn fold_at_level(
15396        &mut self,
15397        fold_at: &FoldAtLevel,
15398        window: &mut Window,
15399        cx: &mut Context<Self>,
15400    ) {
15401        if !self.buffer.read(cx).is_singleton() {
15402            return;
15403        }
15404
15405        let fold_at_level = fold_at.0;
15406        let snapshot = self.buffer.read(cx).snapshot(cx);
15407        let mut to_fold = Vec::new();
15408        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15409
15410        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15411            while start_row < end_row {
15412                match self
15413                    .snapshot(window, cx)
15414                    .crease_for_buffer_row(MultiBufferRow(start_row))
15415                {
15416                    Some(crease) => {
15417                        let nested_start_row = crease.range().start.row + 1;
15418                        let nested_end_row = crease.range().end.row;
15419
15420                        if current_level < fold_at_level {
15421                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15422                        } else if current_level == fold_at_level {
15423                            to_fold.push(crease);
15424                        }
15425
15426                        start_row = nested_end_row + 1;
15427                    }
15428                    None => start_row += 1,
15429                }
15430            }
15431        }
15432
15433        self.fold_creases(to_fold, true, window, cx);
15434    }
15435
15436    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15437        if self.buffer.read(cx).is_singleton() {
15438            let mut fold_ranges = Vec::new();
15439            let snapshot = self.buffer.read(cx).snapshot(cx);
15440
15441            for row in 0..snapshot.max_row().0 {
15442                if let Some(foldable_range) = self
15443                    .snapshot(window, cx)
15444                    .crease_for_buffer_row(MultiBufferRow(row))
15445                {
15446                    fold_ranges.push(foldable_range);
15447                }
15448            }
15449
15450            self.fold_creases(fold_ranges, true, window, cx);
15451        } else {
15452            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15453                editor
15454                    .update_in(cx, |editor, _, cx| {
15455                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15456                            editor.fold_buffer(buffer_id, cx);
15457                        }
15458                    })
15459                    .ok();
15460            });
15461        }
15462    }
15463
15464    pub fn fold_function_bodies(
15465        &mut self,
15466        _: &actions::FoldFunctionBodies,
15467        window: &mut Window,
15468        cx: &mut Context<Self>,
15469    ) {
15470        let snapshot = self.buffer.read(cx).snapshot(cx);
15471
15472        let ranges = snapshot
15473            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15474            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15475            .collect::<Vec<_>>();
15476
15477        let creases = ranges
15478            .into_iter()
15479            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15480            .collect();
15481
15482        self.fold_creases(creases, true, window, cx);
15483    }
15484
15485    pub fn fold_recursive(
15486        &mut self,
15487        _: &actions::FoldRecursive,
15488        window: &mut Window,
15489        cx: &mut Context<Self>,
15490    ) {
15491        let mut to_fold = Vec::new();
15492        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15493        let selections = self.selections.all_adjusted(cx);
15494
15495        for selection in selections {
15496            let range = selection.range().sorted();
15497            let buffer_start_row = range.start.row;
15498
15499            if range.start.row != range.end.row {
15500                let mut found = false;
15501                for row in range.start.row..=range.end.row {
15502                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15503                        found = true;
15504                        to_fold.push(crease);
15505                    }
15506                }
15507                if found {
15508                    continue;
15509                }
15510            }
15511
15512            for row in (0..=range.start.row).rev() {
15513                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15514                    if crease.range().end.row >= buffer_start_row {
15515                        to_fold.push(crease);
15516                    } else {
15517                        break;
15518                    }
15519                }
15520            }
15521        }
15522
15523        self.fold_creases(to_fold, true, window, cx);
15524    }
15525
15526    pub fn fold_at(
15527        &mut self,
15528        buffer_row: MultiBufferRow,
15529        window: &mut Window,
15530        cx: &mut Context<Self>,
15531    ) {
15532        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15533
15534        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15535            let autoscroll = self
15536                .selections
15537                .all::<Point>(cx)
15538                .iter()
15539                .any(|selection| crease.range().overlaps(&selection.range()));
15540
15541            self.fold_creases(vec![crease], autoscroll, window, cx);
15542        }
15543    }
15544
15545    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15546        if self.is_singleton(cx) {
15547            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15548            let buffer = &display_map.buffer_snapshot;
15549            let selections = self.selections.all::<Point>(cx);
15550            let ranges = selections
15551                .iter()
15552                .map(|s| {
15553                    let range = s.display_range(&display_map).sorted();
15554                    let mut start = range.start.to_point(&display_map);
15555                    let mut end = range.end.to_point(&display_map);
15556                    start.column = 0;
15557                    end.column = buffer.line_len(MultiBufferRow(end.row));
15558                    start..end
15559                })
15560                .collect::<Vec<_>>();
15561
15562            self.unfold_ranges(&ranges, true, true, cx);
15563        } else {
15564            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15565            let buffer_ids = self
15566                .selections
15567                .disjoint_anchor_ranges()
15568                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15569                .collect::<HashSet<_>>();
15570            for buffer_id in buffer_ids {
15571                self.unfold_buffer(buffer_id, cx);
15572            }
15573        }
15574    }
15575
15576    pub fn unfold_recursive(
15577        &mut self,
15578        _: &UnfoldRecursive,
15579        _window: &mut Window,
15580        cx: &mut Context<Self>,
15581    ) {
15582        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15583        let selections = self.selections.all::<Point>(cx);
15584        let ranges = selections
15585            .iter()
15586            .map(|s| {
15587                let mut range = s.display_range(&display_map).sorted();
15588                *range.start.column_mut() = 0;
15589                *range.end.column_mut() = display_map.line_len(range.end.row());
15590                let start = range.start.to_point(&display_map);
15591                let end = range.end.to_point(&display_map);
15592                start..end
15593            })
15594            .collect::<Vec<_>>();
15595
15596        self.unfold_ranges(&ranges, true, true, cx);
15597    }
15598
15599    pub fn unfold_at(
15600        &mut self,
15601        buffer_row: MultiBufferRow,
15602        _window: &mut Window,
15603        cx: &mut Context<Self>,
15604    ) {
15605        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15606
15607        let intersection_range = Point::new(buffer_row.0, 0)
15608            ..Point::new(
15609                buffer_row.0,
15610                display_map.buffer_snapshot.line_len(buffer_row),
15611            );
15612
15613        let autoscroll = self
15614            .selections
15615            .all::<Point>(cx)
15616            .iter()
15617            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15618
15619        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15620    }
15621
15622    pub fn unfold_all(
15623        &mut self,
15624        _: &actions::UnfoldAll,
15625        _window: &mut Window,
15626        cx: &mut Context<Self>,
15627    ) {
15628        if self.buffer.read(cx).is_singleton() {
15629            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15630            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15631        } else {
15632            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15633                editor
15634                    .update(cx, |editor, cx| {
15635                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15636                            editor.unfold_buffer(buffer_id, cx);
15637                        }
15638                    })
15639                    .ok();
15640            });
15641        }
15642    }
15643
15644    pub fn fold_selected_ranges(
15645        &mut self,
15646        _: &FoldSelectedRanges,
15647        window: &mut Window,
15648        cx: &mut Context<Self>,
15649    ) {
15650        let selections = self.selections.all_adjusted(cx);
15651        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15652        let ranges = selections
15653            .into_iter()
15654            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15655            .collect::<Vec<_>>();
15656        self.fold_creases(ranges, true, window, cx);
15657    }
15658
15659    pub fn fold_ranges<T: ToOffset + Clone>(
15660        &mut self,
15661        ranges: Vec<Range<T>>,
15662        auto_scroll: bool,
15663        window: &mut Window,
15664        cx: &mut Context<Self>,
15665    ) {
15666        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15667        let ranges = ranges
15668            .into_iter()
15669            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15670            .collect::<Vec<_>>();
15671        self.fold_creases(ranges, auto_scroll, window, cx);
15672    }
15673
15674    pub fn fold_creases<T: ToOffset + Clone>(
15675        &mut self,
15676        creases: Vec<Crease<T>>,
15677        auto_scroll: bool,
15678        _window: &mut Window,
15679        cx: &mut Context<Self>,
15680    ) {
15681        if creases.is_empty() {
15682            return;
15683        }
15684
15685        let mut buffers_affected = HashSet::default();
15686        let multi_buffer = self.buffer().read(cx);
15687        for crease in &creases {
15688            if let Some((_, buffer, _)) =
15689                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15690            {
15691                buffers_affected.insert(buffer.read(cx).remote_id());
15692            };
15693        }
15694
15695        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15696
15697        if auto_scroll {
15698            self.request_autoscroll(Autoscroll::fit(), cx);
15699        }
15700
15701        cx.notify();
15702
15703        self.scrollbar_marker_state.dirty = true;
15704        self.folds_did_change(cx);
15705    }
15706
15707    /// Removes any folds whose ranges intersect any of the given ranges.
15708    pub fn unfold_ranges<T: ToOffset + Clone>(
15709        &mut self,
15710        ranges: &[Range<T>],
15711        inclusive: bool,
15712        auto_scroll: bool,
15713        cx: &mut Context<Self>,
15714    ) {
15715        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15716            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15717        });
15718        self.folds_did_change(cx);
15719    }
15720
15721    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15722        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15723            return;
15724        }
15725        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15726        self.display_map.update(cx, |display_map, cx| {
15727            display_map.fold_buffers([buffer_id], cx)
15728        });
15729        cx.emit(EditorEvent::BufferFoldToggled {
15730            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15731            folded: true,
15732        });
15733        cx.notify();
15734    }
15735
15736    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15737        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15738            return;
15739        }
15740        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15741        self.display_map.update(cx, |display_map, cx| {
15742            display_map.unfold_buffers([buffer_id], cx);
15743        });
15744        cx.emit(EditorEvent::BufferFoldToggled {
15745            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15746            folded: false,
15747        });
15748        cx.notify();
15749    }
15750
15751    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15752        self.display_map.read(cx).is_buffer_folded(buffer)
15753    }
15754
15755    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15756        self.display_map.read(cx).folded_buffers()
15757    }
15758
15759    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15760        self.display_map.update(cx, |display_map, cx| {
15761            display_map.disable_header_for_buffer(buffer_id, cx);
15762        });
15763        cx.notify();
15764    }
15765
15766    /// Removes any folds with the given ranges.
15767    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15768        &mut self,
15769        ranges: &[Range<T>],
15770        type_id: TypeId,
15771        auto_scroll: bool,
15772        cx: &mut Context<Self>,
15773    ) {
15774        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15775            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15776        });
15777        self.folds_did_change(cx);
15778    }
15779
15780    fn remove_folds_with<T: ToOffset + Clone>(
15781        &mut self,
15782        ranges: &[Range<T>],
15783        auto_scroll: bool,
15784        cx: &mut Context<Self>,
15785        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15786    ) {
15787        if ranges.is_empty() {
15788            return;
15789        }
15790
15791        let mut buffers_affected = HashSet::default();
15792        let multi_buffer = self.buffer().read(cx);
15793        for range in ranges {
15794            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15795                buffers_affected.insert(buffer.read(cx).remote_id());
15796            };
15797        }
15798
15799        self.display_map.update(cx, update);
15800
15801        if auto_scroll {
15802            self.request_autoscroll(Autoscroll::fit(), cx);
15803        }
15804
15805        cx.notify();
15806        self.scrollbar_marker_state.dirty = true;
15807        self.active_indent_guides_state.dirty = true;
15808    }
15809
15810    pub fn update_fold_widths(
15811        &mut self,
15812        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15813        cx: &mut Context<Self>,
15814    ) -> bool {
15815        self.display_map
15816            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15817    }
15818
15819    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15820        self.display_map.read(cx).fold_placeholder.clone()
15821    }
15822
15823    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15824        self.buffer.update(cx, |buffer, cx| {
15825            buffer.set_all_diff_hunks_expanded(cx);
15826        });
15827    }
15828
15829    pub fn expand_all_diff_hunks(
15830        &mut self,
15831        _: &ExpandAllDiffHunks,
15832        _window: &mut Window,
15833        cx: &mut Context<Self>,
15834    ) {
15835        self.buffer.update(cx, |buffer, cx| {
15836            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15837        });
15838    }
15839
15840    pub fn toggle_selected_diff_hunks(
15841        &mut self,
15842        _: &ToggleSelectedDiffHunks,
15843        _window: &mut Window,
15844        cx: &mut Context<Self>,
15845    ) {
15846        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15847        self.toggle_diff_hunks_in_ranges(ranges, cx);
15848    }
15849
15850    pub fn diff_hunks_in_ranges<'a>(
15851        &'a self,
15852        ranges: &'a [Range<Anchor>],
15853        buffer: &'a MultiBufferSnapshot,
15854    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15855        ranges.iter().flat_map(move |range| {
15856            let end_excerpt_id = range.end.excerpt_id;
15857            let range = range.to_point(buffer);
15858            let mut peek_end = range.end;
15859            if range.end.row < buffer.max_row().0 {
15860                peek_end = Point::new(range.end.row + 1, 0);
15861            }
15862            buffer
15863                .diff_hunks_in_range(range.start..peek_end)
15864                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15865        })
15866    }
15867
15868    pub fn has_stageable_diff_hunks_in_ranges(
15869        &self,
15870        ranges: &[Range<Anchor>],
15871        snapshot: &MultiBufferSnapshot,
15872    ) -> bool {
15873        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15874        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15875    }
15876
15877    pub fn toggle_staged_selected_diff_hunks(
15878        &mut self,
15879        _: &::git::ToggleStaged,
15880        _: &mut Window,
15881        cx: &mut Context<Self>,
15882    ) {
15883        let snapshot = self.buffer.read(cx).snapshot(cx);
15884        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15885        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15886        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15887    }
15888
15889    pub fn set_render_diff_hunk_controls(
15890        &mut self,
15891        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15892        cx: &mut Context<Self>,
15893    ) {
15894        self.render_diff_hunk_controls = render_diff_hunk_controls;
15895        cx.notify();
15896    }
15897
15898    pub fn stage_and_next(
15899        &mut self,
15900        _: &::git::StageAndNext,
15901        window: &mut Window,
15902        cx: &mut Context<Self>,
15903    ) {
15904        self.do_stage_or_unstage_and_next(true, window, cx);
15905    }
15906
15907    pub fn unstage_and_next(
15908        &mut self,
15909        _: &::git::UnstageAndNext,
15910        window: &mut Window,
15911        cx: &mut Context<Self>,
15912    ) {
15913        self.do_stage_or_unstage_and_next(false, window, cx);
15914    }
15915
15916    pub fn stage_or_unstage_diff_hunks(
15917        &mut self,
15918        stage: bool,
15919        ranges: Vec<Range<Anchor>>,
15920        cx: &mut Context<Self>,
15921    ) {
15922        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15923        cx.spawn(async move |this, cx| {
15924            task.await?;
15925            this.update(cx, |this, cx| {
15926                let snapshot = this.buffer.read(cx).snapshot(cx);
15927                let chunk_by = this
15928                    .diff_hunks_in_ranges(&ranges, &snapshot)
15929                    .chunk_by(|hunk| hunk.buffer_id);
15930                for (buffer_id, hunks) in &chunk_by {
15931                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15932                }
15933            })
15934        })
15935        .detach_and_log_err(cx);
15936    }
15937
15938    fn save_buffers_for_ranges_if_needed(
15939        &mut self,
15940        ranges: &[Range<Anchor>],
15941        cx: &mut Context<Editor>,
15942    ) -> Task<Result<()>> {
15943        let multibuffer = self.buffer.read(cx);
15944        let snapshot = multibuffer.read(cx);
15945        let buffer_ids: HashSet<_> = ranges
15946            .iter()
15947            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15948            .collect();
15949        drop(snapshot);
15950
15951        let mut buffers = HashSet::default();
15952        for buffer_id in buffer_ids {
15953            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15954                let buffer = buffer_entity.read(cx);
15955                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15956                {
15957                    buffers.insert(buffer_entity);
15958                }
15959            }
15960        }
15961
15962        if let Some(project) = &self.project {
15963            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15964        } else {
15965            Task::ready(Ok(()))
15966        }
15967    }
15968
15969    fn do_stage_or_unstage_and_next(
15970        &mut self,
15971        stage: bool,
15972        window: &mut Window,
15973        cx: &mut Context<Self>,
15974    ) {
15975        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15976
15977        if ranges.iter().any(|range| range.start != range.end) {
15978            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15979            return;
15980        }
15981
15982        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15983        let snapshot = self.snapshot(window, cx);
15984        let position = self.selections.newest::<Point>(cx).head();
15985        let mut row = snapshot
15986            .buffer_snapshot
15987            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15988            .find(|hunk| hunk.row_range.start.0 > position.row)
15989            .map(|hunk| hunk.row_range.start);
15990
15991        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15992        // Outside of the project diff editor, wrap around to the beginning.
15993        if !all_diff_hunks_expanded {
15994            row = row.or_else(|| {
15995                snapshot
15996                    .buffer_snapshot
15997                    .diff_hunks_in_range(Point::zero()..position)
15998                    .find(|hunk| hunk.row_range.end.0 < position.row)
15999                    .map(|hunk| hunk.row_range.start)
16000            });
16001        }
16002
16003        if let Some(row) = row {
16004            let destination = Point::new(row.0, 0);
16005            let autoscroll = Autoscroll::center();
16006
16007            self.unfold_ranges(&[destination..destination], false, false, cx);
16008            self.change_selections(Some(autoscroll), window, cx, |s| {
16009                s.select_ranges([destination..destination]);
16010            });
16011        }
16012    }
16013
16014    fn do_stage_or_unstage(
16015        &self,
16016        stage: bool,
16017        buffer_id: BufferId,
16018        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16019        cx: &mut App,
16020    ) -> Option<()> {
16021        let project = self.project.as_ref()?;
16022        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16023        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16024        let buffer_snapshot = buffer.read(cx).snapshot();
16025        let file_exists = buffer_snapshot
16026            .file()
16027            .is_some_and(|file| file.disk_state().exists());
16028        diff.update(cx, |diff, cx| {
16029            diff.stage_or_unstage_hunks(
16030                stage,
16031                &hunks
16032                    .map(|hunk| buffer_diff::DiffHunk {
16033                        buffer_range: hunk.buffer_range,
16034                        diff_base_byte_range: hunk.diff_base_byte_range,
16035                        secondary_status: hunk.secondary_status,
16036                        range: Point::zero()..Point::zero(), // unused
16037                    })
16038                    .collect::<Vec<_>>(),
16039                &buffer_snapshot,
16040                file_exists,
16041                cx,
16042            )
16043        });
16044        None
16045    }
16046
16047    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16048        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16049        self.buffer
16050            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16051    }
16052
16053    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16054        self.buffer.update(cx, |buffer, cx| {
16055            let ranges = vec![Anchor::min()..Anchor::max()];
16056            if !buffer.all_diff_hunks_expanded()
16057                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16058            {
16059                buffer.collapse_diff_hunks(ranges, cx);
16060                true
16061            } else {
16062                false
16063            }
16064        })
16065    }
16066
16067    fn toggle_diff_hunks_in_ranges(
16068        &mut self,
16069        ranges: Vec<Range<Anchor>>,
16070        cx: &mut Context<Editor>,
16071    ) {
16072        self.buffer.update(cx, |buffer, cx| {
16073            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16074            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16075        })
16076    }
16077
16078    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16079        self.buffer.update(cx, |buffer, cx| {
16080            let snapshot = buffer.snapshot(cx);
16081            let excerpt_id = range.end.excerpt_id;
16082            let point_range = range.to_point(&snapshot);
16083            let expand = !buffer.single_hunk_is_expanded(range, cx);
16084            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16085        })
16086    }
16087
16088    pub(crate) fn apply_all_diff_hunks(
16089        &mut self,
16090        _: &ApplyAllDiffHunks,
16091        window: &mut Window,
16092        cx: &mut Context<Self>,
16093    ) {
16094        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16095
16096        let buffers = self.buffer.read(cx).all_buffers();
16097        for branch_buffer in buffers {
16098            branch_buffer.update(cx, |branch_buffer, cx| {
16099                branch_buffer.merge_into_base(Vec::new(), cx);
16100            });
16101        }
16102
16103        if let Some(project) = self.project.clone() {
16104            self.save(true, project, window, cx).detach_and_log_err(cx);
16105        }
16106    }
16107
16108    pub(crate) fn apply_selected_diff_hunks(
16109        &mut self,
16110        _: &ApplyDiffHunk,
16111        window: &mut Window,
16112        cx: &mut Context<Self>,
16113    ) {
16114        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16115        let snapshot = self.snapshot(window, cx);
16116        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16117        let mut ranges_by_buffer = HashMap::default();
16118        self.transact(window, cx, |editor, _window, cx| {
16119            for hunk in hunks {
16120                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16121                    ranges_by_buffer
16122                        .entry(buffer.clone())
16123                        .or_insert_with(Vec::new)
16124                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16125                }
16126            }
16127
16128            for (buffer, ranges) in ranges_by_buffer {
16129                buffer.update(cx, |buffer, cx| {
16130                    buffer.merge_into_base(ranges, cx);
16131                });
16132            }
16133        });
16134
16135        if let Some(project) = self.project.clone() {
16136            self.save(true, project, window, cx).detach_and_log_err(cx);
16137        }
16138    }
16139
16140    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16141        if hovered != self.gutter_hovered {
16142            self.gutter_hovered = hovered;
16143            cx.notify();
16144        }
16145    }
16146
16147    pub fn insert_blocks(
16148        &mut self,
16149        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16150        autoscroll: Option<Autoscroll>,
16151        cx: &mut Context<Self>,
16152    ) -> Vec<CustomBlockId> {
16153        let blocks = self
16154            .display_map
16155            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16156        if let Some(autoscroll) = autoscroll {
16157            self.request_autoscroll(autoscroll, cx);
16158        }
16159        cx.notify();
16160        blocks
16161    }
16162
16163    pub fn resize_blocks(
16164        &mut self,
16165        heights: HashMap<CustomBlockId, u32>,
16166        autoscroll: Option<Autoscroll>,
16167        cx: &mut Context<Self>,
16168    ) {
16169        self.display_map
16170            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16171        if let Some(autoscroll) = autoscroll {
16172            self.request_autoscroll(autoscroll, cx);
16173        }
16174        cx.notify();
16175    }
16176
16177    pub fn replace_blocks(
16178        &mut self,
16179        renderers: HashMap<CustomBlockId, RenderBlock>,
16180        autoscroll: Option<Autoscroll>,
16181        cx: &mut Context<Self>,
16182    ) {
16183        self.display_map
16184            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16185        if let Some(autoscroll) = autoscroll {
16186            self.request_autoscroll(autoscroll, cx);
16187        }
16188        cx.notify();
16189    }
16190
16191    pub fn remove_blocks(
16192        &mut self,
16193        block_ids: HashSet<CustomBlockId>,
16194        autoscroll: Option<Autoscroll>,
16195        cx: &mut Context<Self>,
16196    ) {
16197        self.display_map.update(cx, |display_map, cx| {
16198            display_map.remove_blocks(block_ids, cx)
16199        });
16200        if let Some(autoscroll) = autoscroll {
16201            self.request_autoscroll(autoscroll, cx);
16202        }
16203        cx.notify();
16204    }
16205
16206    pub fn row_for_block(
16207        &self,
16208        block_id: CustomBlockId,
16209        cx: &mut Context<Self>,
16210    ) -> Option<DisplayRow> {
16211        self.display_map
16212            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16213    }
16214
16215    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16216        self.focused_block = Some(focused_block);
16217    }
16218
16219    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16220        self.focused_block.take()
16221    }
16222
16223    pub fn insert_creases(
16224        &mut self,
16225        creases: impl IntoIterator<Item = Crease<Anchor>>,
16226        cx: &mut Context<Self>,
16227    ) -> Vec<CreaseId> {
16228        self.display_map
16229            .update(cx, |map, cx| map.insert_creases(creases, cx))
16230    }
16231
16232    pub fn remove_creases(
16233        &mut self,
16234        ids: impl IntoIterator<Item = CreaseId>,
16235        cx: &mut Context<Self>,
16236    ) -> Vec<(CreaseId, Range<Anchor>)> {
16237        self.display_map
16238            .update(cx, |map, cx| map.remove_creases(ids, cx))
16239    }
16240
16241    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16242        self.display_map
16243            .update(cx, |map, cx| map.snapshot(cx))
16244            .longest_row()
16245    }
16246
16247    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16248        self.display_map
16249            .update(cx, |map, cx| map.snapshot(cx))
16250            .max_point()
16251    }
16252
16253    pub fn text(&self, cx: &App) -> String {
16254        self.buffer.read(cx).read(cx).text()
16255    }
16256
16257    pub fn is_empty(&self, cx: &App) -> bool {
16258        self.buffer.read(cx).read(cx).is_empty()
16259    }
16260
16261    pub fn text_option(&self, cx: &App) -> Option<String> {
16262        let text = self.text(cx);
16263        let text = text.trim();
16264
16265        if text.is_empty() {
16266            return None;
16267        }
16268
16269        Some(text.to_string())
16270    }
16271
16272    pub fn set_text(
16273        &mut self,
16274        text: impl Into<Arc<str>>,
16275        window: &mut Window,
16276        cx: &mut Context<Self>,
16277    ) {
16278        self.transact(window, cx, |this, _, cx| {
16279            this.buffer
16280                .read(cx)
16281                .as_singleton()
16282                .expect("you can only call set_text on editors for singleton buffers")
16283                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16284        });
16285    }
16286
16287    pub fn display_text(&self, cx: &mut App) -> String {
16288        self.display_map
16289            .update(cx, |map, cx| map.snapshot(cx))
16290            .text()
16291    }
16292
16293    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16294        let mut wrap_guides = smallvec::smallvec![];
16295
16296        if self.show_wrap_guides == Some(false) {
16297            return wrap_guides;
16298        }
16299
16300        let settings = self.buffer.read(cx).language_settings(cx);
16301        if settings.show_wrap_guides {
16302            match self.soft_wrap_mode(cx) {
16303                SoftWrap::Column(soft_wrap) => {
16304                    wrap_guides.push((soft_wrap as usize, true));
16305                }
16306                SoftWrap::Bounded(soft_wrap) => {
16307                    wrap_guides.push((soft_wrap as usize, true));
16308                }
16309                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16310            }
16311            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16312        }
16313
16314        wrap_guides
16315    }
16316
16317    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16318        let settings = self.buffer.read(cx).language_settings(cx);
16319        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16320        match mode {
16321            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16322                SoftWrap::None
16323            }
16324            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16325            language_settings::SoftWrap::PreferredLineLength => {
16326                SoftWrap::Column(settings.preferred_line_length)
16327            }
16328            language_settings::SoftWrap::Bounded => {
16329                SoftWrap::Bounded(settings.preferred_line_length)
16330            }
16331        }
16332    }
16333
16334    pub fn set_soft_wrap_mode(
16335        &mut self,
16336        mode: language_settings::SoftWrap,
16337
16338        cx: &mut Context<Self>,
16339    ) {
16340        self.soft_wrap_mode_override = Some(mode);
16341        cx.notify();
16342    }
16343
16344    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16345        self.hard_wrap = hard_wrap;
16346        cx.notify();
16347    }
16348
16349    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16350        self.text_style_refinement = Some(style);
16351    }
16352
16353    /// called by the Element so we know what style we were most recently rendered with.
16354    pub(crate) fn set_style(
16355        &mut self,
16356        style: EditorStyle,
16357        window: &mut Window,
16358        cx: &mut Context<Self>,
16359    ) {
16360        let rem_size = window.rem_size();
16361        self.display_map.update(cx, |map, cx| {
16362            map.set_font(
16363                style.text.font(),
16364                style.text.font_size.to_pixels(rem_size),
16365                cx,
16366            )
16367        });
16368        self.style = Some(style);
16369    }
16370
16371    pub fn style(&self) -> Option<&EditorStyle> {
16372        self.style.as_ref()
16373    }
16374
16375    // Called by the element. This method is not designed to be called outside of the editor
16376    // element's layout code because it does not notify when rewrapping is computed synchronously.
16377    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16378        self.display_map
16379            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16380    }
16381
16382    pub fn set_soft_wrap(&mut self) {
16383        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16384    }
16385
16386    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16387        if self.soft_wrap_mode_override.is_some() {
16388            self.soft_wrap_mode_override.take();
16389        } else {
16390            let soft_wrap = match self.soft_wrap_mode(cx) {
16391                SoftWrap::GitDiff => return,
16392                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16393                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16394                    language_settings::SoftWrap::None
16395                }
16396            };
16397            self.soft_wrap_mode_override = Some(soft_wrap);
16398        }
16399        cx.notify();
16400    }
16401
16402    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16403        let Some(workspace) = self.workspace() else {
16404            return;
16405        };
16406        let fs = workspace.read(cx).app_state().fs.clone();
16407        let current_show = TabBarSettings::get_global(cx).show;
16408        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16409            setting.show = Some(!current_show);
16410        });
16411    }
16412
16413    pub fn toggle_indent_guides(
16414        &mut self,
16415        _: &ToggleIndentGuides,
16416        _: &mut Window,
16417        cx: &mut Context<Self>,
16418    ) {
16419        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16420            self.buffer
16421                .read(cx)
16422                .language_settings(cx)
16423                .indent_guides
16424                .enabled
16425        });
16426        self.show_indent_guides = Some(!currently_enabled);
16427        cx.notify();
16428    }
16429
16430    fn should_show_indent_guides(&self) -> Option<bool> {
16431        self.show_indent_guides
16432    }
16433
16434    pub fn toggle_line_numbers(
16435        &mut self,
16436        _: &ToggleLineNumbers,
16437        _: &mut Window,
16438        cx: &mut Context<Self>,
16439    ) {
16440        let mut editor_settings = EditorSettings::get_global(cx).clone();
16441        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16442        EditorSettings::override_global(editor_settings, cx);
16443    }
16444
16445    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16446        if let Some(show_line_numbers) = self.show_line_numbers {
16447            return show_line_numbers;
16448        }
16449        EditorSettings::get_global(cx).gutter.line_numbers
16450    }
16451
16452    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16453        self.use_relative_line_numbers
16454            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16455    }
16456
16457    pub fn toggle_relative_line_numbers(
16458        &mut self,
16459        _: &ToggleRelativeLineNumbers,
16460        _: &mut Window,
16461        cx: &mut Context<Self>,
16462    ) {
16463        let is_relative = self.should_use_relative_line_numbers(cx);
16464        self.set_relative_line_number(Some(!is_relative), cx)
16465    }
16466
16467    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16468        self.use_relative_line_numbers = is_relative;
16469        cx.notify();
16470    }
16471
16472    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16473        self.show_gutter = show_gutter;
16474        cx.notify();
16475    }
16476
16477    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16478        self.show_scrollbars = show_scrollbars;
16479        cx.notify();
16480    }
16481
16482    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16483        self.show_line_numbers = Some(show_line_numbers);
16484        cx.notify();
16485    }
16486
16487    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16488        self.disable_expand_excerpt_buttons = true;
16489        cx.notify();
16490    }
16491
16492    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16493        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16494        cx.notify();
16495    }
16496
16497    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16498        self.show_code_actions = Some(show_code_actions);
16499        cx.notify();
16500    }
16501
16502    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16503        self.show_runnables = Some(show_runnables);
16504        cx.notify();
16505    }
16506
16507    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16508        self.show_breakpoints = Some(show_breakpoints);
16509        cx.notify();
16510    }
16511
16512    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16513        if self.display_map.read(cx).masked != masked {
16514            self.display_map.update(cx, |map, _| map.masked = masked);
16515        }
16516        cx.notify()
16517    }
16518
16519    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16520        self.show_wrap_guides = Some(show_wrap_guides);
16521        cx.notify();
16522    }
16523
16524    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16525        self.show_indent_guides = Some(show_indent_guides);
16526        cx.notify();
16527    }
16528
16529    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16530        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16531            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16532                if let Some(dir) = file.abs_path(cx).parent() {
16533                    return Some(dir.to_owned());
16534                }
16535            }
16536
16537            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16538                return Some(project_path.path.to_path_buf());
16539            }
16540        }
16541
16542        None
16543    }
16544
16545    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16546        self.active_excerpt(cx)?
16547            .1
16548            .read(cx)
16549            .file()
16550            .and_then(|f| f.as_local())
16551    }
16552
16553    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16554        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16555            let buffer = buffer.read(cx);
16556            if let Some(project_path) = buffer.project_path(cx) {
16557                let project = self.project.as_ref()?.read(cx);
16558                project.absolute_path(&project_path, cx)
16559            } else {
16560                buffer
16561                    .file()
16562                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16563            }
16564        })
16565    }
16566
16567    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16568        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16569            let project_path = buffer.read(cx).project_path(cx)?;
16570            let project = self.project.as_ref()?.read(cx);
16571            let entry = project.entry_for_path(&project_path, cx)?;
16572            let path = entry.path.to_path_buf();
16573            Some(path)
16574        })
16575    }
16576
16577    pub fn reveal_in_finder(
16578        &mut self,
16579        _: &RevealInFileManager,
16580        _window: &mut Window,
16581        cx: &mut Context<Self>,
16582    ) {
16583        if let Some(target) = self.target_file(cx) {
16584            cx.reveal_path(&target.abs_path(cx));
16585        }
16586    }
16587
16588    pub fn copy_path(
16589        &mut self,
16590        _: &zed_actions::workspace::CopyPath,
16591        _window: &mut Window,
16592        cx: &mut Context<Self>,
16593    ) {
16594        if let Some(path) = self.target_file_abs_path(cx) {
16595            if let Some(path) = path.to_str() {
16596                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16597            }
16598        }
16599    }
16600
16601    pub fn copy_relative_path(
16602        &mut self,
16603        _: &zed_actions::workspace::CopyRelativePath,
16604        _window: &mut Window,
16605        cx: &mut Context<Self>,
16606    ) {
16607        if let Some(path) = self.target_file_path(cx) {
16608            if let Some(path) = path.to_str() {
16609                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16610            }
16611        }
16612    }
16613
16614    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16615        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16616            buffer.read(cx).project_path(cx)
16617        } else {
16618            None
16619        }
16620    }
16621
16622    // Returns true if the editor handled a go-to-line request
16623    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16624        maybe!({
16625            let breakpoint_store = self.breakpoint_store.as_ref()?;
16626
16627            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16628            else {
16629                self.clear_row_highlights::<ActiveDebugLine>();
16630                return None;
16631            };
16632
16633            let position = active_stack_frame.position;
16634            let buffer_id = position.buffer_id?;
16635            let snapshot = self
16636                .project
16637                .as_ref()?
16638                .read(cx)
16639                .buffer_for_id(buffer_id, cx)?
16640                .read(cx)
16641                .snapshot();
16642
16643            let mut handled = false;
16644            for (id, ExcerptRange { context, .. }) in
16645                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16646            {
16647                if context.start.cmp(&position, &snapshot).is_ge()
16648                    || context.end.cmp(&position, &snapshot).is_lt()
16649                {
16650                    continue;
16651                }
16652                let snapshot = self.buffer.read(cx).snapshot(cx);
16653                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16654
16655                handled = true;
16656                self.clear_row_highlights::<ActiveDebugLine>();
16657                self.go_to_line::<ActiveDebugLine>(
16658                    multibuffer_anchor,
16659                    Some(cx.theme().colors().editor_debugger_active_line_background),
16660                    window,
16661                    cx,
16662                );
16663
16664                cx.notify();
16665            }
16666
16667            handled.then_some(())
16668        })
16669        .is_some()
16670    }
16671
16672    pub fn copy_file_name_without_extension(
16673        &mut self,
16674        _: &CopyFileNameWithoutExtension,
16675        _: &mut Window,
16676        cx: &mut Context<Self>,
16677    ) {
16678        if let Some(file) = self.target_file(cx) {
16679            if let Some(file_stem) = file.path().file_stem() {
16680                if let Some(name) = file_stem.to_str() {
16681                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16682                }
16683            }
16684        }
16685    }
16686
16687    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16688        if let Some(file) = self.target_file(cx) {
16689            if let Some(file_name) = file.path().file_name() {
16690                if let Some(name) = file_name.to_str() {
16691                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16692                }
16693            }
16694        }
16695    }
16696
16697    pub fn toggle_git_blame(
16698        &mut self,
16699        _: &::git::Blame,
16700        window: &mut Window,
16701        cx: &mut Context<Self>,
16702    ) {
16703        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16704
16705        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16706            self.start_git_blame(true, window, cx);
16707        }
16708
16709        cx.notify();
16710    }
16711
16712    pub fn toggle_git_blame_inline(
16713        &mut self,
16714        _: &ToggleGitBlameInline,
16715        window: &mut Window,
16716        cx: &mut Context<Self>,
16717    ) {
16718        self.toggle_git_blame_inline_internal(true, window, cx);
16719        cx.notify();
16720    }
16721
16722    pub fn open_git_blame_commit(
16723        &mut self,
16724        _: &OpenGitBlameCommit,
16725        window: &mut Window,
16726        cx: &mut Context<Self>,
16727    ) {
16728        self.open_git_blame_commit_internal(window, cx);
16729    }
16730
16731    fn open_git_blame_commit_internal(
16732        &mut self,
16733        window: &mut Window,
16734        cx: &mut Context<Self>,
16735    ) -> Option<()> {
16736        let blame = self.blame.as_ref()?;
16737        let snapshot = self.snapshot(window, cx);
16738        let cursor = self.selections.newest::<Point>(cx).head();
16739        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16740        let blame_entry = blame
16741            .update(cx, |blame, cx| {
16742                blame
16743                    .blame_for_rows(
16744                        &[RowInfo {
16745                            buffer_id: Some(buffer.remote_id()),
16746                            buffer_row: Some(point.row),
16747                            ..Default::default()
16748                        }],
16749                        cx,
16750                    )
16751                    .next()
16752            })
16753            .flatten()?;
16754        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16755        let repo = blame.read(cx).repository(cx)?;
16756        let workspace = self.workspace()?.downgrade();
16757        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16758        None
16759    }
16760
16761    pub fn git_blame_inline_enabled(&self) -> bool {
16762        self.git_blame_inline_enabled
16763    }
16764
16765    pub fn toggle_selection_menu(
16766        &mut self,
16767        _: &ToggleSelectionMenu,
16768        _: &mut Window,
16769        cx: &mut Context<Self>,
16770    ) {
16771        self.show_selection_menu = self
16772            .show_selection_menu
16773            .map(|show_selections_menu| !show_selections_menu)
16774            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16775
16776        cx.notify();
16777    }
16778
16779    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16780        self.show_selection_menu
16781            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16782    }
16783
16784    fn start_git_blame(
16785        &mut self,
16786        user_triggered: bool,
16787        window: &mut Window,
16788        cx: &mut Context<Self>,
16789    ) {
16790        if let Some(project) = self.project.as_ref() {
16791            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16792                return;
16793            };
16794
16795            if buffer.read(cx).file().is_none() {
16796                return;
16797            }
16798
16799            let focused = self.focus_handle(cx).contains_focused(window, cx);
16800
16801            let project = project.clone();
16802            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16803            self.blame_subscription =
16804                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16805            self.blame = Some(blame);
16806        }
16807    }
16808
16809    fn toggle_git_blame_inline_internal(
16810        &mut self,
16811        user_triggered: bool,
16812        window: &mut Window,
16813        cx: &mut Context<Self>,
16814    ) {
16815        if self.git_blame_inline_enabled {
16816            self.git_blame_inline_enabled = false;
16817            self.show_git_blame_inline = false;
16818            self.show_git_blame_inline_delay_task.take();
16819        } else {
16820            self.git_blame_inline_enabled = true;
16821            self.start_git_blame_inline(user_triggered, window, cx);
16822        }
16823
16824        cx.notify();
16825    }
16826
16827    fn start_git_blame_inline(
16828        &mut self,
16829        user_triggered: bool,
16830        window: &mut Window,
16831        cx: &mut Context<Self>,
16832    ) {
16833        self.start_git_blame(user_triggered, window, cx);
16834
16835        if ProjectSettings::get_global(cx)
16836            .git
16837            .inline_blame_delay()
16838            .is_some()
16839        {
16840            self.start_inline_blame_timer(window, cx);
16841        } else {
16842            self.show_git_blame_inline = true
16843        }
16844    }
16845
16846    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16847        self.blame.as_ref()
16848    }
16849
16850    pub fn show_git_blame_gutter(&self) -> bool {
16851        self.show_git_blame_gutter
16852    }
16853
16854    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16855        self.show_git_blame_gutter && self.has_blame_entries(cx)
16856    }
16857
16858    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16859        self.show_git_blame_inline
16860            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16861            && !self.newest_selection_head_on_empty_line(cx)
16862            && self.has_blame_entries(cx)
16863    }
16864
16865    fn has_blame_entries(&self, cx: &App) -> bool {
16866        self.blame()
16867            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16868    }
16869
16870    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16871        let cursor_anchor = self.selections.newest_anchor().head();
16872
16873        let snapshot = self.buffer.read(cx).snapshot(cx);
16874        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16875
16876        snapshot.line_len(buffer_row) == 0
16877    }
16878
16879    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16880        let buffer_and_selection = maybe!({
16881            let selection = self.selections.newest::<Point>(cx);
16882            let selection_range = selection.range();
16883
16884            let multi_buffer = self.buffer().read(cx);
16885            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16886            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16887
16888            let (buffer, range, _) = if selection.reversed {
16889                buffer_ranges.first()
16890            } else {
16891                buffer_ranges.last()
16892            }?;
16893
16894            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16895                ..text::ToPoint::to_point(&range.end, &buffer).row;
16896            Some((
16897                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16898                selection,
16899            ))
16900        });
16901
16902        let Some((buffer, selection)) = buffer_and_selection else {
16903            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16904        };
16905
16906        let Some(project) = self.project.as_ref() else {
16907            return Task::ready(Err(anyhow!("editor does not have project")));
16908        };
16909
16910        project.update(cx, |project, cx| {
16911            project.get_permalink_to_line(&buffer, selection, cx)
16912        })
16913    }
16914
16915    pub fn copy_permalink_to_line(
16916        &mut self,
16917        _: &CopyPermalinkToLine,
16918        window: &mut Window,
16919        cx: &mut Context<Self>,
16920    ) {
16921        let permalink_task = self.get_permalink_to_line(cx);
16922        let workspace = self.workspace();
16923
16924        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16925            Ok(permalink) => {
16926                cx.update(|_, cx| {
16927                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16928                })
16929                .ok();
16930            }
16931            Err(err) => {
16932                let message = format!("Failed to copy permalink: {err}");
16933
16934                Err::<(), anyhow::Error>(err).log_err();
16935
16936                if let Some(workspace) = workspace {
16937                    workspace
16938                        .update_in(cx, |workspace, _, cx| {
16939                            struct CopyPermalinkToLine;
16940
16941                            workspace.show_toast(
16942                                Toast::new(
16943                                    NotificationId::unique::<CopyPermalinkToLine>(),
16944                                    message,
16945                                ),
16946                                cx,
16947                            )
16948                        })
16949                        .ok();
16950                }
16951            }
16952        })
16953        .detach();
16954    }
16955
16956    pub fn copy_file_location(
16957        &mut self,
16958        _: &CopyFileLocation,
16959        _: &mut Window,
16960        cx: &mut Context<Self>,
16961    ) {
16962        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16963        if let Some(file) = self.target_file(cx) {
16964            if let Some(path) = file.path().to_str() {
16965                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16966            }
16967        }
16968    }
16969
16970    pub fn open_permalink_to_line(
16971        &mut self,
16972        _: &OpenPermalinkToLine,
16973        window: &mut Window,
16974        cx: &mut Context<Self>,
16975    ) {
16976        let permalink_task = self.get_permalink_to_line(cx);
16977        let workspace = self.workspace();
16978
16979        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16980            Ok(permalink) => {
16981                cx.update(|_, cx| {
16982                    cx.open_url(permalink.as_ref());
16983                })
16984                .ok();
16985            }
16986            Err(err) => {
16987                let message = format!("Failed to open permalink: {err}");
16988
16989                Err::<(), anyhow::Error>(err).log_err();
16990
16991                if let Some(workspace) = workspace {
16992                    workspace
16993                        .update(cx, |workspace, cx| {
16994                            struct OpenPermalinkToLine;
16995
16996                            workspace.show_toast(
16997                                Toast::new(
16998                                    NotificationId::unique::<OpenPermalinkToLine>(),
16999                                    message,
17000                                ),
17001                                cx,
17002                            )
17003                        })
17004                        .ok();
17005                }
17006            }
17007        })
17008        .detach();
17009    }
17010
17011    pub fn insert_uuid_v4(
17012        &mut self,
17013        _: &InsertUuidV4,
17014        window: &mut Window,
17015        cx: &mut Context<Self>,
17016    ) {
17017        self.insert_uuid(UuidVersion::V4, window, cx);
17018    }
17019
17020    pub fn insert_uuid_v7(
17021        &mut self,
17022        _: &InsertUuidV7,
17023        window: &mut Window,
17024        cx: &mut Context<Self>,
17025    ) {
17026        self.insert_uuid(UuidVersion::V7, window, cx);
17027    }
17028
17029    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17030        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17031        self.transact(window, cx, |this, window, cx| {
17032            let edits = this
17033                .selections
17034                .all::<Point>(cx)
17035                .into_iter()
17036                .map(|selection| {
17037                    let uuid = match version {
17038                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17039                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17040                    };
17041
17042                    (selection.range(), uuid.to_string())
17043                });
17044            this.edit(edits, cx);
17045            this.refresh_inline_completion(true, false, window, cx);
17046        });
17047    }
17048
17049    pub fn open_selections_in_multibuffer(
17050        &mut self,
17051        _: &OpenSelectionsInMultibuffer,
17052        window: &mut Window,
17053        cx: &mut Context<Self>,
17054    ) {
17055        let multibuffer = self.buffer.read(cx);
17056
17057        let Some(buffer) = multibuffer.as_singleton() else {
17058            return;
17059        };
17060
17061        let Some(workspace) = self.workspace() else {
17062            return;
17063        };
17064
17065        let locations = self
17066            .selections
17067            .disjoint_anchors()
17068            .iter()
17069            .map(|range| Location {
17070                buffer: buffer.clone(),
17071                range: range.start.text_anchor..range.end.text_anchor,
17072            })
17073            .collect::<Vec<_>>();
17074
17075        let title = multibuffer.title(cx).to_string();
17076
17077        cx.spawn_in(window, async move |_, cx| {
17078            workspace.update_in(cx, |workspace, window, cx| {
17079                Self::open_locations_in_multibuffer(
17080                    workspace,
17081                    locations,
17082                    format!("Selections for '{title}'"),
17083                    false,
17084                    MultibufferSelectionMode::All,
17085                    window,
17086                    cx,
17087                );
17088            })
17089        })
17090        .detach();
17091    }
17092
17093    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17094    /// last highlight added will be used.
17095    ///
17096    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17097    pub fn highlight_rows<T: 'static>(
17098        &mut self,
17099        range: Range<Anchor>,
17100        color: Hsla,
17101        options: RowHighlightOptions,
17102        cx: &mut Context<Self>,
17103    ) {
17104        let snapshot = self.buffer().read(cx).snapshot(cx);
17105        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17106        let ix = row_highlights.binary_search_by(|highlight| {
17107            Ordering::Equal
17108                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17109                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17110        });
17111
17112        if let Err(mut ix) = ix {
17113            let index = post_inc(&mut self.highlight_order);
17114
17115            // If this range intersects with the preceding highlight, then merge it with
17116            // the preceding highlight. Otherwise insert a new highlight.
17117            let mut merged = false;
17118            if ix > 0 {
17119                let prev_highlight = &mut row_highlights[ix - 1];
17120                if prev_highlight
17121                    .range
17122                    .end
17123                    .cmp(&range.start, &snapshot)
17124                    .is_ge()
17125                {
17126                    ix -= 1;
17127                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17128                        prev_highlight.range.end = range.end;
17129                    }
17130                    merged = true;
17131                    prev_highlight.index = index;
17132                    prev_highlight.color = color;
17133                    prev_highlight.options = options;
17134                }
17135            }
17136
17137            if !merged {
17138                row_highlights.insert(
17139                    ix,
17140                    RowHighlight {
17141                        range: range.clone(),
17142                        index,
17143                        color,
17144                        options,
17145                        type_id: TypeId::of::<T>(),
17146                    },
17147                );
17148            }
17149
17150            // If any of the following highlights intersect with this one, merge them.
17151            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17152                let highlight = &row_highlights[ix];
17153                if next_highlight
17154                    .range
17155                    .start
17156                    .cmp(&highlight.range.end, &snapshot)
17157                    .is_le()
17158                {
17159                    if next_highlight
17160                        .range
17161                        .end
17162                        .cmp(&highlight.range.end, &snapshot)
17163                        .is_gt()
17164                    {
17165                        row_highlights[ix].range.end = next_highlight.range.end;
17166                    }
17167                    row_highlights.remove(ix + 1);
17168                } else {
17169                    break;
17170                }
17171            }
17172        }
17173    }
17174
17175    /// Remove any highlighted row ranges of the given type that intersect the
17176    /// given ranges.
17177    pub fn remove_highlighted_rows<T: 'static>(
17178        &mut self,
17179        ranges_to_remove: Vec<Range<Anchor>>,
17180        cx: &mut Context<Self>,
17181    ) {
17182        let snapshot = self.buffer().read(cx).snapshot(cx);
17183        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17184        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17185        row_highlights.retain(|highlight| {
17186            while let Some(range_to_remove) = ranges_to_remove.peek() {
17187                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17188                    Ordering::Less | Ordering::Equal => {
17189                        ranges_to_remove.next();
17190                    }
17191                    Ordering::Greater => {
17192                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17193                            Ordering::Less | Ordering::Equal => {
17194                                return false;
17195                            }
17196                            Ordering::Greater => break,
17197                        }
17198                    }
17199                }
17200            }
17201
17202            true
17203        })
17204    }
17205
17206    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17207    pub fn clear_row_highlights<T: 'static>(&mut self) {
17208        self.highlighted_rows.remove(&TypeId::of::<T>());
17209    }
17210
17211    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17212    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17213        self.highlighted_rows
17214            .get(&TypeId::of::<T>())
17215            .map_or(&[] as &[_], |vec| vec.as_slice())
17216            .iter()
17217            .map(|highlight| (highlight.range.clone(), highlight.color))
17218    }
17219
17220    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17221    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17222    /// Allows to ignore certain kinds of highlights.
17223    pub fn highlighted_display_rows(
17224        &self,
17225        window: &mut Window,
17226        cx: &mut App,
17227    ) -> BTreeMap<DisplayRow, LineHighlight> {
17228        let snapshot = self.snapshot(window, cx);
17229        let mut used_highlight_orders = HashMap::default();
17230        self.highlighted_rows
17231            .iter()
17232            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17233            .fold(
17234                BTreeMap::<DisplayRow, LineHighlight>::new(),
17235                |mut unique_rows, highlight| {
17236                    let start = highlight.range.start.to_display_point(&snapshot);
17237                    let end = highlight.range.end.to_display_point(&snapshot);
17238                    let start_row = start.row().0;
17239                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17240                        && end.column() == 0
17241                    {
17242                        end.row().0.saturating_sub(1)
17243                    } else {
17244                        end.row().0
17245                    };
17246                    for row in start_row..=end_row {
17247                        let used_index =
17248                            used_highlight_orders.entry(row).or_insert(highlight.index);
17249                        if highlight.index >= *used_index {
17250                            *used_index = highlight.index;
17251                            unique_rows.insert(
17252                                DisplayRow(row),
17253                                LineHighlight {
17254                                    include_gutter: highlight.options.include_gutter,
17255                                    border: None,
17256                                    background: highlight.color.into(),
17257                                    type_id: Some(highlight.type_id),
17258                                },
17259                            );
17260                        }
17261                    }
17262                    unique_rows
17263                },
17264            )
17265    }
17266
17267    pub fn highlighted_display_row_for_autoscroll(
17268        &self,
17269        snapshot: &DisplaySnapshot,
17270    ) -> Option<DisplayRow> {
17271        self.highlighted_rows
17272            .values()
17273            .flat_map(|highlighted_rows| highlighted_rows.iter())
17274            .filter_map(|highlight| {
17275                if highlight.options.autoscroll {
17276                    Some(highlight.range.start.to_display_point(snapshot).row())
17277                } else {
17278                    None
17279                }
17280            })
17281            .min()
17282    }
17283
17284    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17285        self.highlight_background::<SearchWithinRange>(
17286            ranges,
17287            |colors| colors.editor_document_highlight_read_background,
17288            cx,
17289        )
17290    }
17291
17292    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17293        self.breadcrumb_header = Some(new_header);
17294    }
17295
17296    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17297        self.clear_background_highlights::<SearchWithinRange>(cx);
17298    }
17299
17300    pub fn highlight_background<T: 'static>(
17301        &mut self,
17302        ranges: &[Range<Anchor>],
17303        color_fetcher: fn(&ThemeColors) -> Hsla,
17304        cx: &mut Context<Self>,
17305    ) {
17306        self.background_highlights
17307            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17308        self.scrollbar_marker_state.dirty = true;
17309        cx.notify();
17310    }
17311
17312    pub fn clear_background_highlights<T: 'static>(
17313        &mut self,
17314        cx: &mut Context<Self>,
17315    ) -> Option<BackgroundHighlight> {
17316        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17317        if !text_highlights.1.is_empty() {
17318            self.scrollbar_marker_state.dirty = true;
17319            cx.notify();
17320        }
17321        Some(text_highlights)
17322    }
17323
17324    pub fn highlight_gutter<T: 'static>(
17325        &mut self,
17326        ranges: &[Range<Anchor>],
17327        color_fetcher: fn(&App) -> Hsla,
17328        cx: &mut Context<Self>,
17329    ) {
17330        self.gutter_highlights
17331            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17332        cx.notify();
17333    }
17334
17335    pub fn clear_gutter_highlights<T: 'static>(
17336        &mut self,
17337        cx: &mut Context<Self>,
17338    ) -> Option<GutterHighlight> {
17339        cx.notify();
17340        self.gutter_highlights.remove(&TypeId::of::<T>())
17341    }
17342
17343    #[cfg(feature = "test-support")]
17344    pub fn all_text_background_highlights(
17345        &self,
17346        window: &mut Window,
17347        cx: &mut Context<Self>,
17348    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17349        let snapshot = self.snapshot(window, cx);
17350        let buffer = &snapshot.buffer_snapshot;
17351        let start = buffer.anchor_before(0);
17352        let end = buffer.anchor_after(buffer.len());
17353        let theme = cx.theme().colors();
17354        self.background_highlights_in_range(start..end, &snapshot, theme)
17355    }
17356
17357    #[cfg(feature = "test-support")]
17358    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17359        let snapshot = self.buffer().read(cx).snapshot(cx);
17360
17361        let highlights = self
17362            .background_highlights
17363            .get(&TypeId::of::<items::BufferSearchHighlights>());
17364
17365        if let Some((_color, ranges)) = highlights {
17366            ranges
17367                .iter()
17368                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17369                .collect_vec()
17370        } else {
17371            vec![]
17372        }
17373    }
17374
17375    fn document_highlights_for_position<'a>(
17376        &'a self,
17377        position: Anchor,
17378        buffer: &'a MultiBufferSnapshot,
17379    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17380        let read_highlights = self
17381            .background_highlights
17382            .get(&TypeId::of::<DocumentHighlightRead>())
17383            .map(|h| &h.1);
17384        let write_highlights = self
17385            .background_highlights
17386            .get(&TypeId::of::<DocumentHighlightWrite>())
17387            .map(|h| &h.1);
17388        let left_position = position.bias_left(buffer);
17389        let right_position = position.bias_right(buffer);
17390        read_highlights
17391            .into_iter()
17392            .chain(write_highlights)
17393            .flat_map(move |ranges| {
17394                let start_ix = match ranges.binary_search_by(|probe| {
17395                    let cmp = probe.end.cmp(&left_position, buffer);
17396                    if cmp.is_ge() {
17397                        Ordering::Greater
17398                    } else {
17399                        Ordering::Less
17400                    }
17401                }) {
17402                    Ok(i) | Err(i) => i,
17403                };
17404
17405                ranges[start_ix..]
17406                    .iter()
17407                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17408            })
17409    }
17410
17411    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17412        self.background_highlights
17413            .get(&TypeId::of::<T>())
17414            .map_or(false, |(_, highlights)| !highlights.is_empty())
17415    }
17416
17417    pub fn background_highlights_in_range(
17418        &self,
17419        search_range: Range<Anchor>,
17420        display_snapshot: &DisplaySnapshot,
17421        theme: &ThemeColors,
17422    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17423        let mut results = Vec::new();
17424        for (color_fetcher, ranges) in self.background_highlights.values() {
17425            let color = color_fetcher(theme);
17426            let start_ix = match ranges.binary_search_by(|probe| {
17427                let cmp = probe
17428                    .end
17429                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17430                if cmp.is_gt() {
17431                    Ordering::Greater
17432                } else {
17433                    Ordering::Less
17434                }
17435            }) {
17436                Ok(i) | Err(i) => i,
17437            };
17438            for range in &ranges[start_ix..] {
17439                if range
17440                    .start
17441                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17442                    .is_ge()
17443                {
17444                    break;
17445                }
17446
17447                let start = range.start.to_display_point(display_snapshot);
17448                let end = range.end.to_display_point(display_snapshot);
17449                results.push((start..end, color))
17450            }
17451        }
17452        results
17453    }
17454
17455    pub fn background_highlight_row_ranges<T: 'static>(
17456        &self,
17457        search_range: Range<Anchor>,
17458        display_snapshot: &DisplaySnapshot,
17459        count: usize,
17460    ) -> Vec<RangeInclusive<DisplayPoint>> {
17461        let mut results = Vec::new();
17462        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17463            return vec![];
17464        };
17465
17466        let start_ix = match ranges.binary_search_by(|probe| {
17467            let cmp = probe
17468                .end
17469                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17470            if cmp.is_gt() {
17471                Ordering::Greater
17472            } else {
17473                Ordering::Less
17474            }
17475        }) {
17476            Ok(i) | Err(i) => i,
17477        };
17478        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17479            if let (Some(start_display), Some(end_display)) = (start, end) {
17480                results.push(
17481                    start_display.to_display_point(display_snapshot)
17482                        ..=end_display.to_display_point(display_snapshot),
17483                );
17484            }
17485        };
17486        let mut start_row: Option<Point> = None;
17487        let mut end_row: Option<Point> = None;
17488        if ranges.len() > count {
17489            return Vec::new();
17490        }
17491        for range in &ranges[start_ix..] {
17492            if range
17493                .start
17494                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17495                .is_ge()
17496            {
17497                break;
17498            }
17499            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17500            if let Some(current_row) = &end_row {
17501                if end.row == current_row.row {
17502                    continue;
17503                }
17504            }
17505            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17506            if start_row.is_none() {
17507                assert_eq!(end_row, None);
17508                start_row = Some(start);
17509                end_row = Some(end);
17510                continue;
17511            }
17512            if let Some(current_end) = end_row.as_mut() {
17513                if start.row > current_end.row + 1 {
17514                    push_region(start_row, end_row);
17515                    start_row = Some(start);
17516                    end_row = Some(end);
17517                } else {
17518                    // Merge two hunks.
17519                    *current_end = end;
17520                }
17521            } else {
17522                unreachable!();
17523            }
17524        }
17525        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17526        push_region(start_row, end_row);
17527        results
17528    }
17529
17530    pub fn gutter_highlights_in_range(
17531        &self,
17532        search_range: Range<Anchor>,
17533        display_snapshot: &DisplaySnapshot,
17534        cx: &App,
17535    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17536        let mut results = Vec::new();
17537        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17538            let color = color_fetcher(cx);
17539            let start_ix = match ranges.binary_search_by(|probe| {
17540                let cmp = probe
17541                    .end
17542                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17543                if cmp.is_gt() {
17544                    Ordering::Greater
17545                } else {
17546                    Ordering::Less
17547                }
17548            }) {
17549                Ok(i) | Err(i) => i,
17550            };
17551            for range in &ranges[start_ix..] {
17552                if range
17553                    .start
17554                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17555                    .is_ge()
17556                {
17557                    break;
17558                }
17559
17560                let start = range.start.to_display_point(display_snapshot);
17561                let end = range.end.to_display_point(display_snapshot);
17562                results.push((start..end, color))
17563            }
17564        }
17565        results
17566    }
17567
17568    /// Get the text ranges corresponding to the redaction query
17569    pub fn redacted_ranges(
17570        &self,
17571        search_range: Range<Anchor>,
17572        display_snapshot: &DisplaySnapshot,
17573        cx: &App,
17574    ) -> Vec<Range<DisplayPoint>> {
17575        display_snapshot
17576            .buffer_snapshot
17577            .redacted_ranges(search_range, |file| {
17578                if let Some(file) = file {
17579                    file.is_private()
17580                        && EditorSettings::get(
17581                            Some(SettingsLocation {
17582                                worktree_id: file.worktree_id(cx),
17583                                path: file.path().as_ref(),
17584                            }),
17585                            cx,
17586                        )
17587                        .redact_private_values
17588                } else {
17589                    false
17590                }
17591            })
17592            .map(|range| {
17593                range.start.to_display_point(display_snapshot)
17594                    ..range.end.to_display_point(display_snapshot)
17595            })
17596            .collect()
17597    }
17598
17599    pub fn highlight_text<T: 'static>(
17600        &mut self,
17601        ranges: Vec<Range<Anchor>>,
17602        style: HighlightStyle,
17603        cx: &mut Context<Self>,
17604    ) {
17605        self.display_map.update(cx, |map, _| {
17606            map.highlight_text(TypeId::of::<T>(), ranges, style)
17607        });
17608        cx.notify();
17609    }
17610
17611    pub(crate) fn highlight_inlays<T: 'static>(
17612        &mut self,
17613        highlights: Vec<InlayHighlight>,
17614        style: HighlightStyle,
17615        cx: &mut Context<Self>,
17616    ) {
17617        self.display_map.update(cx, |map, _| {
17618            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17619        });
17620        cx.notify();
17621    }
17622
17623    pub fn text_highlights<'a, T: 'static>(
17624        &'a self,
17625        cx: &'a App,
17626    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17627        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17628    }
17629
17630    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17631        let cleared = self
17632            .display_map
17633            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17634        if cleared {
17635            cx.notify();
17636        }
17637    }
17638
17639    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17640        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17641            && self.focus_handle.is_focused(window)
17642    }
17643
17644    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17645        self.show_cursor_when_unfocused = is_enabled;
17646        cx.notify();
17647    }
17648
17649    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17650        cx.notify();
17651    }
17652
17653    fn on_debug_session_event(
17654        &mut self,
17655        _session: Entity<Session>,
17656        event: &SessionEvent,
17657        cx: &mut Context<Self>,
17658    ) {
17659        match event {
17660            SessionEvent::InvalidateInlineValue => {
17661                self.refresh_inline_values(cx);
17662            }
17663            _ => {}
17664        }
17665    }
17666
17667    fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17668        let Some(project) = self.project.clone() else {
17669            return;
17670        };
17671        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17672            return;
17673        };
17674        if !self.inline_value_cache.enabled {
17675            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17676            self.splice_inlays(&inlays, Vec::new(), cx);
17677            return;
17678        }
17679
17680        let current_execution_position = self
17681            .highlighted_rows
17682            .get(&TypeId::of::<ActiveDebugLine>())
17683            .and_then(|lines| lines.last().map(|line| line.range.start));
17684
17685        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17686            let snapshot = editor
17687                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17688                .ok()?;
17689
17690            let inline_values = editor
17691                .update(cx, |_, cx| {
17692                    let Some(current_execution_position) = current_execution_position else {
17693                        return Some(Task::ready(Ok(Vec::new())));
17694                    };
17695
17696                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17697                    // anchor is in the same buffer
17698                    let range =
17699                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17700                    project.inline_values(buffer, range, cx)
17701                })
17702                .ok()
17703                .flatten()?
17704                .await
17705                .context("refreshing debugger inlays")
17706                .log_err()?;
17707
17708            let (excerpt_id, buffer_id) = snapshot
17709                .excerpts()
17710                .next()
17711                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17712            editor
17713                .update(cx, |editor, cx| {
17714                    let new_inlays = inline_values
17715                        .into_iter()
17716                        .map(|debugger_value| {
17717                            Inlay::debugger_hint(
17718                                post_inc(&mut editor.next_inlay_id),
17719                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17720                                debugger_value.text(),
17721                            )
17722                        })
17723                        .collect::<Vec<_>>();
17724                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17725                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17726
17727                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17728                })
17729                .ok()?;
17730            Some(())
17731        });
17732    }
17733
17734    fn on_buffer_event(
17735        &mut self,
17736        multibuffer: &Entity<MultiBuffer>,
17737        event: &multi_buffer::Event,
17738        window: &mut Window,
17739        cx: &mut Context<Self>,
17740    ) {
17741        match event {
17742            multi_buffer::Event::Edited {
17743                singleton_buffer_edited,
17744                edited_buffer: buffer_edited,
17745            } => {
17746                self.scrollbar_marker_state.dirty = true;
17747                self.active_indent_guides_state.dirty = true;
17748                self.refresh_active_diagnostics(cx);
17749                self.refresh_code_actions(window, cx);
17750                self.refresh_selected_text_highlights(true, window, cx);
17751                refresh_matching_bracket_highlights(self, window, cx);
17752                if self.has_active_inline_completion() {
17753                    self.update_visible_inline_completion(window, cx);
17754                }
17755                if let Some(buffer) = buffer_edited {
17756                    let buffer_id = buffer.read(cx).remote_id();
17757                    if !self.registered_buffers.contains_key(&buffer_id) {
17758                        if let Some(project) = self.project.as_ref() {
17759                            project.update(cx, |project, cx| {
17760                                self.registered_buffers.insert(
17761                                    buffer_id,
17762                                    project.register_buffer_with_language_servers(&buffer, cx),
17763                                );
17764                            })
17765                        }
17766                    }
17767                }
17768                cx.emit(EditorEvent::BufferEdited);
17769                cx.emit(SearchEvent::MatchesInvalidated);
17770                if *singleton_buffer_edited {
17771                    if let Some(project) = &self.project {
17772                        #[allow(clippy::mutable_key_type)]
17773                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17774                            multibuffer
17775                                .all_buffers()
17776                                .into_iter()
17777                                .filter_map(|buffer| {
17778                                    buffer.update(cx, |buffer, cx| {
17779                                        let language = buffer.language()?;
17780                                        let should_discard = project.update(cx, |project, cx| {
17781                                            project.is_local()
17782                                                && !project.has_language_servers_for(buffer, cx)
17783                                        });
17784                                        should_discard.not().then_some(language.clone())
17785                                    })
17786                                })
17787                                .collect::<HashSet<_>>()
17788                        });
17789                        if !languages_affected.is_empty() {
17790                            self.refresh_inlay_hints(
17791                                InlayHintRefreshReason::BufferEdited(languages_affected),
17792                                cx,
17793                            );
17794                        }
17795                    }
17796                }
17797
17798                let Some(project) = &self.project else { return };
17799                let (telemetry, is_via_ssh) = {
17800                    let project = project.read(cx);
17801                    let telemetry = project.client().telemetry().clone();
17802                    let is_via_ssh = project.is_via_ssh();
17803                    (telemetry, is_via_ssh)
17804                };
17805                refresh_linked_ranges(self, window, cx);
17806                telemetry.log_edit_event("editor", is_via_ssh);
17807            }
17808            multi_buffer::Event::ExcerptsAdded {
17809                buffer,
17810                predecessor,
17811                excerpts,
17812            } => {
17813                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17814                let buffer_id = buffer.read(cx).remote_id();
17815                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17816                    if let Some(project) = &self.project {
17817                        update_uncommitted_diff_for_buffer(
17818                            cx.entity(),
17819                            project,
17820                            [buffer.clone()],
17821                            self.buffer.clone(),
17822                            cx,
17823                        )
17824                        .detach();
17825                    }
17826                }
17827                cx.emit(EditorEvent::ExcerptsAdded {
17828                    buffer: buffer.clone(),
17829                    predecessor: *predecessor,
17830                    excerpts: excerpts.clone(),
17831                });
17832                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17833            }
17834            multi_buffer::Event::ExcerptsRemoved {
17835                ids,
17836                removed_buffer_ids,
17837            } => {
17838                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17839                let buffer = self.buffer.read(cx);
17840                self.registered_buffers
17841                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17842                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17843                cx.emit(EditorEvent::ExcerptsRemoved {
17844                    ids: ids.clone(),
17845                    removed_buffer_ids: removed_buffer_ids.clone(),
17846                })
17847            }
17848            multi_buffer::Event::ExcerptsEdited {
17849                excerpt_ids,
17850                buffer_ids,
17851            } => {
17852                self.display_map.update(cx, |map, cx| {
17853                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17854                });
17855                cx.emit(EditorEvent::ExcerptsEdited {
17856                    ids: excerpt_ids.clone(),
17857                })
17858            }
17859            multi_buffer::Event::ExcerptsExpanded { ids } => {
17860                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17861                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17862            }
17863            multi_buffer::Event::Reparsed(buffer_id) => {
17864                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17865                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17866
17867                cx.emit(EditorEvent::Reparsed(*buffer_id));
17868            }
17869            multi_buffer::Event::DiffHunksToggled => {
17870                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17871            }
17872            multi_buffer::Event::LanguageChanged(buffer_id) => {
17873                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17874                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17875                cx.emit(EditorEvent::Reparsed(*buffer_id));
17876                cx.notify();
17877            }
17878            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17879            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17880            multi_buffer::Event::FileHandleChanged
17881            | multi_buffer::Event::Reloaded
17882            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17883            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17884            multi_buffer::Event::DiagnosticsUpdated => {
17885                self.refresh_active_diagnostics(cx);
17886                self.refresh_inline_diagnostics(true, window, cx);
17887                self.scrollbar_marker_state.dirty = true;
17888                cx.notify();
17889            }
17890            _ => {}
17891        };
17892    }
17893
17894    pub fn start_temporary_diff_override(&mut self) {
17895        self.load_diff_task.take();
17896        self.temporary_diff_override = true;
17897    }
17898
17899    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17900        self.temporary_diff_override = false;
17901        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17902        self.buffer.update(cx, |buffer, cx| {
17903            buffer.set_all_diff_hunks_collapsed(cx);
17904        });
17905
17906        if let Some(project) = self.project.clone() {
17907            self.load_diff_task = Some(
17908                update_uncommitted_diff_for_buffer(
17909                    cx.entity(),
17910                    &project,
17911                    self.buffer.read(cx).all_buffers(),
17912                    self.buffer.clone(),
17913                    cx,
17914                )
17915                .shared(),
17916            );
17917        }
17918    }
17919
17920    fn on_display_map_changed(
17921        &mut self,
17922        _: Entity<DisplayMap>,
17923        _: &mut Window,
17924        cx: &mut Context<Self>,
17925    ) {
17926        cx.notify();
17927    }
17928
17929    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17930        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17931        self.update_edit_prediction_settings(cx);
17932        self.refresh_inline_completion(true, false, window, cx);
17933        self.refresh_inlay_hints(
17934            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17935                self.selections.newest_anchor().head(),
17936                &self.buffer.read(cx).snapshot(cx),
17937                cx,
17938            )),
17939            cx,
17940        );
17941
17942        let old_cursor_shape = self.cursor_shape;
17943
17944        {
17945            let editor_settings = EditorSettings::get_global(cx);
17946            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17947            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17948            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17949            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17950        }
17951
17952        if old_cursor_shape != self.cursor_shape {
17953            cx.emit(EditorEvent::CursorShapeChanged);
17954        }
17955
17956        let project_settings = ProjectSettings::get_global(cx);
17957        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17958
17959        if self.mode.is_full() {
17960            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17961            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17962            if self.show_inline_diagnostics != show_inline_diagnostics {
17963                self.show_inline_diagnostics = show_inline_diagnostics;
17964                self.refresh_inline_diagnostics(false, window, cx);
17965            }
17966
17967            if self.git_blame_inline_enabled != inline_blame_enabled {
17968                self.toggle_git_blame_inline_internal(false, window, cx);
17969            }
17970        }
17971
17972        cx.notify();
17973    }
17974
17975    pub fn set_searchable(&mut self, searchable: bool) {
17976        self.searchable = searchable;
17977    }
17978
17979    pub fn searchable(&self) -> bool {
17980        self.searchable
17981    }
17982
17983    fn open_proposed_changes_editor(
17984        &mut self,
17985        _: &OpenProposedChangesEditor,
17986        window: &mut Window,
17987        cx: &mut Context<Self>,
17988    ) {
17989        let Some(workspace) = self.workspace() else {
17990            cx.propagate();
17991            return;
17992        };
17993
17994        let selections = self.selections.all::<usize>(cx);
17995        let multi_buffer = self.buffer.read(cx);
17996        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17997        let mut new_selections_by_buffer = HashMap::default();
17998        for selection in selections {
17999            for (buffer, range, _) in
18000                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18001            {
18002                let mut range = range.to_point(buffer);
18003                range.start.column = 0;
18004                range.end.column = buffer.line_len(range.end.row);
18005                new_selections_by_buffer
18006                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18007                    .or_insert(Vec::new())
18008                    .push(range)
18009            }
18010        }
18011
18012        let proposed_changes_buffers = new_selections_by_buffer
18013            .into_iter()
18014            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18015            .collect::<Vec<_>>();
18016        let proposed_changes_editor = cx.new(|cx| {
18017            ProposedChangesEditor::new(
18018                "Proposed changes",
18019                proposed_changes_buffers,
18020                self.project.clone(),
18021                window,
18022                cx,
18023            )
18024        });
18025
18026        window.defer(cx, move |window, cx| {
18027            workspace.update(cx, |workspace, cx| {
18028                workspace.active_pane().update(cx, |pane, cx| {
18029                    pane.add_item(
18030                        Box::new(proposed_changes_editor),
18031                        true,
18032                        true,
18033                        None,
18034                        window,
18035                        cx,
18036                    );
18037                });
18038            });
18039        });
18040    }
18041
18042    pub fn open_excerpts_in_split(
18043        &mut self,
18044        _: &OpenExcerptsSplit,
18045        window: &mut Window,
18046        cx: &mut Context<Self>,
18047    ) {
18048        self.open_excerpts_common(None, true, window, cx)
18049    }
18050
18051    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18052        self.open_excerpts_common(None, false, window, cx)
18053    }
18054
18055    fn open_excerpts_common(
18056        &mut self,
18057        jump_data: Option<JumpData>,
18058        split: bool,
18059        window: &mut Window,
18060        cx: &mut Context<Self>,
18061    ) {
18062        let Some(workspace) = self.workspace() else {
18063            cx.propagate();
18064            return;
18065        };
18066
18067        if self.buffer.read(cx).is_singleton() {
18068            cx.propagate();
18069            return;
18070        }
18071
18072        let mut new_selections_by_buffer = HashMap::default();
18073        match &jump_data {
18074            Some(JumpData::MultiBufferPoint {
18075                excerpt_id,
18076                position,
18077                anchor,
18078                line_offset_from_top,
18079            }) => {
18080                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18081                if let Some(buffer) = multi_buffer_snapshot
18082                    .buffer_id_for_excerpt(*excerpt_id)
18083                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18084                {
18085                    let buffer_snapshot = buffer.read(cx).snapshot();
18086                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18087                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18088                    } else {
18089                        buffer_snapshot.clip_point(*position, Bias::Left)
18090                    };
18091                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18092                    new_selections_by_buffer.insert(
18093                        buffer,
18094                        (
18095                            vec![jump_to_offset..jump_to_offset],
18096                            Some(*line_offset_from_top),
18097                        ),
18098                    );
18099                }
18100            }
18101            Some(JumpData::MultiBufferRow {
18102                row,
18103                line_offset_from_top,
18104            }) => {
18105                let point = MultiBufferPoint::new(row.0, 0);
18106                if let Some((buffer, buffer_point, _)) =
18107                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18108                {
18109                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18110                    new_selections_by_buffer
18111                        .entry(buffer)
18112                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18113                        .0
18114                        .push(buffer_offset..buffer_offset)
18115                }
18116            }
18117            None => {
18118                let selections = self.selections.all::<usize>(cx);
18119                let multi_buffer = self.buffer.read(cx);
18120                for selection in selections {
18121                    for (snapshot, range, _, anchor) in multi_buffer
18122                        .snapshot(cx)
18123                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18124                    {
18125                        if let Some(anchor) = anchor {
18126                            // selection is in a deleted hunk
18127                            let Some(buffer_id) = anchor.buffer_id else {
18128                                continue;
18129                            };
18130                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18131                                continue;
18132                            };
18133                            let offset = text::ToOffset::to_offset(
18134                                &anchor.text_anchor,
18135                                &buffer_handle.read(cx).snapshot(),
18136                            );
18137                            let range = offset..offset;
18138                            new_selections_by_buffer
18139                                .entry(buffer_handle)
18140                                .or_insert((Vec::new(), None))
18141                                .0
18142                                .push(range)
18143                        } else {
18144                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18145                            else {
18146                                continue;
18147                            };
18148                            new_selections_by_buffer
18149                                .entry(buffer_handle)
18150                                .or_insert((Vec::new(), None))
18151                                .0
18152                                .push(range)
18153                        }
18154                    }
18155                }
18156            }
18157        }
18158
18159        new_selections_by_buffer
18160            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18161
18162        if new_selections_by_buffer.is_empty() {
18163            return;
18164        }
18165
18166        // We defer the pane interaction because we ourselves are a workspace item
18167        // and activating a new item causes the pane to call a method on us reentrantly,
18168        // which panics if we're on the stack.
18169        window.defer(cx, move |window, cx| {
18170            workspace.update(cx, |workspace, cx| {
18171                let pane = if split {
18172                    workspace.adjacent_pane(window, cx)
18173                } else {
18174                    workspace.active_pane().clone()
18175                };
18176
18177                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18178                    let editor = buffer
18179                        .read(cx)
18180                        .file()
18181                        .is_none()
18182                        .then(|| {
18183                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18184                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18185                            // Instead, we try to activate the existing editor in the pane first.
18186                            let (editor, pane_item_index) =
18187                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18188                                    let editor = item.downcast::<Editor>()?;
18189                                    let singleton_buffer =
18190                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18191                                    if singleton_buffer == buffer {
18192                                        Some((editor, i))
18193                                    } else {
18194                                        None
18195                                    }
18196                                })?;
18197                            pane.update(cx, |pane, cx| {
18198                                pane.activate_item(pane_item_index, true, true, window, cx)
18199                            });
18200                            Some(editor)
18201                        })
18202                        .flatten()
18203                        .unwrap_or_else(|| {
18204                            workspace.open_project_item::<Self>(
18205                                pane.clone(),
18206                                buffer,
18207                                true,
18208                                true,
18209                                window,
18210                                cx,
18211                            )
18212                        });
18213
18214                    editor.update(cx, |editor, cx| {
18215                        let autoscroll = match scroll_offset {
18216                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18217                            None => Autoscroll::newest(),
18218                        };
18219                        let nav_history = editor.nav_history.take();
18220                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18221                            s.select_ranges(ranges);
18222                        });
18223                        editor.nav_history = nav_history;
18224                    });
18225                }
18226            })
18227        });
18228    }
18229
18230    // For now, don't allow opening excerpts in buffers that aren't backed by
18231    // regular project files.
18232    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18233        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18234    }
18235
18236    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18237        let snapshot = self.buffer.read(cx).read(cx);
18238        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18239        Some(
18240            ranges
18241                .iter()
18242                .map(move |range| {
18243                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18244                })
18245                .collect(),
18246        )
18247    }
18248
18249    fn selection_replacement_ranges(
18250        &self,
18251        range: Range<OffsetUtf16>,
18252        cx: &mut App,
18253    ) -> Vec<Range<OffsetUtf16>> {
18254        let selections = self.selections.all::<OffsetUtf16>(cx);
18255        let newest_selection = selections
18256            .iter()
18257            .max_by_key(|selection| selection.id)
18258            .unwrap();
18259        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18260        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18261        let snapshot = self.buffer.read(cx).read(cx);
18262        selections
18263            .into_iter()
18264            .map(|mut selection| {
18265                selection.start.0 =
18266                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18267                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18268                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18269                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18270            })
18271            .collect()
18272    }
18273
18274    fn report_editor_event(
18275        &self,
18276        event_type: &'static str,
18277        file_extension: Option<String>,
18278        cx: &App,
18279    ) {
18280        if cfg!(any(test, feature = "test-support")) {
18281            return;
18282        }
18283
18284        let Some(project) = &self.project else { return };
18285
18286        // If None, we are in a file without an extension
18287        let file = self
18288            .buffer
18289            .read(cx)
18290            .as_singleton()
18291            .and_then(|b| b.read(cx).file());
18292        let file_extension = file_extension.or(file
18293            .as_ref()
18294            .and_then(|file| Path::new(file.file_name(cx)).extension())
18295            .and_then(|e| e.to_str())
18296            .map(|a| a.to_string()));
18297
18298        let vim_mode = vim_enabled(cx);
18299
18300        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18301        let copilot_enabled = edit_predictions_provider
18302            == language::language_settings::EditPredictionProvider::Copilot;
18303        let copilot_enabled_for_language = self
18304            .buffer
18305            .read(cx)
18306            .language_settings(cx)
18307            .show_edit_predictions;
18308
18309        let project = project.read(cx);
18310        telemetry::event!(
18311            event_type,
18312            file_extension,
18313            vim_mode,
18314            copilot_enabled,
18315            copilot_enabled_for_language,
18316            edit_predictions_provider,
18317            is_via_ssh = project.is_via_ssh(),
18318        );
18319    }
18320
18321    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18322    /// with each line being an array of {text, highlight} objects.
18323    fn copy_highlight_json(
18324        &mut self,
18325        _: &CopyHighlightJson,
18326        window: &mut Window,
18327        cx: &mut Context<Self>,
18328    ) {
18329        #[derive(Serialize)]
18330        struct Chunk<'a> {
18331            text: String,
18332            highlight: Option<&'a str>,
18333        }
18334
18335        let snapshot = self.buffer.read(cx).snapshot(cx);
18336        let range = self
18337            .selected_text_range(false, window, cx)
18338            .and_then(|selection| {
18339                if selection.range.is_empty() {
18340                    None
18341                } else {
18342                    Some(selection.range)
18343                }
18344            })
18345            .unwrap_or_else(|| 0..snapshot.len());
18346
18347        let chunks = snapshot.chunks(range, true);
18348        let mut lines = Vec::new();
18349        let mut line: VecDeque<Chunk> = VecDeque::new();
18350
18351        let Some(style) = self.style.as_ref() else {
18352            return;
18353        };
18354
18355        for chunk in chunks {
18356            let highlight = chunk
18357                .syntax_highlight_id
18358                .and_then(|id| id.name(&style.syntax));
18359            let mut chunk_lines = chunk.text.split('\n').peekable();
18360            while let Some(text) = chunk_lines.next() {
18361                let mut merged_with_last_token = false;
18362                if let Some(last_token) = line.back_mut() {
18363                    if last_token.highlight == highlight {
18364                        last_token.text.push_str(text);
18365                        merged_with_last_token = true;
18366                    }
18367                }
18368
18369                if !merged_with_last_token {
18370                    line.push_back(Chunk {
18371                        text: text.into(),
18372                        highlight,
18373                    });
18374                }
18375
18376                if chunk_lines.peek().is_some() {
18377                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18378                        line.pop_front();
18379                    }
18380                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18381                        line.pop_back();
18382                    }
18383
18384                    lines.push(mem::take(&mut line));
18385                }
18386            }
18387        }
18388
18389        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18390            return;
18391        };
18392        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18393    }
18394
18395    pub fn open_context_menu(
18396        &mut self,
18397        _: &OpenContextMenu,
18398        window: &mut Window,
18399        cx: &mut Context<Self>,
18400    ) {
18401        self.request_autoscroll(Autoscroll::newest(), cx);
18402        let position = self.selections.newest_display(cx).start;
18403        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18404    }
18405
18406    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18407        &self.inlay_hint_cache
18408    }
18409
18410    pub fn replay_insert_event(
18411        &mut self,
18412        text: &str,
18413        relative_utf16_range: Option<Range<isize>>,
18414        window: &mut Window,
18415        cx: &mut Context<Self>,
18416    ) {
18417        if !self.input_enabled {
18418            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18419            return;
18420        }
18421        if let Some(relative_utf16_range) = relative_utf16_range {
18422            let selections = self.selections.all::<OffsetUtf16>(cx);
18423            self.change_selections(None, window, cx, |s| {
18424                let new_ranges = selections.into_iter().map(|range| {
18425                    let start = OffsetUtf16(
18426                        range
18427                            .head()
18428                            .0
18429                            .saturating_add_signed(relative_utf16_range.start),
18430                    );
18431                    let end = OffsetUtf16(
18432                        range
18433                            .head()
18434                            .0
18435                            .saturating_add_signed(relative_utf16_range.end),
18436                    );
18437                    start..end
18438                });
18439                s.select_ranges(new_ranges);
18440            });
18441        }
18442
18443        self.handle_input(text, window, cx);
18444    }
18445
18446    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18447        let Some(provider) = self.semantics_provider.as_ref() else {
18448            return false;
18449        };
18450
18451        let mut supports = false;
18452        self.buffer().update(cx, |this, cx| {
18453            this.for_each_buffer(|buffer| {
18454                supports |= provider.supports_inlay_hints(buffer, cx);
18455            });
18456        });
18457
18458        supports
18459    }
18460
18461    pub fn is_focused(&self, window: &Window) -> bool {
18462        self.focus_handle.is_focused(window)
18463    }
18464
18465    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18466        cx.emit(EditorEvent::Focused);
18467
18468        if let Some(descendant) = self
18469            .last_focused_descendant
18470            .take()
18471            .and_then(|descendant| descendant.upgrade())
18472        {
18473            window.focus(&descendant);
18474        } else {
18475            if let Some(blame) = self.blame.as_ref() {
18476                blame.update(cx, GitBlame::focus)
18477            }
18478
18479            self.blink_manager.update(cx, BlinkManager::enable);
18480            self.show_cursor_names(window, cx);
18481            self.buffer.update(cx, |buffer, cx| {
18482                buffer.finalize_last_transaction(cx);
18483                if self.leader_id.is_none() {
18484                    buffer.set_active_selections(
18485                        &self.selections.disjoint_anchors(),
18486                        self.selections.line_mode,
18487                        self.cursor_shape,
18488                        cx,
18489                    );
18490                }
18491            });
18492        }
18493    }
18494
18495    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18496        cx.emit(EditorEvent::FocusedIn)
18497    }
18498
18499    fn handle_focus_out(
18500        &mut self,
18501        event: FocusOutEvent,
18502        _window: &mut Window,
18503        cx: &mut Context<Self>,
18504    ) {
18505        if event.blurred != self.focus_handle {
18506            self.last_focused_descendant = Some(event.blurred);
18507        }
18508        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18509    }
18510
18511    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18512        self.blink_manager.update(cx, BlinkManager::disable);
18513        self.buffer
18514            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18515
18516        if let Some(blame) = self.blame.as_ref() {
18517            blame.update(cx, GitBlame::blur)
18518        }
18519        if !self.hover_state.focused(window, cx) {
18520            hide_hover(self, cx);
18521        }
18522        if !self
18523            .context_menu
18524            .borrow()
18525            .as_ref()
18526            .is_some_and(|context_menu| context_menu.focused(window, cx))
18527        {
18528            self.hide_context_menu(window, cx);
18529        }
18530        self.discard_inline_completion(false, cx);
18531        cx.emit(EditorEvent::Blurred);
18532        cx.notify();
18533    }
18534
18535    pub fn register_action<A: Action>(
18536        &mut self,
18537        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18538    ) -> Subscription {
18539        let id = self.next_editor_action_id.post_inc();
18540        let listener = Arc::new(listener);
18541        self.editor_actions.borrow_mut().insert(
18542            id,
18543            Box::new(move |window, _| {
18544                let listener = listener.clone();
18545                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18546                    let action = action.downcast_ref().unwrap();
18547                    if phase == DispatchPhase::Bubble {
18548                        listener(action, window, cx)
18549                    }
18550                })
18551            }),
18552        );
18553
18554        let editor_actions = self.editor_actions.clone();
18555        Subscription::new(move || {
18556            editor_actions.borrow_mut().remove(&id);
18557        })
18558    }
18559
18560    pub fn file_header_size(&self) -> u32 {
18561        FILE_HEADER_HEIGHT
18562    }
18563
18564    pub fn restore(
18565        &mut self,
18566        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18567        window: &mut Window,
18568        cx: &mut Context<Self>,
18569    ) {
18570        let workspace = self.workspace();
18571        let project = self.project.as_ref();
18572        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18573            let mut tasks = Vec::new();
18574            for (buffer_id, changes) in revert_changes {
18575                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18576                    buffer.update(cx, |buffer, cx| {
18577                        buffer.edit(
18578                            changes
18579                                .into_iter()
18580                                .map(|(range, text)| (range, text.to_string())),
18581                            None,
18582                            cx,
18583                        );
18584                    });
18585
18586                    if let Some(project) =
18587                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18588                    {
18589                        project.update(cx, |project, cx| {
18590                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18591                        })
18592                    }
18593                }
18594            }
18595            tasks
18596        });
18597        cx.spawn_in(window, async move |_, cx| {
18598            for (buffer, task) in save_tasks {
18599                let result = task.await;
18600                if result.is_err() {
18601                    let Some(path) = buffer
18602                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18603                        .ok()
18604                    else {
18605                        continue;
18606                    };
18607                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18608                        let Some(task) = cx
18609                            .update_window_entity(&workspace, |workspace, window, cx| {
18610                                workspace
18611                                    .open_path_preview(path, None, false, false, false, window, cx)
18612                            })
18613                            .ok()
18614                        else {
18615                            continue;
18616                        };
18617                        task.await.log_err();
18618                    }
18619                }
18620            }
18621        })
18622        .detach();
18623        self.change_selections(None, window, cx, |selections| selections.refresh());
18624    }
18625
18626    pub fn to_pixel_point(
18627        &self,
18628        source: multi_buffer::Anchor,
18629        editor_snapshot: &EditorSnapshot,
18630        window: &mut Window,
18631    ) -> Option<gpui::Point<Pixels>> {
18632        let source_point = source.to_display_point(editor_snapshot);
18633        self.display_to_pixel_point(source_point, editor_snapshot, window)
18634    }
18635
18636    pub fn display_to_pixel_point(
18637        &self,
18638        source: DisplayPoint,
18639        editor_snapshot: &EditorSnapshot,
18640        window: &mut Window,
18641    ) -> Option<gpui::Point<Pixels>> {
18642        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18643        let text_layout_details = self.text_layout_details(window);
18644        let scroll_top = text_layout_details
18645            .scroll_anchor
18646            .scroll_position(editor_snapshot)
18647            .y;
18648
18649        if source.row().as_f32() < scroll_top.floor() {
18650            return None;
18651        }
18652        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18653        let source_y = line_height * (source.row().as_f32() - scroll_top);
18654        Some(gpui::Point::new(source_x, source_y))
18655    }
18656
18657    pub fn has_visible_completions_menu(&self) -> bool {
18658        !self.edit_prediction_preview_is_active()
18659            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18660                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18661            })
18662    }
18663
18664    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18665        self.addons
18666            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18667    }
18668
18669    pub fn unregister_addon<T: Addon>(&mut self) {
18670        self.addons.remove(&std::any::TypeId::of::<T>());
18671    }
18672
18673    pub fn addon<T: Addon>(&self) -> Option<&T> {
18674        let type_id = std::any::TypeId::of::<T>();
18675        self.addons
18676            .get(&type_id)
18677            .and_then(|item| item.to_any().downcast_ref::<T>())
18678    }
18679
18680    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18681        let type_id = std::any::TypeId::of::<T>();
18682        self.addons
18683            .get_mut(&type_id)
18684            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18685    }
18686
18687    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18688        let text_layout_details = self.text_layout_details(window);
18689        let style = &text_layout_details.editor_style;
18690        let font_id = window.text_system().resolve_font(&style.text.font());
18691        let font_size = style.text.font_size.to_pixels(window.rem_size());
18692        let line_height = style.text.line_height_in_pixels(window.rem_size());
18693        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18694
18695        gpui::Size::new(em_width, line_height)
18696    }
18697
18698    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18699        self.load_diff_task.clone()
18700    }
18701
18702    fn read_metadata_from_db(
18703        &mut self,
18704        item_id: u64,
18705        workspace_id: WorkspaceId,
18706        window: &mut Window,
18707        cx: &mut Context<Editor>,
18708    ) {
18709        if self.is_singleton(cx)
18710            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18711        {
18712            let buffer_snapshot = OnceCell::new();
18713
18714            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18715                if !folds.is_empty() {
18716                    let snapshot =
18717                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18718                    self.fold_ranges(
18719                        folds
18720                            .into_iter()
18721                            .map(|(start, end)| {
18722                                snapshot.clip_offset(start, Bias::Left)
18723                                    ..snapshot.clip_offset(end, Bias::Right)
18724                            })
18725                            .collect(),
18726                        false,
18727                        window,
18728                        cx,
18729                    );
18730                }
18731            }
18732
18733            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18734                if !selections.is_empty() {
18735                    let snapshot =
18736                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18737                    self.change_selections(None, window, cx, |s| {
18738                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18739                            snapshot.clip_offset(start, Bias::Left)
18740                                ..snapshot.clip_offset(end, Bias::Right)
18741                        }));
18742                    });
18743                }
18744            };
18745        }
18746
18747        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18748    }
18749}
18750
18751fn vim_enabled(cx: &App) -> bool {
18752    cx.global::<SettingsStore>()
18753        .raw_user_settings()
18754        .get("vim_mode")
18755        == Some(&serde_json::Value::Bool(true))
18756}
18757
18758// Consider user intent and default settings
18759fn choose_completion_range(
18760    completion: &Completion,
18761    intent: CompletionIntent,
18762    buffer: &Entity<Buffer>,
18763    cx: &mut Context<Editor>,
18764) -> Range<usize> {
18765    fn should_replace(
18766        completion: &Completion,
18767        insert_range: &Range<text::Anchor>,
18768        intent: CompletionIntent,
18769        completion_mode_setting: LspInsertMode,
18770        buffer: &Buffer,
18771    ) -> bool {
18772        // specific actions take precedence over settings
18773        match intent {
18774            CompletionIntent::CompleteWithInsert => return false,
18775            CompletionIntent::CompleteWithReplace => return true,
18776            CompletionIntent::Complete | CompletionIntent::Compose => {}
18777        }
18778
18779        match completion_mode_setting {
18780            LspInsertMode::Insert => false,
18781            LspInsertMode::Replace => true,
18782            LspInsertMode::ReplaceSubsequence => {
18783                let mut text_to_replace = buffer.chars_for_range(
18784                    buffer.anchor_before(completion.replace_range.start)
18785                        ..buffer.anchor_after(completion.replace_range.end),
18786                );
18787                let mut completion_text = completion.new_text.chars();
18788
18789                // is `text_to_replace` a subsequence of `completion_text`
18790                text_to_replace
18791                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18792            }
18793            LspInsertMode::ReplaceSuffix => {
18794                let range_after_cursor = insert_range.end..completion.replace_range.end;
18795
18796                let text_after_cursor = buffer
18797                    .text_for_range(
18798                        buffer.anchor_before(range_after_cursor.start)
18799                            ..buffer.anchor_after(range_after_cursor.end),
18800                    )
18801                    .collect::<String>();
18802                completion.new_text.ends_with(&text_after_cursor)
18803            }
18804        }
18805    }
18806
18807    let buffer = buffer.read(cx);
18808
18809    if let CompletionSource::Lsp {
18810        insert_range: Some(insert_range),
18811        ..
18812    } = &completion.source
18813    {
18814        let completion_mode_setting =
18815            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18816                .completions
18817                .lsp_insert_mode;
18818
18819        if !should_replace(
18820            completion,
18821            &insert_range,
18822            intent,
18823            completion_mode_setting,
18824            buffer,
18825        ) {
18826            return insert_range.to_offset(buffer);
18827        }
18828    }
18829
18830    completion.replace_range.to_offset(buffer)
18831}
18832
18833fn insert_extra_newline_brackets(
18834    buffer: &MultiBufferSnapshot,
18835    range: Range<usize>,
18836    language: &language::LanguageScope,
18837) -> bool {
18838    let leading_whitespace_len = buffer
18839        .reversed_chars_at(range.start)
18840        .take_while(|c| c.is_whitespace() && *c != '\n')
18841        .map(|c| c.len_utf8())
18842        .sum::<usize>();
18843    let trailing_whitespace_len = buffer
18844        .chars_at(range.end)
18845        .take_while(|c| c.is_whitespace() && *c != '\n')
18846        .map(|c| c.len_utf8())
18847        .sum::<usize>();
18848    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18849
18850    language.brackets().any(|(pair, enabled)| {
18851        let pair_start = pair.start.trim_end();
18852        let pair_end = pair.end.trim_start();
18853
18854        enabled
18855            && pair.newline
18856            && buffer.contains_str_at(range.end, pair_end)
18857            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18858    })
18859}
18860
18861fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18862    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18863        [(buffer, range, _)] => (*buffer, range.clone()),
18864        _ => return false,
18865    };
18866    let pair = {
18867        let mut result: Option<BracketMatch> = None;
18868
18869        for pair in buffer
18870            .all_bracket_ranges(range.clone())
18871            .filter(move |pair| {
18872                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18873            })
18874        {
18875            let len = pair.close_range.end - pair.open_range.start;
18876
18877            if let Some(existing) = &result {
18878                let existing_len = existing.close_range.end - existing.open_range.start;
18879                if len > existing_len {
18880                    continue;
18881                }
18882            }
18883
18884            result = Some(pair);
18885        }
18886
18887        result
18888    };
18889    let Some(pair) = pair else {
18890        return false;
18891    };
18892    pair.newline_only
18893        && buffer
18894            .chars_for_range(pair.open_range.end..range.start)
18895            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18896            .all(|c| c.is_whitespace() && c != '\n')
18897}
18898
18899fn update_uncommitted_diff_for_buffer(
18900    editor: Entity<Editor>,
18901    project: &Entity<Project>,
18902    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18903    buffer: Entity<MultiBuffer>,
18904    cx: &mut App,
18905) -> Task<()> {
18906    let mut tasks = Vec::new();
18907    project.update(cx, |project, cx| {
18908        for buffer in buffers {
18909            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18910                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18911            }
18912        }
18913    });
18914    cx.spawn(async move |cx| {
18915        let diffs = future::join_all(tasks).await;
18916        if editor
18917            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18918            .unwrap_or(false)
18919        {
18920            return;
18921        }
18922
18923        buffer
18924            .update(cx, |buffer, cx| {
18925                for diff in diffs.into_iter().flatten() {
18926                    buffer.add_diff(diff, cx);
18927                }
18928            })
18929            .ok();
18930    })
18931}
18932
18933fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18934    let tab_size = tab_size.get() as usize;
18935    let mut width = offset;
18936
18937    for ch in text.chars() {
18938        width += if ch == '\t' {
18939            tab_size - (width % tab_size)
18940        } else {
18941            1
18942        };
18943    }
18944
18945    width - offset
18946}
18947
18948#[cfg(test)]
18949mod tests {
18950    use super::*;
18951
18952    #[test]
18953    fn test_string_size_with_expanded_tabs() {
18954        let nz = |val| NonZeroU32::new(val).unwrap();
18955        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18956        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18957        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18958        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18959        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18960        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18961        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18962        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18963    }
18964}
18965
18966/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18967struct WordBreakingTokenizer<'a> {
18968    input: &'a str,
18969}
18970
18971impl<'a> WordBreakingTokenizer<'a> {
18972    fn new(input: &'a str) -> Self {
18973        Self { input }
18974    }
18975}
18976
18977fn is_char_ideographic(ch: char) -> bool {
18978    use unicode_script::Script::*;
18979    use unicode_script::UnicodeScript;
18980    matches!(ch.script(), Han | Tangut | Yi)
18981}
18982
18983fn is_grapheme_ideographic(text: &str) -> bool {
18984    text.chars().any(is_char_ideographic)
18985}
18986
18987fn is_grapheme_whitespace(text: &str) -> bool {
18988    text.chars().any(|x| x.is_whitespace())
18989}
18990
18991fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18992    text.chars().next().map_or(false, |ch| {
18993        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18994    })
18995}
18996
18997#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18998enum WordBreakToken<'a> {
18999    Word { token: &'a str, grapheme_len: usize },
19000    InlineWhitespace { token: &'a str, grapheme_len: usize },
19001    Newline,
19002}
19003
19004impl<'a> Iterator for WordBreakingTokenizer<'a> {
19005    /// Yields a span, the count of graphemes in the token, and whether it was
19006    /// whitespace. Note that it also breaks at word boundaries.
19007    type Item = WordBreakToken<'a>;
19008
19009    fn next(&mut self) -> Option<Self::Item> {
19010        use unicode_segmentation::UnicodeSegmentation;
19011        if self.input.is_empty() {
19012            return None;
19013        }
19014
19015        let mut iter = self.input.graphemes(true).peekable();
19016        let mut offset = 0;
19017        let mut grapheme_len = 0;
19018        if let Some(first_grapheme) = iter.next() {
19019            let is_newline = first_grapheme == "\n";
19020            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19021            offset += first_grapheme.len();
19022            grapheme_len += 1;
19023            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19024                if let Some(grapheme) = iter.peek().copied() {
19025                    if should_stay_with_preceding_ideograph(grapheme) {
19026                        offset += grapheme.len();
19027                        grapheme_len += 1;
19028                    }
19029                }
19030            } else {
19031                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19032                let mut next_word_bound = words.peek().copied();
19033                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19034                    next_word_bound = words.next();
19035                }
19036                while let Some(grapheme) = iter.peek().copied() {
19037                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19038                        break;
19039                    };
19040                    if is_grapheme_whitespace(grapheme) != is_whitespace
19041                        || (grapheme == "\n") != is_newline
19042                    {
19043                        break;
19044                    };
19045                    offset += grapheme.len();
19046                    grapheme_len += 1;
19047                    iter.next();
19048                }
19049            }
19050            let token = &self.input[..offset];
19051            self.input = &self.input[offset..];
19052            if token == "\n" {
19053                Some(WordBreakToken::Newline)
19054            } else if is_whitespace {
19055                Some(WordBreakToken::InlineWhitespace {
19056                    token,
19057                    grapheme_len,
19058                })
19059            } else {
19060                Some(WordBreakToken::Word {
19061                    token,
19062                    grapheme_len,
19063                })
19064            }
19065        } else {
19066            None
19067        }
19068    }
19069}
19070
19071#[test]
19072fn test_word_breaking_tokenizer() {
19073    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19074        ("", &[]),
19075        ("  ", &[whitespace("  ", 2)]),
19076        ("Ʒ", &[word("Ʒ", 1)]),
19077        ("Ǽ", &[word("Ǽ", 1)]),
19078        ("", &[word("", 1)]),
19079        ("⋑⋑", &[word("⋑⋑", 2)]),
19080        (
19081            "原理,进而",
19082            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19083        ),
19084        (
19085            "hello world",
19086            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19087        ),
19088        (
19089            "hello, world",
19090            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19091        ),
19092        (
19093            "  hello world",
19094            &[
19095                whitespace("  ", 2),
19096                word("hello", 5),
19097                whitespace(" ", 1),
19098                word("world", 5),
19099            ],
19100        ),
19101        (
19102            "这是什么 \n 钢笔",
19103            &[
19104                word("", 1),
19105                word("", 1),
19106                word("", 1),
19107                word("", 1),
19108                whitespace(" ", 1),
19109                newline(),
19110                whitespace(" ", 1),
19111                word("", 1),
19112                word("", 1),
19113            ],
19114        ),
19115        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19116    ];
19117
19118    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19119        WordBreakToken::Word {
19120            token,
19121            grapheme_len,
19122        }
19123    }
19124
19125    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19126        WordBreakToken::InlineWhitespace {
19127            token,
19128            grapheme_len,
19129        }
19130    }
19131
19132    fn newline() -> WordBreakToken<'static> {
19133        WordBreakToken::Newline
19134    }
19135
19136    for (input, result) in tests {
19137        assert_eq!(
19138            WordBreakingTokenizer::new(input)
19139                .collect::<Vec<_>>()
19140                .as_slice(),
19141            *result,
19142        );
19143    }
19144}
19145
19146fn wrap_with_prefix(
19147    line_prefix: String,
19148    unwrapped_text: String,
19149    wrap_column: usize,
19150    tab_size: NonZeroU32,
19151    preserve_existing_whitespace: bool,
19152) -> String {
19153    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19154    let mut wrapped_text = String::new();
19155    let mut current_line = line_prefix.clone();
19156
19157    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19158    let mut current_line_len = line_prefix_len;
19159    let mut in_whitespace = false;
19160    for token in tokenizer {
19161        let have_preceding_whitespace = in_whitespace;
19162        match token {
19163            WordBreakToken::Word {
19164                token,
19165                grapheme_len,
19166            } => {
19167                in_whitespace = false;
19168                if current_line_len + grapheme_len > wrap_column
19169                    && current_line_len != line_prefix_len
19170                {
19171                    wrapped_text.push_str(current_line.trim_end());
19172                    wrapped_text.push('\n');
19173                    current_line.truncate(line_prefix.len());
19174                    current_line_len = line_prefix_len;
19175                }
19176                current_line.push_str(token);
19177                current_line_len += grapheme_len;
19178            }
19179            WordBreakToken::InlineWhitespace {
19180                mut token,
19181                mut grapheme_len,
19182            } => {
19183                in_whitespace = true;
19184                if have_preceding_whitespace && !preserve_existing_whitespace {
19185                    continue;
19186                }
19187                if !preserve_existing_whitespace {
19188                    token = " ";
19189                    grapheme_len = 1;
19190                }
19191                if current_line_len + grapheme_len > wrap_column {
19192                    wrapped_text.push_str(current_line.trim_end());
19193                    wrapped_text.push('\n');
19194                    current_line.truncate(line_prefix.len());
19195                    current_line_len = line_prefix_len;
19196                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19197                    current_line.push_str(token);
19198                    current_line_len += grapheme_len;
19199                }
19200            }
19201            WordBreakToken::Newline => {
19202                in_whitespace = true;
19203                if preserve_existing_whitespace {
19204                    wrapped_text.push_str(current_line.trim_end());
19205                    wrapped_text.push('\n');
19206                    current_line.truncate(line_prefix.len());
19207                    current_line_len = line_prefix_len;
19208                } else if have_preceding_whitespace {
19209                    continue;
19210                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19211                {
19212                    wrapped_text.push_str(current_line.trim_end());
19213                    wrapped_text.push('\n');
19214                    current_line.truncate(line_prefix.len());
19215                    current_line_len = line_prefix_len;
19216                } else if current_line_len != line_prefix_len {
19217                    current_line.push(' ');
19218                    current_line_len += 1;
19219                }
19220            }
19221        }
19222    }
19223
19224    if !current_line.is_empty() {
19225        wrapped_text.push_str(&current_line);
19226    }
19227    wrapped_text
19228}
19229
19230#[test]
19231fn test_wrap_with_prefix() {
19232    assert_eq!(
19233        wrap_with_prefix(
19234            "# ".to_string(),
19235            "abcdefg".to_string(),
19236            4,
19237            NonZeroU32::new(4).unwrap(),
19238            false,
19239        ),
19240        "# abcdefg"
19241    );
19242    assert_eq!(
19243        wrap_with_prefix(
19244            "".to_string(),
19245            "\thello world".to_string(),
19246            8,
19247            NonZeroU32::new(4).unwrap(),
19248            false,
19249        ),
19250        "hello\nworld"
19251    );
19252    assert_eq!(
19253        wrap_with_prefix(
19254            "// ".to_string(),
19255            "xx \nyy zz aa bb cc".to_string(),
19256            12,
19257            NonZeroU32::new(4).unwrap(),
19258            false,
19259        ),
19260        "// xx yy zz\n// aa bb cc"
19261    );
19262    assert_eq!(
19263        wrap_with_prefix(
19264            String::new(),
19265            "这是什么 \n 钢笔".to_string(),
19266            3,
19267            NonZeroU32::new(4).unwrap(),
19268            false,
19269        ),
19270        "这是什\n么 钢\n"
19271    );
19272}
19273
19274pub trait CollaborationHub {
19275    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19276    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19277    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19278}
19279
19280impl CollaborationHub for Entity<Project> {
19281    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19282        self.read(cx).collaborators()
19283    }
19284
19285    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19286        self.read(cx).user_store().read(cx).participant_indices()
19287    }
19288
19289    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19290        let this = self.read(cx);
19291        let user_ids = this.collaborators().values().map(|c| c.user_id);
19292        this.user_store().read_with(cx, |user_store, cx| {
19293            user_store.participant_names(user_ids, cx)
19294        })
19295    }
19296}
19297
19298pub trait SemanticsProvider {
19299    fn hover(
19300        &self,
19301        buffer: &Entity<Buffer>,
19302        position: text::Anchor,
19303        cx: &mut App,
19304    ) -> Option<Task<Vec<project::Hover>>>;
19305
19306    fn inline_values(
19307        &self,
19308        buffer_handle: Entity<Buffer>,
19309        range: Range<text::Anchor>,
19310        cx: &mut App,
19311    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19312
19313    fn inlay_hints(
19314        &self,
19315        buffer_handle: Entity<Buffer>,
19316        range: Range<text::Anchor>,
19317        cx: &mut App,
19318    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19319
19320    fn resolve_inlay_hint(
19321        &self,
19322        hint: InlayHint,
19323        buffer_handle: Entity<Buffer>,
19324        server_id: LanguageServerId,
19325        cx: &mut App,
19326    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19327
19328    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19329
19330    fn document_highlights(
19331        &self,
19332        buffer: &Entity<Buffer>,
19333        position: text::Anchor,
19334        cx: &mut App,
19335    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19336
19337    fn definitions(
19338        &self,
19339        buffer: &Entity<Buffer>,
19340        position: text::Anchor,
19341        kind: GotoDefinitionKind,
19342        cx: &mut App,
19343    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19344
19345    fn range_for_rename(
19346        &self,
19347        buffer: &Entity<Buffer>,
19348        position: text::Anchor,
19349        cx: &mut App,
19350    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19351
19352    fn perform_rename(
19353        &self,
19354        buffer: &Entity<Buffer>,
19355        position: text::Anchor,
19356        new_name: String,
19357        cx: &mut App,
19358    ) -> Option<Task<Result<ProjectTransaction>>>;
19359}
19360
19361pub trait CompletionProvider {
19362    fn completions(
19363        &self,
19364        excerpt_id: ExcerptId,
19365        buffer: &Entity<Buffer>,
19366        buffer_position: text::Anchor,
19367        trigger: CompletionContext,
19368        window: &mut Window,
19369        cx: &mut Context<Editor>,
19370    ) -> Task<Result<Option<Vec<Completion>>>>;
19371
19372    fn resolve_completions(
19373        &self,
19374        buffer: Entity<Buffer>,
19375        completion_indices: Vec<usize>,
19376        completions: Rc<RefCell<Box<[Completion]>>>,
19377        cx: &mut Context<Editor>,
19378    ) -> Task<Result<bool>>;
19379
19380    fn apply_additional_edits_for_completion(
19381        &self,
19382        _buffer: Entity<Buffer>,
19383        _completions: Rc<RefCell<Box<[Completion]>>>,
19384        _completion_index: usize,
19385        _push_to_history: bool,
19386        _cx: &mut Context<Editor>,
19387    ) -> Task<Result<Option<language::Transaction>>> {
19388        Task::ready(Ok(None))
19389    }
19390
19391    fn is_completion_trigger(
19392        &self,
19393        buffer: &Entity<Buffer>,
19394        position: language::Anchor,
19395        text: &str,
19396        trigger_in_words: bool,
19397        cx: &mut Context<Editor>,
19398    ) -> bool;
19399
19400    fn sort_completions(&self) -> bool {
19401        true
19402    }
19403
19404    fn filter_completions(&self) -> bool {
19405        true
19406    }
19407}
19408
19409pub trait CodeActionProvider {
19410    fn id(&self) -> Arc<str>;
19411
19412    fn code_actions(
19413        &self,
19414        buffer: &Entity<Buffer>,
19415        range: Range<text::Anchor>,
19416        window: &mut Window,
19417        cx: &mut App,
19418    ) -> Task<Result<Vec<CodeAction>>>;
19419
19420    fn apply_code_action(
19421        &self,
19422        buffer_handle: Entity<Buffer>,
19423        action: CodeAction,
19424        excerpt_id: ExcerptId,
19425        push_to_history: bool,
19426        window: &mut Window,
19427        cx: &mut App,
19428    ) -> Task<Result<ProjectTransaction>>;
19429}
19430
19431impl CodeActionProvider for Entity<Project> {
19432    fn id(&self) -> Arc<str> {
19433        "project".into()
19434    }
19435
19436    fn code_actions(
19437        &self,
19438        buffer: &Entity<Buffer>,
19439        range: Range<text::Anchor>,
19440        _window: &mut Window,
19441        cx: &mut App,
19442    ) -> Task<Result<Vec<CodeAction>>> {
19443        self.update(cx, |project, cx| {
19444            let code_lens = project.code_lens(buffer, range.clone(), cx);
19445            let code_actions = project.code_actions(buffer, range, None, cx);
19446            cx.background_spawn(async move {
19447                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19448                Ok(code_lens
19449                    .context("code lens fetch")?
19450                    .into_iter()
19451                    .chain(code_actions.context("code action fetch")?)
19452                    .collect())
19453            })
19454        })
19455    }
19456
19457    fn apply_code_action(
19458        &self,
19459        buffer_handle: Entity<Buffer>,
19460        action: CodeAction,
19461        _excerpt_id: ExcerptId,
19462        push_to_history: bool,
19463        _window: &mut Window,
19464        cx: &mut App,
19465    ) -> Task<Result<ProjectTransaction>> {
19466        self.update(cx, |project, cx| {
19467            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19468        })
19469    }
19470}
19471
19472fn snippet_completions(
19473    project: &Project,
19474    buffer: &Entity<Buffer>,
19475    buffer_position: text::Anchor,
19476    cx: &mut App,
19477) -> Task<Result<Vec<Completion>>> {
19478    let languages = buffer.read(cx).languages_at(buffer_position);
19479    let snippet_store = project.snippets().read(cx);
19480
19481    let scopes: Vec<_> = languages
19482        .iter()
19483        .filter_map(|language| {
19484            let language_name = language.lsp_id();
19485            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19486
19487            if snippets.is_empty() {
19488                None
19489            } else {
19490                Some((language.default_scope(), snippets))
19491            }
19492        })
19493        .collect();
19494
19495    if scopes.is_empty() {
19496        return Task::ready(Ok(vec![]));
19497    }
19498
19499    let snapshot = buffer.read(cx).text_snapshot();
19500    let chars: String = snapshot
19501        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19502        .collect();
19503    let executor = cx.background_executor().clone();
19504
19505    cx.background_spawn(async move {
19506        let mut all_results: Vec<Completion> = Vec::new();
19507        for (scope, snippets) in scopes.into_iter() {
19508            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19509            let mut last_word = chars
19510                .chars()
19511                .take_while(|c| classifier.is_word(*c))
19512                .collect::<String>();
19513            last_word = last_word.chars().rev().collect();
19514
19515            if last_word.is_empty() {
19516                return Ok(vec![]);
19517            }
19518
19519            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19520            let to_lsp = |point: &text::Anchor| {
19521                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19522                point_to_lsp(end)
19523            };
19524            let lsp_end = to_lsp(&buffer_position);
19525
19526            let candidates = snippets
19527                .iter()
19528                .enumerate()
19529                .flat_map(|(ix, snippet)| {
19530                    snippet
19531                        .prefix
19532                        .iter()
19533                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19534                })
19535                .collect::<Vec<StringMatchCandidate>>();
19536
19537            let mut matches = fuzzy::match_strings(
19538                &candidates,
19539                &last_word,
19540                last_word.chars().any(|c| c.is_uppercase()),
19541                100,
19542                &Default::default(),
19543                executor.clone(),
19544            )
19545            .await;
19546
19547            // Remove all candidates where the query's start does not match the start of any word in the candidate
19548            if let Some(query_start) = last_word.chars().next() {
19549                matches.retain(|string_match| {
19550                    split_words(&string_match.string).any(|word| {
19551                        // Check that the first codepoint of the word as lowercase matches the first
19552                        // codepoint of the query as lowercase
19553                        word.chars()
19554                            .flat_map(|codepoint| codepoint.to_lowercase())
19555                            .zip(query_start.to_lowercase())
19556                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19557                    })
19558                });
19559            }
19560
19561            let matched_strings = matches
19562                .into_iter()
19563                .map(|m| m.string)
19564                .collect::<HashSet<_>>();
19565
19566            let mut result: Vec<Completion> = snippets
19567                .iter()
19568                .filter_map(|snippet| {
19569                    let matching_prefix = snippet
19570                        .prefix
19571                        .iter()
19572                        .find(|prefix| matched_strings.contains(*prefix))?;
19573                    let start = as_offset - last_word.len();
19574                    let start = snapshot.anchor_before(start);
19575                    let range = start..buffer_position;
19576                    let lsp_start = to_lsp(&start);
19577                    let lsp_range = lsp::Range {
19578                        start: lsp_start,
19579                        end: lsp_end,
19580                    };
19581                    Some(Completion {
19582                        replace_range: range,
19583                        new_text: snippet.body.clone(),
19584                        source: CompletionSource::Lsp {
19585                            insert_range: None,
19586                            server_id: LanguageServerId(usize::MAX),
19587                            resolved: true,
19588                            lsp_completion: Box::new(lsp::CompletionItem {
19589                                label: snippet.prefix.first().unwrap().clone(),
19590                                kind: Some(CompletionItemKind::SNIPPET),
19591                                label_details: snippet.description.as_ref().map(|description| {
19592                                    lsp::CompletionItemLabelDetails {
19593                                        detail: Some(description.clone()),
19594                                        description: None,
19595                                    }
19596                                }),
19597                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19598                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19599                                    lsp::InsertReplaceEdit {
19600                                        new_text: snippet.body.clone(),
19601                                        insert: lsp_range,
19602                                        replace: lsp_range,
19603                                    },
19604                                )),
19605                                filter_text: Some(snippet.body.clone()),
19606                                sort_text: Some(char::MAX.to_string()),
19607                                ..lsp::CompletionItem::default()
19608                            }),
19609                            lsp_defaults: None,
19610                        },
19611                        label: CodeLabel {
19612                            text: matching_prefix.clone(),
19613                            runs: Vec::new(),
19614                            filter_range: 0..matching_prefix.len(),
19615                        },
19616                        icon_path: None,
19617                        documentation: snippet.description.clone().map(|description| {
19618                            CompletionDocumentation::SingleLine(description.into())
19619                        }),
19620                        insert_text_mode: None,
19621                        confirm: None,
19622                    })
19623                })
19624                .collect();
19625
19626            all_results.append(&mut result);
19627        }
19628
19629        Ok(all_results)
19630    })
19631}
19632
19633impl CompletionProvider for Entity<Project> {
19634    fn completions(
19635        &self,
19636        _excerpt_id: ExcerptId,
19637        buffer: &Entity<Buffer>,
19638        buffer_position: text::Anchor,
19639        options: CompletionContext,
19640        _window: &mut Window,
19641        cx: &mut Context<Editor>,
19642    ) -> Task<Result<Option<Vec<Completion>>>> {
19643        self.update(cx, |project, cx| {
19644            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19645            let project_completions = project.completions(buffer, buffer_position, options, cx);
19646            cx.background_spawn(async move {
19647                let snippets_completions = snippets.await?;
19648                match project_completions.await? {
19649                    Some(mut completions) => {
19650                        completions.extend(snippets_completions);
19651                        Ok(Some(completions))
19652                    }
19653                    None => {
19654                        if snippets_completions.is_empty() {
19655                            Ok(None)
19656                        } else {
19657                            Ok(Some(snippets_completions))
19658                        }
19659                    }
19660                }
19661            })
19662        })
19663    }
19664
19665    fn resolve_completions(
19666        &self,
19667        buffer: Entity<Buffer>,
19668        completion_indices: Vec<usize>,
19669        completions: Rc<RefCell<Box<[Completion]>>>,
19670        cx: &mut Context<Editor>,
19671    ) -> Task<Result<bool>> {
19672        self.update(cx, |project, cx| {
19673            project.lsp_store().update(cx, |lsp_store, cx| {
19674                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19675            })
19676        })
19677    }
19678
19679    fn apply_additional_edits_for_completion(
19680        &self,
19681        buffer: Entity<Buffer>,
19682        completions: Rc<RefCell<Box<[Completion]>>>,
19683        completion_index: usize,
19684        push_to_history: bool,
19685        cx: &mut Context<Editor>,
19686    ) -> Task<Result<Option<language::Transaction>>> {
19687        self.update(cx, |project, cx| {
19688            project.lsp_store().update(cx, |lsp_store, cx| {
19689                lsp_store.apply_additional_edits_for_completion(
19690                    buffer,
19691                    completions,
19692                    completion_index,
19693                    push_to_history,
19694                    cx,
19695                )
19696            })
19697        })
19698    }
19699
19700    fn is_completion_trigger(
19701        &self,
19702        buffer: &Entity<Buffer>,
19703        position: language::Anchor,
19704        text: &str,
19705        trigger_in_words: bool,
19706        cx: &mut Context<Editor>,
19707    ) -> bool {
19708        let mut chars = text.chars();
19709        let char = if let Some(char) = chars.next() {
19710            char
19711        } else {
19712            return false;
19713        };
19714        if chars.next().is_some() {
19715            return false;
19716        }
19717
19718        let buffer = buffer.read(cx);
19719        let snapshot = buffer.snapshot();
19720        if !snapshot.settings_at(position, cx).show_completions_on_input {
19721            return false;
19722        }
19723        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19724        if trigger_in_words && classifier.is_word(char) {
19725            return true;
19726        }
19727
19728        buffer.completion_triggers().contains(text)
19729    }
19730}
19731
19732impl SemanticsProvider for Entity<Project> {
19733    fn hover(
19734        &self,
19735        buffer: &Entity<Buffer>,
19736        position: text::Anchor,
19737        cx: &mut App,
19738    ) -> Option<Task<Vec<project::Hover>>> {
19739        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19740    }
19741
19742    fn document_highlights(
19743        &self,
19744        buffer: &Entity<Buffer>,
19745        position: text::Anchor,
19746        cx: &mut App,
19747    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19748        Some(self.update(cx, |project, cx| {
19749            project.document_highlights(buffer, position, cx)
19750        }))
19751    }
19752
19753    fn definitions(
19754        &self,
19755        buffer: &Entity<Buffer>,
19756        position: text::Anchor,
19757        kind: GotoDefinitionKind,
19758        cx: &mut App,
19759    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19760        Some(self.update(cx, |project, cx| match kind {
19761            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19762            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19763            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19764            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19765        }))
19766    }
19767
19768    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19769        // TODO: make this work for remote projects
19770        self.update(cx, |project, cx| {
19771            if project
19772                .active_debug_session(cx)
19773                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19774            {
19775                return true;
19776            }
19777
19778            buffer.update(cx, |buffer, cx| {
19779                project.any_language_server_supports_inlay_hints(buffer, cx)
19780            })
19781        })
19782    }
19783
19784    fn inline_values(
19785        &self,
19786        buffer_handle: Entity<Buffer>,
19787        range: Range<text::Anchor>,
19788        cx: &mut App,
19789    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19790        self.update(cx, |project, cx| {
19791            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19792
19793            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19794        })
19795    }
19796
19797    fn inlay_hints(
19798        &self,
19799        buffer_handle: Entity<Buffer>,
19800        range: Range<text::Anchor>,
19801        cx: &mut App,
19802    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19803        Some(self.update(cx, |project, cx| {
19804            project.inlay_hints(buffer_handle, range, cx)
19805        }))
19806    }
19807
19808    fn resolve_inlay_hint(
19809        &self,
19810        hint: InlayHint,
19811        buffer_handle: Entity<Buffer>,
19812        server_id: LanguageServerId,
19813        cx: &mut App,
19814    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19815        Some(self.update(cx, |project, cx| {
19816            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19817        }))
19818    }
19819
19820    fn range_for_rename(
19821        &self,
19822        buffer: &Entity<Buffer>,
19823        position: text::Anchor,
19824        cx: &mut App,
19825    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19826        Some(self.update(cx, |project, cx| {
19827            let buffer = buffer.clone();
19828            let task = project.prepare_rename(buffer.clone(), position, cx);
19829            cx.spawn(async move |_, cx| {
19830                Ok(match task.await? {
19831                    PrepareRenameResponse::Success(range) => Some(range),
19832                    PrepareRenameResponse::InvalidPosition => None,
19833                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19834                        // Fallback on using TreeSitter info to determine identifier range
19835                        buffer.update(cx, |buffer, _| {
19836                            let snapshot = buffer.snapshot();
19837                            let (range, kind) = snapshot.surrounding_word(position);
19838                            if kind != Some(CharKind::Word) {
19839                                return None;
19840                            }
19841                            Some(
19842                                snapshot.anchor_before(range.start)
19843                                    ..snapshot.anchor_after(range.end),
19844                            )
19845                        })?
19846                    }
19847                })
19848            })
19849        }))
19850    }
19851
19852    fn perform_rename(
19853        &self,
19854        buffer: &Entity<Buffer>,
19855        position: text::Anchor,
19856        new_name: String,
19857        cx: &mut App,
19858    ) -> Option<Task<Result<ProjectTransaction>>> {
19859        Some(self.update(cx, |project, cx| {
19860            project.perform_rename(buffer.clone(), position, new_name, cx)
19861        }))
19862    }
19863}
19864
19865fn inlay_hint_settings(
19866    location: Anchor,
19867    snapshot: &MultiBufferSnapshot,
19868    cx: &mut Context<Editor>,
19869) -> InlayHintSettings {
19870    let file = snapshot.file_at(location);
19871    let language = snapshot.language_at(location).map(|l| l.name());
19872    language_settings(language, file, cx).inlay_hints
19873}
19874
19875fn consume_contiguous_rows(
19876    contiguous_row_selections: &mut Vec<Selection<Point>>,
19877    selection: &Selection<Point>,
19878    display_map: &DisplaySnapshot,
19879    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19880) -> (MultiBufferRow, MultiBufferRow) {
19881    contiguous_row_selections.push(selection.clone());
19882    let start_row = MultiBufferRow(selection.start.row);
19883    let mut end_row = ending_row(selection, display_map);
19884
19885    while let Some(next_selection) = selections.peek() {
19886        if next_selection.start.row <= end_row.0 {
19887            end_row = ending_row(next_selection, display_map);
19888            contiguous_row_selections.push(selections.next().unwrap().clone());
19889        } else {
19890            break;
19891        }
19892    }
19893    (start_row, end_row)
19894}
19895
19896fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19897    if next_selection.end.column > 0 || next_selection.is_empty() {
19898        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19899    } else {
19900        MultiBufferRow(next_selection.end.row)
19901    }
19902}
19903
19904impl EditorSnapshot {
19905    pub fn remote_selections_in_range<'a>(
19906        &'a self,
19907        range: &'a Range<Anchor>,
19908        collaboration_hub: &dyn CollaborationHub,
19909        cx: &'a App,
19910    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19911        let participant_names = collaboration_hub.user_names(cx);
19912        let participant_indices = collaboration_hub.user_participant_indices(cx);
19913        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19914        let collaborators_by_replica_id = collaborators_by_peer_id
19915            .iter()
19916            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19917            .collect::<HashMap<_, _>>();
19918        self.buffer_snapshot
19919            .selections_in_range(range, false)
19920            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19921                if replica_id == AGENT_REPLICA_ID {
19922                    Some(RemoteSelection {
19923                        replica_id,
19924                        selection,
19925                        cursor_shape,
19926                        line_mode,
19927                        collaborator_id: CollaboratorId::Agent,
19928                        user_name: Some("Agent".into()),
19929                        color: cx.theme().players().agent(),
19930                    })
19931                } else {
19932                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19933                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19934                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19935                    Some(RemoteSelection {
19936                        replica_id,
19937                        selection,
19938                        cursor_shape,
19939                        line_mode,
19940                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19941                        user_name,
19942                        color: if let Some(index) = participant_index {
19943                            cx.theme().players().color_for_participant(index.0)
19944                        } else {
19945                            cx.theme().players().absent()
19946                        },
19947                    })
19948                }
19949            })
19950    }
19951
19952    pub fn hunks_for_ranges(
19953        &self,
19954        ranges: impl IntoIterator<Item = Range<Point>>,
19955    ) -> Vec<MultiBufferDiffHunk> {
19956        let mut hunks = Vec::new();
19957        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19958            HashMap::default();
19959        for query_range in ranges {
19960            let query_rows =
19961                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19962            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19963                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19964            ) {
19965                // Include deleted hunks that are adjacent to the query range, because
19966                // otherwise they would be missed.
19967                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19968                if hunk.status().is_deleted() {
19969                    intersects_range |= hunk.row_range.start == query_rows.end;
19970                    intersects_range |= hunk.row_range.end == query_rows.start;
19971                }
19972                if intersects_range {
19973                    if !processed_buffer_rows
19974                        .entry(hunk.buffer_id)
19975                        .or_default()
19976                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19977                    {
19978                        continue;
19979                    }
19980                    hunks.push(hunk);
19981                }
19982            }
19983        }
19984
19985        hunks
19986    }
19987
19988    fn display_diff_hunks_for_rows<'a>(
19989        &'a self,
19990        display_rows: Range<DisplayRow>,
19991        folded_buffers: &'a HashSet<BufferId>,
19992    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19993        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19994        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19995
19996        self.buffer_snapshot
19997            .diff_hunks_in_range(buffer_start..buffer_end)
19998            .filter_map(|hunk| {
19999                if folded_buffers.contains(&hunk.buffer_id) {
20000                    return None;
20001                }
20002
20003                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20004                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20005
20006                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20007                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20008
20009                let display_hunk = if hunk_display_start.column() != 0 {
20010                    DisplayDiffHunk::Folded {
20011                        display_row: hunk_display_start.row(),
20012                    }
20013                } else {
20014                    let mut end_row = hunk_display_end.row();
20015                    if hunk_display_end.column() > 0 {
20016                        end_row.0 += 1;
20017                    }
20018                    let is_created_file = hunk.is_created_file();
20019                    DisplayDiffHunk::Unfolded {
20020                        status: hunk.status(),
20021                        diff_base_byte_range: hunk.diff_base_byte_range,
20022                        display_row_range: hunk_display_start.row()..end_row,
20023                        multi_buffer_range: Anchor::range_in_buffer(
20024                            hunk.excerpt_id,
20025                            hunk.buffer_id,
20026                            hunk.buffer_range,
20027                        ),
20028                        is_created_file,
20029                    }
20030                };
20031
20032                Some(display_hunk)
20033            })
20034    }
20035
20036    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20037        self.display_snapshot.buffer_snapshot.language_at(position)
20038    }
20039
20040    pub fn is_focused(&self) -> bool {
20041        self.is_focused
20042    }
20043
20044    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20045        self.placeholder_text.as_ref()
20046    }
20047
20048    pub fn scroll_position(&self) -> gpui::Point<f32> {
20049        self.scroll_anchor.scroll_position(&self.display_snapshot)
20050    }
20051
20052    fn gutter_dimensions(
20053        &self,
20054        font_id: FontId,
20055        font_size: Pixels,
20056        max_line_number_width: Pixels,
20057        cx: &App,
20058    ) -> Option<GutterDimensions> {
20059        if !self.show_gutter {
20060            return None;
20061        }
20062
20063        let descent = cx.text_system().descent(font_id, font_size);
20064        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20065        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20066
20067        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20068            matches!(
20069                ProjectSettings::get_global(cx).git.git_gutter,
20070                Some(GitGutterSetting::TrackedFiles)
20071            )
20072        });
20073        let gutter_settings = EditorSettings::get_global(cx).gutter;
20074        let show_line_numbers = self
20075            .show_line_numbers
20076            .unwrap_or(gutter_settings.line_numbers);
20077        let line_gutter_width = if show_line_numbers {
20078            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20079            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20080            max_line_number_width.max(min_width_for_number_on_gutter)
20081        } else {
20082            0.0.into()
20083        };
20084
20085        let show_code_actions = self
20086            .show_code_actions
20087            .unwrap_or(gutter_settings.code_actions);
20088
20089        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20090        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20091
20092        let git_blame_entries_width =
20093            self.git_blame_gutter_max_author_length
20094                .map(|max_author_length| {
20095                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20096                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20097
20098                    /// The number of characters to dedicate to gaps and margins.
20099                    const SPACING_WIDTH: usize = 4;
20100
20101                    let max_char_count = max_author_length.min(renderer.max_author_length())
20102                        + ::git::SHORT_SHA_LENGTH
20103                        + MAX_RELATIVE_TIMESTAMP.len()
20104                        + SPACING_WIDTH;
20105
20106                    em_advance * max_char_count
20107                });
20108
20109        let is_singleton = self.buffer_snapshot.is_singleton();
20110
20111        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20112        left_padding += if !is_singleton {
20113            em_width * 4.0
20114        } else if show_code_actions || show_runnables || show_breakpoints {
20115            em_width * 3.0
20116        } else if show_git_gutter && show_line_numbers {
20117            em_width * 2.0
20118        } else if show_git_gutter || show_line_numbers {
20119            em_width
20120        } else {
20121            px(0.)
20122        };
20123
20124        let shows_folds = is_singleton && gutter_settings.folds;
20125
20126        let right_padding = if shows_folds && show_line_numbers {
20127            em_width * 4.0
20128        } else if shows_folds || (!is_singleton && show_line_numbers) {
20129            em_width * 3.0
20130        } else if show_line_numbers {
20131            em_width
20132        } else {
20133            px(0.)
20134        };
20135
20136        Some(GutterDimensions {
20137            left_padding,
20138            right_padding,
20139            width: line_gutter_width + left_padding + right_padding,
20140            margin: -descent,
20141            git_blame_entries_width,
20142        })
20143    }
20144
20145    pub fn render_crease_toggle(
20146        &self,
20147        buffer_row: MultiBufferRow,
20148        row_contains_cursor: bool,
20149        editor: Entity<Editor>,
20150        window: &mut Window,
20151        cx: &mut App,
20152    ) -> Option<AnyElement> {
20153        let folded = self.is_line_folded(buffer_row);
20154        let mut is_foldable = false;
20155
20156        if let Some(crease) = self
20157            .crease_snapshot
20158            .query_row(buffer_row, &self.buffer_snapshot)
20159        {
20160            is_foldable = true;
20161            match crease {
20162                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20163                    if let Some(render_toggle) = render_toggle {
20164                        let toggle_callback =
20165                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20166                                if folded {
20167                                    editor.update(cx, |editor, cx| {
20168                                        editor.fold_at(buffer_row, window, cx)
20169                                    });
20170                                } else {
20171                                    editor.update(cx, |editor, cx| {
20172                                        editor.unfold_at(buffer_row, window, cx)
20173                                    });
20174                                }
20175                            });
20176                        return Some((render_toggle)(
20177                            buffer_row,
20178                            folded,
20179                            toggle_callback,
20180                            window,
20181                            cx,
20182                        ));
20183                    }
20184                }
20185            }
20186        }
20187
20188        is_foldable |= self.starts_indent(buffer_row);
20189
20190        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20191            Some(
20192                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20193                    .toggle_state(folded)
20194                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20195                        if folded {
20196                            this.unfold_at(buffer_row, window, cx);
20197                        } else {
20198                            this.fold_at(buffer_row, window, cx);
20199                        }
20200                    }))
20201                    .into_any_element(),
20202            )
20203        } else {
20204            None
20205        }
20206    }
20207
20208    pub fn render_crease_trailer(
20209        &self,
20210        buffer_row: MultiBufferRow,
20211        window: &mut Window,
20212        cx: &mut App,
20213    ) -> Option<AnyElement> {
20214        let folded = self.is_line_folded(buffer_row);
20215        if let Crease::Inline { render_trailer, .. } = self
20216            .crease_snapshot
20217            .query_row(buffer_row, &self.buffer_snapshot)?
20218        {
20219            let render_trailer = render_trailer.as_ref()?;
20220            Some(render_trailer(buffer_row, folded, window, cx))
20221        } else {
20222            None
20223        }
20224    }
20225}
20226
20227impl Deref for EditorSnapshot {
20228    type Target = DisplaySnapshot;
20229
20230    fn deref(&self) -> &Self::Target {
20231        &self.display_snapshot
20232    }
20233}
20234
20235#[derive(Clone, Debug, PartialEq, Eq)]
20236pub enum EditorEvent {
20237    InputIgnored {
20238        text: Arc<str>,
20239    },
20240    InputHandled {
20241        utf16_range_to_replace: Option<Range<isize>>,
20242        text: Arc<str>,
20243    },
20244    ExcerptsAdded {
20245        buffer: Entity<Buffer>,
20246        predecessor: ExcerptId,
20247        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20248    },
20249    ExcerptsRemoved {
20250        ids: Vec<ExcerptId>,
20251        removed_buffer_ids: Vec<BufferId>,
20252    },
20253    BufferFoldToggled {
20254        ids: Vec<ExcerptId>,
20255        folded: bool,
20256    },
20257    ExcerptsEdited {
20258        ids: Vec<ExcerptId>,
20259    },
20260    ExcerptsExpanded {
20261        ids: Vec<ExcerptId>,
20262    },
20263    BufferEdited,
20264    Edited {
20265        transaction_id: clock::Lamport,
20266    },
20267    Reparsed(BufferId),
20268    Focused,
20269    FocusedIn,
20270    Blurred,
20271    DirtyChanged,
20272    Saved,
20273    TitleChanged,
20274    DiffBaseChanged,
20275    SelectionsChanged {
20276        local: bool,
20277    },
20278    ScrollPositionChanged {
20279        local: bool,
20280        autoscroll: bool,
20281    },
20282    Closed,
20283    TransactionUndone {
20284        transaction_id: clock::Lamport,
20285    },
20286    TransactionBegun {
20287        transaction_id: clock::Lamport,
20288    },
20289    Reloaded,
20290    CursorShapeChanged,
20291    PushedToNavHistory {
20292        anchor: Anchor,
20293        is_deactivate: bool,
20294    },
20295}
20296
20297impl EventEmitter<EditorEvent> for Editor {}
20298
20299impl Focusable for Editor {
20300    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20301        self.focus_handle.clone()
20302    }
20303}
20304
20305impl Render for Editor {
20306    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20307        let settings = ThemeSettings::get_global(cx);
20308
20309        let mut text_style = match self.mode {
20310            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20311                color: cx.theme().colors().editor_foreground,
20312                font_family: settings.ui_font.family.clone(),
20313                font_features: settings.ui_font.features.clone(),
20314                font_fallbacks: settings.ui_font.fallbacks.clone(),
20315                font_size: rems(0.875).into(),
20316                font_weight: settings.ui_font.weight,
20317                line_height: relative(settings.buffer_line_height.value()),
20318                ..Default::default()
20319            },
20320            EditorMode::Full { .. } => TextStyle {
20321                color: cx.theme().colors().editor_foreground,
20322                font_family: settings.buffer_font.family.clone(),
20323                font_features: settings.buffer_font.features.clone(),
20324                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20325                font_size: settings.buffer_font_size(cx).into(),
20326                font_weight: settings.buffer_font.weight,
20327                line_height: relative(settings.buffer_line_height.value()),
20328                ..Default::default()
20329            },
20330        };
20331        if let Some(text_style_refinement) = &self.text_style_refinement {
20332            text_style.refine(text_style_refinement)
20333        }
20334
20335        let background = match self.mode {
20336            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20337            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20338            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20339        };
20340
20341        EditorElement::new(
20342            &cx.entity(),
20343            EditorStyle {
20344                background,
20345                horizontal_padding: Pixels::default(),
20346                local_player: cx.theme().players().local(),
20347                text: text_style,
20348                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20349                syntax: cx.theme().syntax().clone(),
20350                status: cx.theme().status().clone(),
20351                inlay_hints_style: make_inlay_hints_style(cx),
20352                inline_completion_styles: make_suggestion_styles(cx),
20353                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20354            },
20355        )
20356    }
20357}
20358
20359impl EntityInputHandler for Editor {
20360    fn text_for_range(
20361        &mut self,
20362        range_utf16: Range<usize>,
20363        adjusted_range: &mut Option<Range<usize>>,
20364        _: &mut Window,
20365        cx: &mut Context<Self>,
20366    ) -> Option<String> {
20367        let snapshot = self.buffer.read(cx).read(cx);
20368        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20369        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20370        if (start.0..end.0) != range_utf16 {
20371            adjusted_range.replace(start.0..end.0);
20372        }
20373        Some(snapshot.text_for_range(start..end).collect())
20374    }
20375
20376    fn selected_text_range(
20377        &mut self,
20378        ignore_disabled_input: bool,
20379        _: &mut Window,
20380        cx: &mut Context<Self>,
20381    ) -> Option<UTF16Selection> {
20382        // Prevent the IME menu from appearing when holding down an alphabetic key
20383        // while input is disabled.
20384        if !ignore_disabled_input && !self.input_enabled {
20385            return None;
20386        }
20387
20388        let selection = self.selections.newest::<OffsetUtf16>(cx);
20389        let range = selection.range();
20390
20391        Some(UTF16Selection {
20392            range: range.start.0..range.end.0,
20393            reversed: selection.reversed,
20394        })
20395    }
20396
20397    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20398        let snapshot = self.buffer.read(cx).read(cx);
20399        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20400        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20401    }
20402
20403    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20404        self.clear_highlights::<InputComposition>(cx);
20405        self.ime_transaction.take();
20406    }
20407
20408    fn replace_text_in_range(
20409        &mut self,
20410        range_utf16: Option<Range<usize>>,
20411        text: &str,
20412        window: &mut Window,
20413        cx: &mut Context<Self>,
20414    ) {
20415        if !self.input_enabled {
20416            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20417            return;
20418        }
20419
20420        self.transact(window, cx, |this, window, cx| {
20421            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20422                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20423                Some(this.selection_replacement_ranges(range_utf16, cx))
20424            } else {
20425                this.marked_text_ranges(cx)
20426            };
20427
20428            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20429                let newest_selection_id = this.selections.newest_anchor().id;
20430                this.selections
20431                    .all::<OffsetUtf16>(cx)
20432                    .iter()
20433                    .zip(ranges_to_replace.iter())
20434                    .find_map(|(selection, range)| {
20435                        if selection.id == newest_selection_id {
20436                            Some(
20437                                (range.start.0 as isize - selection.head().0 as isize)
20438                                    ..(range.end.0 as isize - selection.head().0 as isize),
20439                            )
20440                        } else {
20441                            None
20442                        }
20443                    })
20444            });
20445
20446            cx.emit(EditorEvent::InputHandled {
20447                utf16_range_to_replace: range_to_replace,
20448                text: text.into(),
20449            });
20450
20451            if let Some(new_selected_ranges) = new_selected_ranges {
20452                this.change_selections(None, window, cx, |selections| {
20453                    selections.select_ranges(new_selected_ranges)
20454                });
20455                this.backspace(&Default::default(), window, cx);
20456            }
20457
20458            this.handle_input(text, window, cx);
20459        });
20460
20461        if let Some(transaction) = self.ime_transaction {
20462            self.buffer.update(cx, |buffer, cx| {
20463                buffer.group_until_transaction(transaction, cx);
20464            });
20465        }
20466
20467        self.unmark_text(window, cx);
20468    }
20469
20470    fn replace_and_mark_text_in_range(
20471        &mut self,
20472        range_utf16: Option<Range<usize>>,
20473        text: &str,
20474        new_selected_range_utf16: Option<Range<usize>>,
20475        window: &mut Window,
20476        cx: &mut Context<Self>,
20477    ) {
20478        if !self.input_enabled {
20479            return;
20480        }
20481
20482        let transaction = self.transact(window, cx, |this, window, cx| {
20483            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20484                let snapshot = this.buffer.read(cx).read(cx);
20485                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20486                    for marked_range in &mut marked_ranges {
20487                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20488                        marked_range.start.0 += relative_range_utf16.start;
20489                        marked_range.start =
20490                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20491                        marked_range.end =
20492                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20493                    }
20494                }
20495                Some(marked_ranges)
20496            } else if let Some(range_utf16) = range_utf16 {
20497                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20498                Some(this.selection_replacement_ranges(range_utf16, cx))
20499            } else {
20500                None
20501            };
20502
20503            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20504                let newest_selection_id = this.selections.newest_anchor().id;
20505                this.selections
20506                    .all::<OffsetUtf16>(cx)
20507                    .iter()
20508                    .zip(ranges_to_replace.iter())
20509                    .find_map(|(selection, range)| {
20510                        if selection.id == newest_selection_id {
20511                            Some(
20512                                (range.start.0 as isize - selection.head().0 as isize)
20513                                    ..(range.end.0 as isize - selection.head().0 as isize),
20514                            )
20515                        } else {
20516                            None
20517                        }
20518                    })
20519            });
20520
20521            cx.emit(EditorEvent::InputHandled {
20522                utf16_range_to_replace: range_to_replace,
20523                text: text.into(),
20524            });
20525
20526            if let Some(ranges) = ranges_to_replace {
20527                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20528            }
20529
20530            let marked_ranges = {
20531                let snapshot = this.buffer.read(cx).read(cx);
20532                this.selections
20533                    .disjoint_anchors()
20534                    .iter()
20535                    .map(|selection| {
20536                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20537                    })
20538                    .collect::<Vec<_>>()
20539            };
20540
20541            if text.is_empty() {
20542                this.unmark_text(window, cx);
20543            } else {
20544                this.highlight_text::<InputComposition>(
20545                    marked_ranges.clone(),
20546                    HighlightStyle {
20547                        underline: Some(UnderlineStyle {
20548                            thickness: px(1.),
20549                            color: None,
20550                            wavy: false,
20551                        }),
20552                        ..Default::default()
20553                    },
20554                    cx,
20555                );
20556            }
20557
20558            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20559            let use_autoclose = this.use_autoclose;
20560            let use_auto_surround = this.use_auto_surround;
20561            this.set_use_autoclose(false);
20562            this.set_use_auto_surround(false);
20563            this.handle_input(text, window, cx);
20564            this.set_use_autoclose(use_autoclose);
20565            this.set_use_auto_surround(use_auto_surround);
20566
20567            if let Some(new_selected_range) = new_selected_range_utf16 {
20568                let snapshot = this.buffer.read(cx).read(cx);
20569                let new_selected_ranges = marked_ranges
20570                    .into_iter()
20571                    .map(|marked_range| {
20572                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20573                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20574                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20575                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20576                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20577                    })
20578                    .collect::<Vec<_>>();
20579
20580                drop(snapshot);
20581                this.change_selections(None, window, cx, |selections| {
20582                    selections.select_ranges(new_selected_ranges)
20583                });
20584            }
20585        });
20586
20587        self.ime_transaction = self.ime_transaction.or(transaction);
20588        if let Some(transaction) = self.ime_transaction {
20589            self.buffer.update(cx, |buffer, cx| {
20590                buffer.group_until_transaction(transaction, cx);
20591            });
20592        }
20593
20594        if self.text_highlights::<InputComposition>(cx).is_none() {
20595            self.ime_transaction.take();
20596        }
20597    }
20598
20599    fn bounds_for_range(
20600        &mut self,
20601        range_utf16: Range<usize>,
20602        element_bounds: gpui::Bounds<Pixels>,
20603        window: &mut Window,
20604        cx: &mut Context<Self>,
20605    ) -> Option<gpui::Bounds<Pixels>> {
20606        let text_layout_details = self.text_layout_details(window);
20607        let gpui::Size {
20608            width: em_width,
20609            height: line_height,
20610        } = self.character_size(window);
20611
20612        let snapshot = self.snapshot(window, cx);
20613        let scroll_position = snapshot.scroll_position();
20614        let scroll_left = scroll_position.x * em_width;
20615
20616        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20617        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20618            + self.gutter_dimensions.width
20619            + self.gutter_dimensions.margin;
20620        let y = line_height * (start.row().as_f32() - scroll_position.y);
20621
20622        Some(Bounds {
20623            origin: element_bounds.origin + point(x, y),
20624            size: size(em_width, line_height),
20625        })
20626    }
20627
20628    fn character_index_for_point(
20629        &mut self,
20630        point: gpui::Point<Pixels>,
20631        _window: &mut Window,
20632        _cx: &mut Context<Self>,
20633    ) -> Option<usize> {
20634        let position_map = self.last_position_map.as_ref()?;
20635        if !position_map.text_hitbox.contains(&point) {
20636            return None;
20637        }
20638        let display_point = position_map.point_for_position(point).previous_valid;
20639        let anchor = position_map
20640            .snapshot
20641            .display_point_to_anchor(display_point, Bias::Left);
20642        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20643        Some(utf16_offset.0)
20644    }
20645}
20646
20647trait SelectionExt {
20648    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20649    fn spanned_rows(
20650        &self,
20651        include_end_if_at_line_start: bool,
20652        map: &DisplaySnapshot,
20653    ) -> Range<MultiBufferRow>;
20654}
20655
20656impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20657    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20658        let start = self
20659            .start
20660            .to_point(&map.buffer_snapshot)
20661            .to_display_point(map);
20662        let end = self
20663            .end
20664            .to_point(&map.buffer_snapshot)
20665            .to_display_point(map);
20666        if self.reversed {
20667            end..start
20668        } else {
20669            start..end
20670        }
20671    }
20672
20673    fn spanned_rows(
20674        &self,
20675        include_end_if_at_line_start: bool,
20676        map: &DisplaySnapshot,
20677    ) -> Range<MultiBufferRow> {
20678        let start = self.start.to_point(&map.buffer_snapshot);
20679        let mut end = self.end.to_point(&map.buffer_snapshot);
20680        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20681            end.row -= 1;
20682        }
20683
20684        let buffer_start = map.prev_line_boundary(start).0;
20685        let buffer_end = map.next_line_boundary(end).0;
20686        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20687    }
20688}
20689
20690impl<T: InvalidationRegion> InvalidationStack<T> {
20691    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20692    where
20693        S: Clone + ToOffset,
20694    {
20695        while let Some(region) = self.last() {
20696            let all_selections_inside_invalidation_ranges =
20697                if selections.len() == region.ranges().len() {
20698                    selections
20699                        .iter()
20700                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20701                        .all(|(selection, invalidation_range)| {
20702                            let head = selection.head().to_offset(buffer);
20703                            invalidation_range.start <= head && invalidation_range.end >= head
20704                        })
20705                } else {
20706                    false
20707                };
20708
20709            if all_selections_inside_invalidation_ranges {
20710                break;
20711            } else {
20712                self.pop();
20713            }
20714        }
20715    }
20716}
20717
20718impl<T> Default for InvalidationStack<T> {
20719    fn default() -> Self {
20720        Self(Default::default())
20721    }
20722}
20723
20724impl<T> Deref for InvalidationStack<T> {
20725    type Target = Vec<T>;
20726
20727    fn deref(&self) -> &Self::Target {
20728        &self.0
20729    }
20730}
20731
20732impl<T> DerefMut for InvalidationStack<T> {
20733    fn deref_mut(&mut self) -> &mut Self::Target {
20734        &mut self.0
20735    }
20736}
20737
20738impl InvalidationRegion for SnippetState {
20739    fn ranges(&self) -> &[Range<Anchor>] {
20740        &self.ranges[self.active_index]
20741    }
20742}
20743
20744fn inline_completion_edit_text(
20745    current_snapshot: &BufferSnapshot,
20746    edits: &[(Range<Anchor>, String)],
20747    edit_preview: &EditPreview,
20748    include_deletions: bool,
20749    cx: &App,
20750) -> HighlightedText {
20751    let edits = edits
20752        .iter()
20753        .map(|(anchor, text)| {
20754            (
20755                anchor.start.text_anchor..anchor.end.text_anchor,
20756                text.clone(),
20757            )
20758        })
20759        .collect::<Vec<_>>();
20760
20761    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20762}
20763
20764pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20765    match severity {
20766        DiagnosticSeverity::ERROR => colors.error,
20767        DiagnosticSeverity::WARNING => colors.warning,
20768        DiagnosticSeverity::INFORMATION => colors.info,
20769        DiagnosticSeverity::HINT => colors.info,
20770        _ => colors.ignored,
20771    }
20772}
20773
20774pub fn styled_runs_for_code_label<'a>(
20775    label: &'a CodeLabel,
20776    syntax_theme: &'a theme::SyntaxTheme,
20777) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20778    let fade_out = HighlightStyle {
20779        fade_out: Some(0.35),
20780        ..Default::default()
20781    };
20782
20783    let mut prev_end = label.filter_range.end;
20784    label
20785        .runs
20786        .iter()
20787        .enumerate()
20788        .flat_map(move |(ix, (range, highlight_id))| {
20789            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20790                style
20791            } else {
20792                return Default::default();
20793            };
20794            let mut muted_style = style;
20795            muted_style.highlight(fade_out);
20796
20797            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20798            if range.start >= label.filter_range.end {
20799                if range.start > prev_end {
20800                    runs.push((prev_end..range.start, fade_out));
20801                }
20802                runs.push((range.clone(), muted_style));
20803            } else if range.end <= label.filter_range.end {
20804                runs.push((range.clone(), style));
20805            } else {
20806                runs.push((range.start..label.filter_range.end, style));
20807                runs.push((label.filter_range.end..range.end, muted_style));
20808            }
20809            prev_end = cmp::max(prev_end, range.end);
20810
20811            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20812                runs.push((prev_end..label.text.len(), fade_out));
20813            }
20814
20815            runs
20816        })
20817}
20818
20819pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20820    let mut prev_index = 0;
20821    let mut prev_codepoint: Option<char> = None;
20822    text.char_indices()
20823        .chain([(text.len(), '\0')])
20824        .filter_map(move |(index, codepoint)| {
20825            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20826            let is_boundary = index == text.len()
20827                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20828                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20829            if is_boundary {
20830                let chunk = &text[prev_index..index];
20831                prev_index = index;
20832                Some(chunk)
20833            } else {
20834                None
20835            }
20836        })
20837}
20838
20839pub trait RangeToAnchorExt: Sized {
20840    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20841
20842    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20843        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20844        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20845    }
20846}
20847
20848impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20849    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20850        let start_offset = self.start.to_offset(snapshot);
20851        let end_offset = self.end.to_offset(snapshot);
20852        if start_offset == end_offset {
20853            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20854        } else {
20855            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20856        }
20857    }
20858}
20859
20860pub trait RowExt {
20861    fn as_f32(&self) -> f32;
20862
20863    fn next_row(&self) -> Self;
20864
20865    fn previous_row(&self) -> Self;
20866
20867    fn minus(&self, other: Self) -> u32;
20868}
20869
20870impl RowExt for DisplayRow {
20871    fn as_f32(&self) -> f32 {
20872        self.0 as f32
20873    }
20874
20875    fn next_row(&self) -> Self {
20876        Self(self.0 + 1)
20877    }
20878
20879    fn previous_row(&self) -> Self {
20880        Self(self.0.saturating_sub(1))
20881    }
20882
20883    fn minus(&self, other: Self) -> u32 {
20884        self.0 - other.0
20885    }
20886}
20887
20888impl RowExt for MultiBufferRow {
20889    fn as_f32(&self) -> f32 {
20890        self.0 as f32
20891    }
20892
20893    fn next_row(&self) -> Self {
20894        Self(self.0 + 1)
20895    }
20896
20897    fn previous_row(&self) -> Self {
20898        Self(self.0.saturating_sub(1))
20899    }
20900
20901    fn minus(&self, other: Self) -> u32 {
20902        self.0 - other.0
20903    }
20904}
20905
20906trait RowRangeExt {
20907    type Row;
20908
20909    fn len(&self) -> usize;
20910
20911    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20912}
20913
20914impl RowRangeExt for Range<MultiBufferRow> {
20915    type Row = MultiBufferRow;
20916
20917    fn len(&self) -> usize {
20918        (self.end.0 - self.start.0) as usize
20919    }
20920
20921    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20922        (self.start.0..self.end.0).map(MultiBufferRow)
20923    }
20924}
20925
20926impl RowRangeExt for Range<DisplayRow> {
20927    type Row = DisplayRow;
20928
20929    fn len(&self) -> usize {
20930        (self.end.0 - self.start.0) as usize
20931    }
20932
20933    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20934        (self.start.0..self.end.0).map(DisplayRow)
20935    }
20936}
20937
20938/// If select range has more than one line, we
20939/// just point the cursor to range.start.
20940fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20941    if range.start.row == range.end.row {
20942        range
20943    } else {
20944        range.start..range.start
20945    }
20946}
20947pub struct KillRing(ClipboardItem);
20948impl Global for KillRing {}
20949
20950const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20951
20952enum BreakpointPromptEditAction {
20953    Log,
20954    Condition,
20955    HitCondition,
20956}
20957
20958struct BreakpointPromptEditor {
20959    pub(crate) prompt: Entity<Editor>,
20960    editor: WeakEntity<Editor>,
20961    breakpoint_anchor: Anchor,
20962    breakpoint: Breakpoint,
20963    edit_action: BreakpointPromptEditAction,
20964    block_ids: HashSet<CustomBlockId>,
20965    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20966    _subscriptions: Vec<Subscription>,
20967}
20968
20969impl BreakpointPromptEditor {
20970    const MAX_LINES: u8 = 4;
20971
20972    fn new(
20973        editor: WeakEntity<Editor>,
20974        breakpoint_anchor: Anchor,
20975        breakpoint: Breakpoint,
20976        edit_action: BreakpointPromptEditAction,
20977        window: &mut Window,
20978        cx: &mut Context<Self>,
20979    ) -> Self {
20980        let base_text = match edit_action {
20981            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20982            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20983            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20984        }
20985        .map(|msg| msg.to_string())
20986        .unwrap_or_default();
20987
20988        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20989        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20990
20991        let prompt = cx.new(|cx| {
20992            let mut prompt = Editor::new(
20993                EditorMode::AutoHeight {
20994                    max_lines: Self::MAX_LINES as usize,
20995                },
20996                buffer,
20997                None,
20998                window,
20999                cx,
21000            );
21001            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21002            prompt.set_show_cursor_when_unfocused(false, cx);
21003            prompt.set_placeholder_text(
21004                match edit_action {
21005                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21006                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21007                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21008                },
21009                cx,
21010            );
21011
21012            prompt
21013        });
21014
21015        Self {
21016            prompt,
21017            editor,
21018            breakpoint_anchor,
21019            breakpoint,
21020            edit_action,
21021            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21022            block_ids: Default::default(),
21023            _subscriptions: vec![],
21024        }
21025    }
21026
21027    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21028        self.block_ids.extend(block_ids)
21029    }
21030
21031    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21032        if let Some(editor) = self.editor.upgrade() {
21033            let message = self
21034                .prompt
21035                .read(cx)
21036                .buffer
21037                .read(cx)
21038                .as_singleton()
21039                .expect("A multi buffer in breakpoint prompt isn't possible")
21040                .read(cx)
21041                .as_rope()
21042                .to_string();
21043
21044            editor.update(cx, |editor, cx| {
21045                editor.edit_breakpoint_at_anchor(
21046                    self.breakpoint_anchor,
21047                    self.breakpoint.clone(),
21048                    match self.edit_action {
21049                        BreakpointPromptEditAction::Log => {
21050                            BreakpointEditAction::EditLogMessage(message.into())
21051                        }
21052                        BreakpointPromptEditAction::Condition => {
21053                            BreakpointEditAction::EditCondition(message.into())
21054                        }
21055                        BreakpointPromptEditAction::HitCondition => {
21056                            BreakpointEditAction::EditHitCondition(message.into())
21057                        }
21058                    },
21059                    cx,
21060                );
21061
21062                editor.remove_blocks(self.block_ids.clone(), None, cx);
21063                cx.focus_self(window);
21064            });
21065        }
21066    }
21067
21068    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21069        self.editor
21070            .update(cx, |editor, cx| {
21071                editor.remove_blocks(self.block_ids.clone(), None, cx);
21072                window.focus(&editor.focus_handle);
21073            })
21074            .log_err();
21075    }
21076
21077    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21078        let settings = ThemeSettings::get_global(cx);
21079        let text_style = TextStyle {
21080            color: if self.prompt.read(cx).read_only(cx) {
21081                cx.theme().colors().text_disabled
21082            } else {
21083                cx.theme().colors().text
21084            },
21085            font_family: settings.buffer_font.family.clone(),
21086            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21087            font_size: settings.buffer_font_size(cx).into(),
21088            font_weight: settings.buffer_font.weight,
21089            line_height: relative(settings.buffer_line_height.value()),
21090            ..Default::default()
21091        };
21092        EditorElement::new(
21093            &self.prompt,
21094            EditorStyle {
21095                background: cx.theme().colors().editor_background,
21096                local_player: cx.theme().players().local(),
21097                text: text_style,
21098                ..Default::default()
21099            },
21100        )
21101    }
21102}
21103
21104impl Render for BreakpointPromptEditor {
21105    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21106        let gutter_dimensions = *self.gutter_dimensions.lock();
21107        h_flex()
21108            .key_context("Editor")
21109            .bg(cx.theme().colors().editor_background)
21110            .border_y_1()
21111            .border_color(cx.theme().status().info_border)
21112            .size_full()
21113            .py(window.line_height() / 2.5)
21114            .on_action(cx.listener(Self::confirm))
21115            .on_action(cx.listener(Self::cancel))
21116            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21117            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21118    }
21119}
21120
21121impl Focusable for BreakpointPromptEditor {
21122    fn focus_handle(&self, cx: &App) -> FocusHandle {
21123        self.prompt.focus_handle(cx)
21124    }
21125}
21126
21127fn all_edits_insertions_or_deletions(
21128    edits: &Vec<(Range<Anchor>, String)>,
21129    snapshot: &MultiBufferSnapshot,
21130) -> bool {
21131    let mut all_insertions = true;
21132    let mut all_deletions = true;
21133
21134    for (range, new_text) in edits.iter() {
21135        let range_is_empty = range.to_offset(&snapshot).is_empty();
21136        let text_is_empty = new_text.is_empty();
21137
21138        if range_is_empty != text_is_empty {
21139            if range_is_empty {
21140                all_deletions = false;
21141            } else {
21142                all_insertions = false;
21143            }
21144        } else {
21145            return false;
21146        }
21147
21148        if !all_insertions && !all_deletions {
21149            return false;
21150        }
21151    }
21152    all_insertions || all_deletions
21153}
21154
21155struct MissingEditPredictionKeybindingTooltip;
21156
21157impl Render for MissingEditPredictionKeybindingTooltip {
21158    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21159        ui::tooltip_container(window, cx, |container, _, cx| {
21160            container
21161                .flex_shrink_0()
21162                .max_w_80()
21163                .min_h(rems_from_px(124.))
21164                .justify_between()
21165                .child(
21166                    v_flex()
21167                        .flex_1()
21168                        .text_ui_sm(cx)
21169                        .child(Label::new("Conflict with Accept Keybinding"))
21170                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21171                )
21172                .child(
21173                    h_flex()
21174                        .pb_1()
21175                        .gap_1()
21176                        .items_end()
21177                        .w_full()
21178                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21179                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21180                        }))
21181                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21182                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21183                        })),
21184                )
21185        })
21186    }
21187}
21188
21189#[derive(Debug, Clone, Copy, PartialEq)]
21190pub struct LineHighlight {
21191    pub background: Background,
21192    pub border: Option<gpui::Hsla>,
21193    pub include_gutter: bool,
21194    pub type_id: Option<TypeId>,
21195}
21196
21197fn render_diff_hunk_controls(
21198    row: u32,
21199    status: &DiffHunkStatus,
21200    hunk_range: Range<Anchor>,
21201    is_created_file: bool,
21202    line_height: Pixels,
21203    editor: &Entity<Editor>,
21204    _window: &mut Window,
21205    cx: &mut App,
21206) -> AnyElement {
21207    h_flex()
21208        .h(line_height)
21209        .mr_1()
21210        .gap_1()
21211        .px_0p5()
21212        .pb_1()
21213        .border_x_1()
21214        .border_b_1()
21215        .border_color(cx.theme().colors().border_variant)
21216        .rounded_b_lg()
21217        .bg(cx.theme().colors().editor_background)
21218        .gap_1()
21219        .occlude()
21220        .shadow_md()
21221        .child(if status.has_secondary_hunk() {
21222            Button::new(("stage", row as u64), "Stage")
21223                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21224                .tooltip({
21225                    let focus_handle = editor.focus_handle(cx);
21226                    move |window, cx| {
21227                        Tooltip::for_action_in(
21228                            "Stage Hunk",
21229                            &::git::ToggleStaged,
21230                            &focus_handle,
21231                            window,
21232                            cx,
21233                        )
21234                    }
21235                })
21236                .on_click({
21237                    let editor = editor.clone();
21238                    move |_event, _window, cx| {
21239                        editor.update(cx, |editor, cx| {
21240                            editor.stage_or_unstage_diff_hunks(
21241                                true,
21242                                vec![hunk_range.start..hunk_range.start],
21243                                cx,
21244                            );
21245                        });
21246                    }
21247                })
21248        } else {
21249            Button::new(("unstage", row as u64), "Unstage")
21250                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21251                .tooltip({
21252                    let focus_handle = editor.focus_handle(cx);
21253                    move |window, cx| {
21254                        Tooltip::for_action_in(
21255                            "Unstage Hunk",
21256                            &::git::ToggleStaged,
21257                            &focus_handle,
21258                            window,
21259                            cx,
21260                        )
21261                    }
21262                })
21263                .on_click({
21264                    let editor = editor.clone();
21265                    move |_event, _window, cx| {
21266                        editor.update(cx, |editor, cx| {
21267                            editor.stage_or_unstage_diff_hunks(
21268                                false,
21269                                vec![hunk_range.start..hunk_range.start],
21270                                cx,
21271                            );
21272                        });
21273                    }
21274                })
21275        })
21276        .child(
21277            Button::new(("restore", row as u64), "Restore")
21278                .tooltip({
21279                    let focus_handle = editor.focus_handle(cx);
21280                    move |window, cx| {
21281                        Tooltip::for_action_in(
21282                            "Restore Hunk",
21283                            &::git::Restore,
21284                            &focus_handle,
21285                            window,
21286                            cx,
21287                        )
21288                    }
21289                })
21290                .on_click({
21291                    let editor = editor.clone();
21292                    move |_event, window, cx| {
21293                        editor.update(cx, |editor, cx| {
21294                            let snapshot = editor.snapshot(window, cx);
21295                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21296                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21297                        });
21298                    }
21299                })
21300                .disabled(is_created_file),
21301        )
21302        .when(
21303            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21304            |el| {
21305                el.child(
21306                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21307                        .shape(IconButtonShape::Square)
21308                        .icon_size(IconSize::Small)
21309                        // .disabled(!has_multiple_hunks)
21310                        .tooltip({
21311                            let focus_handle = editor.focus_handle(cx);
21312                            move |window, cx| {
21313                                Tooltip::for_action_in(
21314                                    "Next Hunk",
21315                                    &GoToHunk,
21316                                    &focus_handle,
21317                                    window,
21318                                    cx,
21319                                )
21320                            }
21321                        })
21322                        .on_click({
21323                            let editor = editor.clone();
21324                            move |_event, window, cx| {
21325                                editor.update(cx, |editor, cx| {
21326                                    let snapshot = editor.snapshot(window, cx);
21327                                    let position =
21328                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21329                                    editor.go_to_hunk_before_or_after_position(
21330                                        &snapshot,
21331                                        position,
21332                                        Direction::Next,
21333                                        window,
21334                                        cx,
21335                                    );
21336                                    editor.expand_selected_diff_hunks(cx);
21337                                });
21338                            }
21339                        }),
21340                )
21341                .child(
21342                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21343                        .shape(IconButtonShape::Square)
21344                        .icon_size(IconSize::Small)
21345                        // .disabled(!has_multiple_hunks)
21346                        .tooltip({
21347                            let focus_handle = editor.focus_handle(cx);
21348                            move |window, cx| {
21349                                Tooltip::for_action_in(
21350                                    "Previous Hunk",
21351                                    &GoToPreviousHunk,
21352                                    &focus_handle,
21353                                    window,
21354                                    cx,
21355                                )
21356                            }
21357                        })
21358                        .on_click({
21359                            let editor = editor.clone();
21360                            move |_event, window, cx| {
21361                                editor.update(cx, |editor, cx| {
21362                                    let snapshot = editor.snapshot(window, cx);
21363                                    let point =
21364                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21365                                    editor.go_to_hunk_before_or_after_position(
21366                                        &snapshot,
21367                                        point,
21368                                        Direction::Prev,
21369                                        window,
21370                                        cx,
21371                                    );
21372                                    editor.expand_selected_diff_hunks(cx);
21373                                });
21374                            }
21375                        }),
21376                )
21377            },
21378        )
21379        .into_any_element()
21380}