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        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 2956
 2957        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 2958            s.set_pending(pending_selection, pending_mode)
 2959        });
 2960    }
 2961
 2962    fn begin_selection(
 2963        &mut self,
 2964        position: DisplayPoint,
 2965        add: bool,
 2966        click_count: usize,
 2967        window: &mut Window,
 2968        cx: &mut Context<Self>,
 2969    ) {
 2970        if !self.focus_handle.is_focused(window) {
 2971            self.last_focused_descendant = None;
 2972            window.focus(&self.focus_handle);
 2973        }
 2974
 2975        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2976        let buffer = &display_map.buffer_snapshot;
 2977        let position = display_map.clip_point(position, Bias::Left);
 2978
 2979        let start;
 2980        let end;
 2981        let mode;
 2982        let mut auto_scroll;
 2983        match click_count {
 2984            1 => {
 2985                start = buffer.anchor_before(position.to_point(&display_map));
 2986                end = start;
 2987                mode = SelectMode::Character;
 2988                auto_scroll = true;
 2989            }
 2990            2 => {
 2991                let range = movement::surrounding_word(&display_map, position);
 2992                start = buffer.anchor_before(range.start.to_point(&display_map));
 2993                end = buffer.anchor_before(range.end.to_point(&display_map));
 2994                mode = SelectMode::Word(start..end);
 2995                auto_scroll = true;
 2996            }
 2997            3 => {
 2998                let position = display_map
 2999                    .clip_point(position, Bias::Left)
 3000                    .to_point(&display_map);
 3001                let line_start = display_map.prev_line_boundary(position).0;
 3002                let next_line_start = buffer.clip_point(
 3003                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3004                    Bias::Left,
 3005                );
 3006                start = buffer.anchor_before(line_start);
 3007                end = buffer.anchor_before(next_line_start);
 3008                mode = SelectMode::Line(start..end);
 3009                auto_scroll = true;
 3010            }
 3011            _ => {
 3012                start = buffer.anchor_before(0);
 3013                end = buffer.anchor_before(buffer.len());
 3014                mode = SelectMode::All;
 3015                auto_scroll = false;
 3016            }
 3017        }
 3018        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3019
 3020        let point_to_delete: Option<usize> = {
 3021            let selected_points: Vec<Selection<Point>> =
 3022                self.selections.disjoint_in_range(start..end, cx);
 3023
 3024            if !add || click_count > 1 {
 3025                None
 3026            } else if !selected_points.is_empty() {
 3027                Some(selected_points[0].id)
 3028            } else {
 3029                let clicked_point_already_selected =
 3030                    self.selections.disjoint.iter().find(|selection| {
 3031                        selection.start.to_point(buffer) == start.to_point(buffer)
 3032                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3033                    });
 3034
 3035                clicked_point_already_selected.map(|selection| selection.id)
 3036            }
 3037        };
 3038
 3039        let selections_count = self.selections.count();
 3040
 3041        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3042            if let Some(point_to_delete) = point_to_delete {
 3043                s.delete(point_to_delete);
 3044
 3045                if selections_count == 1 {
 3046                    s.set_pending_anchor_range(start..end, mode);
 3047                }
 3048            } else {
 3049                if !add {
 3050                    s.clear_disjoint();
 3051                }
 3052
 3053                s.set_pending_anchor_range(start..end, mode);
 3054            }
 3055        });
 3056    }
 3057
 3058    fn begin_columnar_selection(
 3059        &mut self,
 3060        position: DisplayPoint,
 3061        goal_column: u32,
 3062        reset: bool,
 3063        window: &mut Window,
 3064        cx: &mut Context<Self>,
 3065    ) {
 3066        if !self.focus_handle.is_focused(window) {
 3067            self.last_focused_descendant = None;
 3068            window.focus(&self.focus_handle);
 3069        }
 3070
 3071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3072
 3073        if reset {
 3074            let pointer_position = display_map
 3075                .buffer_snapshot
 3076                .anchor_before(position.to_point(&display_map));
 3077
 3078            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3079                s.clear_disjoint();
 3080                s.set_pending_anchor_range(
 3081                    pointer_position..pointer_position,
 3082                    SelectMode::Character,
 3083                );
 3084            });
 3085        }
 3086
 3087        let tail = self.selections.newest::<Point>(cx).tail();
 3088        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3089
 3090        if !reset {
 3091            self.select_columns(
 3092                tail.to_display_point(&display_map),
 3093                position,
 3094                goal_column,
 3095                &display_map,
 3096                window,
 3097                cx,
 3098            );
 3099        }
 3100    }
 3101
 3102    fn update_selection(
 3103        &mut self,
 3104        position: DisplayPoint,
 3105        goal_column: u32,
 3106        scroll_delta: gpui::Point<f32>,
 3107        window: &mut Window,
 3108        cx: &mut Context<Self>,
 3109    ) {
 3110        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3111
 3112        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3113            let tail = tail.to_display_point(&display_map);
 3114            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3115        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3116            let buffer = self.buffer.read(cx).snapshot(cx);
 3117            let head;
 3118            let tail;
 3119            let mode = self.selections.pending_mode().unwrap();
 3120            match &mode {
 3121                SelectMode::Character => {
 3122                    head = position.to_point(&display_map);
 3123                    tail = pending.tail().to_point(&buffer);
 3124                }
 3125                SelectMode::Word(original_range) => {
 3126                    let original_display_range = original_range.start.to_display_point(&display_map)
 3127                        ..original_range.end.to_display_point(&display_map);
 3128                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3129                        ..original_display_range.end.to_point(&display_map);
 3130                    if movement::is_inside_word(&display_map, position)
 3131                        || original_display_range.contains(&position)
 3132                    {
 3133                        let word_range = movement::surrounding_word(&display_map, position);
 3134                        if word_range.start < original_display_range.start {
 3135                            head = word_range.start.to_point(&display_map);
 3136                        } else {
 3137                            head = word_range.end.to_point(&display_map);
 3138                        }
 3139                    } else {
 3140                        head = position.to_point(&display_map);
 3141                    }
 3142
 3143                    if head <= original_buffer_range.start {
 3144                        tail = original_buffer_range.end;
 3145                    } else {
 3146                        tail = original_buffer_range.start;
 3147                    }
 3148                }
 3149                SelectMode::Line(original_range) => {
 3150                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3151
 3152                    let position = display_map
 3153                        .clip_point(position, Bias::Left)
 3154                        .to_point(&display_map);
 3155                    let line_start = display_map.prev_line_boundary(position).0;
 3156                    let next_line_start = buffer.clip_point(
 3157                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3158                        Bias::Left,
 3159                    );
 3160
 3161                    if line_start < original_range.start {
 3162                        head = line_start
 3163                    } else {
 3164                        head = next_line_start
 3165                    }
 3166
 3167                    if head <= original_range.start {
 3168                        tail = original_range.end;
 3169                    } else {
 3170                        tail = original_range.start;
 3171                    }
 3172                }
 3173                SelectMode::All => {
 3174                    return;
 3175                }
 3176            };
 3177
 3178            if head < tail {
 3179                pending.start = buffer.anchor_before(head);
 3180                pending.end = buffer.anchor_before(tail);
 3181                pending.reversed = true;
 3182            } else {
 3183                pending.start = buffer.anchor_before(tail);
 3184                pending.end = buffer.anchor_before(head);
 3185                pending.reversed = false;
 3186            }
 3187
 3188            self.change_selections(None, window, cx, |s| {
 3189                s.set_pending(pending, mode);
 3190            });
 3191        } else {
 3192            log::error!("update_selection dispatched with no pending selection");
 3193            return;
 3194        }
 3195
 3196        self.apply_scroll_delta(scroll_delta, window, cx);
 3197        cx.notify();
 3198    }
 3199
 3200    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3201        self.columnar_selection_tail.take();
 3202        if self.selections.pending_anchor().is_some() {
 3203            let selections = self.selections.all::<usize>(cx);
 3204            self.change_selections(None, window, cx, |s| {
 3205                s.select(selections);
 3206                s.clear_pending();
 3207            });
 3208        }
 3209    }
 3210
 3211    fn select_columns(
 3212        &mut self,
 3213        tail: DisplayPoint,
 3214        head: DisplayPoint,
 3215        goal_column: u32,
 3216        display_map: &DisplaySnapshot,
 3217        window: &mut Window,
 3218        cx: &mut Context<Self>,
 3219    ) {
 3220        let start_row = cmp::min(tail.row(), head.row());
 3221        let end_row = cmp::max(tail.row(), head.row());
 3222        let start_column = cmp::min(tail.column(), goal_column);
 3223        let end_column = cmp::max(tail.column(), goal_column);
 3224        let reversed = start_column < tail.column();
 3225
 3226        let selection_ranges = (start_row.0..=end_row.0)
 3227            .map(DisplayRow)
 3228            .filter_map(|row| {
 3229                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3230                    let start = display_map
 3231                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3232                        .to_point(display_map);
 3233                    let end = display_map
 3234                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3235                        .to_point(display_map);
 3236                    if reversed {
 3237                        Some(end..start)
 3238                    } else {
 3239                        Some(start..end)
 3240                    }
 3241                } else {
 3242                    None
 3243                }
 3244            })
 3245            .collect::<Vec<_>>();
 3246
 3247        self.change_selections(None, window, cx, |s| {
 3248            s.select_ranges(selection_ranges);
 3249        });
 3250        cx.notify();
 3251    }
 3252
 3253    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3254        self.selections
 3255            .all_adjusted(cx)
 3256            .iter()
 3257            .any(|selection| !selection.is_empty())
 3258    }
 3259
 3260    pub fn has_pending_nonempty_selection(&self) -> bool {
 3261        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3262            Some(Selection { start, end, .. }) => start != end,
 3263            None => false,
 3264        };
 3265
 3266        pending_nonempty_selection
 3267            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3268    }
 3269
 3270    pub fn has_pending_selection(&self) -> bool {
 3271        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3272    }
 3273
 3274    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3275        self.selection_mark_mode = false;
 3276
 3277        if self.clear_expanded_diff_hunks(cx) {
 3278            cx.notify();
 3279            return;
 3280        }
 3281        if self.dismiss_menus_and_popups(true, window, cx) {
 3282            return;
 3283        }
 3284
 3285        if self.mode.is_full()
 3286            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3287        {
 3288            return;
 3289        }
 3290
 3291        cx.propagate();
 3292    }
 3293
 3294    pub fn dismiss_menus_and_popups(
 3295        &mut self,
 3296        is_user_requested: bool,
 3297        window: &mut Window,
 3298        cx: &mut Context<Self>,
 3299    ) -> bool {
 3300        if self.take_rename(false, window, cx).is_some() {
 3301            return true;
 3302        }
 3303
 3304        if hide_hover(self, cx) {
 3305            return true;
 3306        }
 3307
 3308        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3309            return true;
 3310        }
 3311
 3312        if self.hide_context_menu(window, cx).is_some() {
 3313            return true;
 3314        }
 3315
 3316        if self.mouse_context_menu.take().is_some() {
 3317            return true;
 3318        }
 3319
 3320        if is_user_requested && self.discard_inline_completion(true, cx) {
 3321            return true;
 3322        }
 3323
 3324        if self.snippet_stack.pop().is_some() {
 3325            return true;
 3326        }
 3327
 3328        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3329            self.dismiss_diagnostics(cx);
 3330            return true;
 3331        }
 3332
 3333        false
 3334    }
 3335
 3336    fn linked_editing_ranges_for(
 3337        &self,
 3338        selection: Range<text::Anchor>,
 3339        cx: &App,
 3340    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3341        if self.linked_edit_ranges.is_empty() {
 3342            return None;
 3343        }
 3344        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3345            selection.end.buffer_id.and_then(|end_buffer_id| {
 3346                if selection.start.buffer_id != Some(end_buffer_id) {
 3347                    return None;
 3348                }
 3349                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3350                let snapshot = buffer.read(cx).snapshot();
 3351                self.linked_edit_ranges
 3352                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3353                    .map(|ranges| (ranges, snapshot, buffer))
 3354            })?;
 3355        use text::ToOffset as TO;
 3356        // find offset from the start of current range to current cursor position
 3357        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3358
 3359        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3360        let start_difference = start_offset - start_byte_offset;
 3361        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3362        let end_difference = end_offset - start_byte_offset;
 3363        // Current range has associated linked ranges.
 3364        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3365        for range in linked_ranges.iter() {
 3366            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3367            let end_offset = start_offset + end_difference;
 3368            let start_offset = start_offset + start_difference;
 3369            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3370                continue;
 3371            }
 3372            if self.selections.disjoint_anchor_ranges().any(|s| {
 3373                if s.start.buffer_id != selection.start.buffer_id
 3374                    || s.end.buffer_id != selection.end.buffer_id
 3375                {
 3376                    return false;
 3377                }
 3378                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3379                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3380            }) {
 3381                continue;
 3382            }
 3383            let start = buffer_snapshot.anchor_after(start_offset);
 3384            let end = buffer_snapshot.anchor_after(end_offset);
 3385            linked_edits
 3386                .entry(buffer.clone())
 3387                .or_default()
 3388                .push(start..end);
 3389        }
 3390        Some(linked_edits)
 3391    }
 3392
 3393    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3394        let text: Arc<str> = text.into();
 3395
 3396        if self.read_only(cx) {
 3397            return;
 3398        }
 3399
 3400        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3401
 3402        let selections = self.selections.all_adjusted(cx);
 3403        let mut bracket_inserted = false;
 3404        let mut edits = Vec::new();
 3405        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3406        let mut new_selections = Vec::with_capacity(selections.len());
 3407        let mut new_autoclose_regions = Vec::new();
 3408        let snapshot = self.buffer.read(cx).read(cx);
 3409        let mut clear_linked_edit_ranges = false;
 3410
 3411        for (selection, autoclose_region) in
 3412            self.selections_with_autoclose_regions(selections, &snapshot)
 3413        {
 3414            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3415                // Determine if the inserted text matches the opening or closing
 3416                // bracket of any of this language's bracket pairs.
 3417                let mut bracket_pair = None;
 3418                let mut is_bracket_pair_start = false;
 3419                let mut is_bracket_pair_end = false;
 3420                if !text.is_empty() {
 3421                    let mut bracket_pair_matching_end = None;
 3422                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3423                    //  and they are removing the character that triggered IME popup.
 3424                    for (pair, enabled) in scope.brackets() {
 3425                        if !pair.close && !pair.surround {
 3426                            continue;
 3427                        }
 3428
 3429                        if enabled && pair.start.ends_with(text.as_ref()) {
 3430                            let prefix_len = pair.start.len() - text.len();
 3431                            let preceding_text_matches_prefix = prefix_len == 0
 3432                                || (selection.start.column >= (prefix_len as u32)
 3433                                    && snapshot.contains_str_at(
 3434                                        Point::new(
 3435                                            selection.start.row,
 3436                                            selection.start.column - (prefix_len as u32),
 3437                                        ),
 3438                                        &pair.start[..prefix_len],
 3439                                    ));
 3440                            if preceding_text_matches_prefix {
 3441                                bracket_pair = Some(pair.clone());
 3442                                is_bracket_pair_start = true;
 3443                                break;
 3444                            }
 3445                        }
 3446                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3447                        {
 3448                            // take first bracket pair matching end, but don't break in case a later bracket
 3449                            // pair matches start
 3450                            bracket_pair_matching_end = Some(pair.clone());
 3451                        }
 3452                    }
 3453                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3454                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3455                        is_bracket_pair_end = true;
 3456                    }
 3457                }
 3458
 3459                if let Some(bracket_pair) = bracket_pair {
 3460                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3461                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3462                    let auto_surround =
 3463                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3464                    if selection.is_empty() {
 3465                        if is_bracket_pair_start {
 3466                            // If the inserted text is a suffix of an opening bracket and the
 3467                            // selection is preceded by the rest of the opening bracket, then
 3468                            // insert the closing bracket.
 3469                            let following_text_allows_autoclose = snapshot
 3470                                .chars_at(selection.start)
 3471                                .next()
 3472                                .map_or(true, |c| scope.should_autoclose_before(c));
 3473
 3474                            let preceding_text_allows_autoclose = selection.start.column == 0
 3475                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3476                                    true,
 3477                                    |c| {
 3478                                        bracket_pair.start != bracket_pair.end
 3479                                            || !snapshot
 3480                                                .char_classifier_at(selection.start)
 3481                                                .is_word(c)
 3482                                    },
 3483                                );
 3484
 3485                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3486                                && bracket_pair.start.len() == 1
 3487                            {
 3488                                let target = bracket_pair.start.chars().next().unwrap();
 3489                                let current_line_count = snapshot
 3490                                    .reversed_chars_at(selection.start)
 3491                                    .take_while(|&c| c != '\n')
 3492                                    .filter(|&c| c == target)
 3493                                    .count();
 3494                                current_line_count % 2 == 1
 3495                            } else {
 3496                                false
 3497                            };
 3498
 3499                            if autoclose
 3500                                && bracket_pair.close
 3501                                && following_text_allows_autoclose
 3502                                && preceding_text_allows_autoclose
 3503                                && !is_closing_quote
 3504                            {
 3505                                let anchor = snapshot.anchor_before(selection.end);
 3506                                new_selections.push((selection.map(|_| anchor), text.len()));
 3507                                new_autoclose_regions.push((
 3508                                    anchor,
 3509                                    text.len(),
 3510                                    selection.id,
 3511                                    bracket_pair.clone(),
 3512                                ));
 3513                                edits.push((
 3514                                    selection.range(),
 3515                                    format!("{}{}", text, bracket_pair.end).into(),
 3516                                ));
 3517                                bracket_inserted = true;
 3518                                continue;
 3519                            }
 3520                        }
 3521
 3522                        if let Some(region) = autoclose_region {
 3523                            // If the selection is followed by an auto-inserted closing bracket,
 3524                            // then don't insert that closing bracket again; just move the selection
 3525                            // past the closing bracket.
 3526                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3527                                && text.as_ref() == region.pair.end.as_str();
 3528                            if should_skip {
 3529                                let anchor = snapshot.anchor_after(selection.end);
 3530                                new_selections
 3531                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3532                                continue;
 3533                            }
 3534                        }
 3535
 3536                        let always_treat_brackets_as_autoclosed = snapshot
 3537                            .language_settings_at(selection.start, cx)
 3538                            .always_treat_brackets_as_autoclosed;
 3539                        if always_treat_brackets_as_autoclosed
 3540                            && is_bracket_pair_end
 3541                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3542                        {
 3543                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3544                            // and the inserted text is a closing bracket and the selection is followed
 3545                            // by the closing bracket then move the selection past the closing bracket.
 3546                            let anchor = snapshot.anchor_after(selection.end);
 3547                            new_selections.push((selection.map(|_| anchor), text.len()));
 3548                            continue;
 3549                        }
 3550                    }
 3551                    // If an opening bracket is 1 character long and is typed while
 3552                    // text is selected, then surround that text with the bracket pair.
 3553                    else if auto_surround
 3554                        && bracket_pair.surround
 3555                        && is_bracket_pair_start
 3556                        && bracket_pair.start.chars().count() == 1
 3557                    {
 3558                        edits.push((selection.start..selection.start, text.clone()));
 3559                        edits.push((
 3560                            selection.end..selection.end,
 3561                            bracket_pair.end.as_str().into(),
 3562                        ));
 3563                        bracket_inserted = true;
 3564                        new_selections.push((
 3565                            Selection {
 3566                                id: selection.id,
 3567                                start: snapshot.anchor_after(selection.start),
 3568                                end: snapshot.anchor_before(selection.end),
 3569                                reversed: selection.reversed,
 3570                                goal: selection.goal,
 3571                            },
 3572                            0,
 3573                        ));
 3574                        continue;
 3575                    }
 3576                }
 3577            }
 3578
 3579            if self.auto_replace_emoji_shortcode
 3580                && selection.is_empty()
 3581                && text.as_ref().ends_with(':')
 3582            {
 3583                if let Some(possible_emoji_short_code) =
 3584                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3585                {
 3586                    if !possible_emoji_short_code.is_empty() {
 3587                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3588                            let emoji_shortcode_start = Point::new(
 3589                                selection.start.row,
 3590                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3591                            );
 3592
 3593                            // Remove shortcode from buffer
 3594                            edits.push((
 3595                                emoji_shortcode_start..selection.start,
 3596                                "".to_string().into(),
 3597                            ));
 3598                            new_selections.push((
 3599                                Selection {
 3600                                    id: selection.id,
 3601                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3602                                    end: snapshot.anchor_before(selection.start),
 3603                                    reversed: selection.reversed,
 3604                                    goal: selection.goal,
 3605                                },
 3606                                0,
 3607                            ));
 3608
 3609                            // Insert emoji
 3610                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3611                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3612                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3613
 3614                            continue;
 3615                        }
 3616                    }
 3617                }
 3618            }
 3619
 3620            // If not handling any auto-close operation, then just replace the selected
 3621            // text with the given input and move the selection to the end of the
 3622            // newly inserted text.
 3623            let anchor = snapshot.anchor_after(selection.end);
 3624            if !self.linked_edit_ranges.is_empty() {
 3625                let start_anchor = snapshot.anchor_before(selection.start);
 3626
 3627                let is_word_char = text.chars().next().map_or(true, |char| {
 3628                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3629                    classifier.is_word(char)
 3630                });
 3631
 3632                if is_word_char {
 3633                    if let Some(ranges) = self
 3634                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3635                    {
 3636                        for (buffer, edits) in ranges {
 3637                            linked_edits
 3638                                .entry(buffer.clone())
 3639                                .or_default()
 3640                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3641                        }
 3642                    }
 3643                } else {
 3644                    clear_linked_edit_ranges = true;
 3645                }
 3646            }
 3647
 3648            new_selections.push((selection.map(|_| anchor), 0));
 3649            edits.push((selection.start..selection.end, text.clone()));
 3650        }
 3651
 3652        drop(snapshot);
 3653
 3654        self.transact(window, cx, |this, window, cx| {
 3655            if clear_linked_edit_ranges {
 3656                this.linked_edit_ranges.clear();
 3657            }
 3658            let initial_buffer_versions =
 3659                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3660
 3661            this.buffer.update(cx, |buffer, cx| {
 3662                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3663            });
 3664            for (buffer, edits) in linked_edits {
 3665                buffer.update(cx, |buffer, cx| {
 3666                    let snapshot = buffer.snapshot();
 3667                    let edits = edits
 3668                        .into_iter()
 3669                        .map(|(range, text)| {
 3670                            use text::ToPoint as TP;
 3671                            let end_point = TP::to_point(&range.end, &snapshot);
 3672                            let start_point = TP::to_point(&range.start, &snapshot);
 3673                            (start_point..end_point, text)
 3674                        })
 3675                        .sorted_by_key(|(range, _)| range.start);
 3676                    buffer.edit(edits, None, cx);
 3677                })
 3678            }
 3679            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3680            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3681            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3682            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3683                .zip(new_selection_deltas)
 3684                .map(|(selection, delta)| Selection {
 3685                    id: selection.id,
 3686                    start: selection.start + delta,
 3687                    end: selection.end + delta,
 3688                    reversed: selection.reversed,
 3689                    goal: SelectionGoal::None,
 3690                })
 3691                .collect::<Vec<_>>();
 3692
 3693            let mut i = 0;
 3694            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3695                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3696                let start = map.buffer_snapshot.anchor_before(position);
 3697                let end = map.buffer_snapshot.anchor_after(position);
 3698                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3699                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3700                        Ordering::Less => i += 1,
 3701                        Ordering::Greater => break,
 3702                        Ordering::Equal => {
 3703                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3704                                Ordering::Less => i += 1,
 3705                                Ordering::Equal => break,
 3706                                Ordering::Greater => break,
 3707                            }
 3708                        }
 3709                    }
 3710                }
 3711                this.autoclose_regions.insert(
 3712                    i,
 3713                    AutocloseRegion {
 3714                        selection_id,
 3715                        range: start..end,
 3716                        pair,
 3717                    },
 3718                );
 3719            }
 3720
 3721            let had_active_inline_completion = this.has_active_inline_completion();
 3722            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3723                s.select(new_selections)
 3724            });
 3725
 3726            if !bracket_inserted {
 3727                if let Some(on_type_format_task) =
 3728                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3729                {
 3730                    on_type_format_task.detach_and_log_err(cx);
 3731                }
 3732            }
 3733
 3734            let editor_settings = EditorSettings::get_global(cx);
 3735            if bracket_inserted
 3736                && (editor_settings.auto_signature_help
 3737                    || editor_settings.show_signature_help_after_edits)
 3738            {
 3739                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3740            }
 3741
 3742            let trigger_in_words =
 3743                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3744            if this.hard_wrap.is_some() {
 3745                let latest: Range<Point> = this.selections.newest(cx).range();
 3746                if latest.is_empty()
 3747                    && this
 3748                        .buffer()
 3749                        .read(cx)
 3750                        .snapshot(cx)
 3751                        .line_len(MultiBufferRow(latest.start.row))
 3752                        == latest.start.column
 3753                {
 3754                    this.rewrap_impl(
 3755                        RewrapOptions {
 3756                            override_language_settings: true,
 3757                            preserve_existing_whitespace: true,
 3758                        },
 3759                        cx,
 3760                    )
 3761                }
 3762            }
 3763            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3764            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3765            this.refresh_inline_completion(true, false, window, cx);
 3766            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3767        });
 3768    }
 3769
 3770    fn find_possible_emoji_shortcode_at_position(
 3771        snapshot: &MultiBufferSnapshot,
 3772        position: Point,
 3773    ) -> Option<String> {
 3774        let mut chars = Vec::new();
 3775        let mut found_colon = false;
 3776        for char in snapshot.reversed_chars_at(position).take(100) {
 3777            // Found a possible emoji shortcode in the middle of the buffer
 3778            if found_colon {
 3779                if char.is_whitespace() {
 3780                    chars.reverse();
 3781                    return Some(chars.iter().collect());
 3782                }
 3783                // If the previous character is not a whitespace, we are in the middle of a word
 3784                // and we only want to complete the shortcode if the word is made up of other emojis
 3785                let mut containing_word = String::new();
 3786                for ch in snapshot
 3787                    .reversed_chars_at(position)
 3788                    .skip(chars.len() + 1)
 3789                    .take(100)
 3790                {
 3791                    if ch.is_whitespace() {
 3792                        break;
 3793                    }
 3794                    containing_word.push(ch);
 3795                }
 3796                let containing_word = containing_word.chars().rev().collect::<String>();
 3797                if util::word_consists_of_emojis(containing_word.as_str()) {
 3798                    chars.reverse();
 3799                    return Some(chars.iter().collect());
 3800                }
 3801            }
 3802
 3803            if char.is_whitespace() || !char.is_ascii() {
 3804                return None;
 3805            }
 3806            if char == ':' {
 3807                found_colon = true;
 3808            } else {
 3809                chars.push(char);
 3810            }
 3811        }
 3812        // Found a possible emoji shortcode at the beginning of the buffer
 3813        chars.reverse();
 3814        Some(chars.iter().collect())
 3815    }
 3816
 3817    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3818        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3819        self.transact(window, cx, |this, window, cx| {
 3820            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3821                let selections = this.selections.all::<usize>(cx);
 3822                let multi_buffer = this.buffer.read(cx);
 3823                let buffer = multi_buffer.snapshot(cx);
 3824                selections
 3825                    .iter()
 3826                    .map(|selection| {
 3827                        let start_point = selection.start.to_point(&buffer);
 3828                        let mut indent =
 3829                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3830                        indent.len = cmp::min(indent.len, start_point.column);
 3831                        let start = selection.start;
 3832                        let end = selection.end;
 3833                        let selection_is_empty = start == end;
 3834                        let language_scope = buffer.language_scope_at(start);
 3835                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3836                            &language_scope
 3837                        {
 3838                            let insert_extra_newline =
 3839                                insert_extra_newline_brackets(&buffer, start..end, language)
 3840                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3841
 3842                            // Comment extension on newline is allowed only for cursor selections
 3843                            let comment_delimiter = maybe!({
 3844                                if !selection_is_empty {
 3845                                    return None;
 3846                                }
 3847
 3848                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3849                                    return None;
 3850                                }
 3851
 3852                                let delimiters = language.line_comment_prefixes();
 3853                                let max_len_of_delimiter =
 3854                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3855                                let (snapshot, range) =
 3856                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3857
 3858                                let mut index_of_first_non_whitespace = 0;
 3859                                let comment_candidate = snapshot
 3860                                    .chars_for_range(range)
 3861                                    .skip_while(|c| {
 3862                                        let should_skip = c.is_whitespace();
 3863                                        if should_skip {
 3864                                            index_of_first_non_whitespace += 1;
 3865                                        }
 3866                                        should_skip
 3867                                    })
 3868                                    .take(max_len_of_delimiter)
 3869                                    .collect::<String>();
 3870                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3871                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3872                                })?;
 3873                                let cursor_is_placed_after_comment_marker =
 3874                                    index_of_first_non_whitespace + comment_prefix.len()
 3875                                        <= start_point.column as usize;
 3876                                if cursor_is_placed_after_comment_marker {
 3877                                    Some(comment_prefix.clone())
 3878                                } else {
 3879                                    None
 3880                                }
 3881                            });
 3882                            (comment_delimiter, insert_extra_newline)
 3883                        } else {
 3884                            (None, false)
 3885                        };
 3886
 3887                        let capacity_for_delimiter = comment_delimiter
 3888                            .as_deref()
 3889                            .map(str::len)
 3890                            .unwrap_or_default();
 3891                        let mut new_text =
 3892                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3893                        new_text.push('\n');
 3894                        new_text.extend(indent.chars());
 3895                        if let Some(delimiter) = &comment_delimiter {
 3896                            new_text.push_str(delimiter);
 3897                        }
 3898                        if insert_extra_newline {
 3899                            new_text = new_text.repeat(2);
 3900                        }
 3901
 3902                        let anchor = buffer.anchor_after(end);
 3903                        let new_selection = selection.map(|_| anchor);
 3904                        (
 3905                            (start..end, new_text),
 3906                            (insert_extra_newline, new_selection),
 3907                        )
 3908                    })
 3909                    .unzip()
 3910            };
 3911
 3912            this.edit_with_autoindent(edits, cx);
 3913            let buffer = this.buffer.read(cx).snapshot(cx);
 3914            let new_selections = selection_fixup_info
 3915                .into_iter()
 3916                .map(|(extra_newline_inserted, new_selection)| {
 3917                    let mut cursor = new_selection.end.to_point(&buffer);
 3918                    if extra_newline_inserted {
 3919                        cursor.row -= 1;
 3920                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3921                    }
 3922                    new_selection.map(|_| cursor)
 3923                })
 3924                .collect();
 3925
 3926            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3927                s.select(new_selections)
 3928            });
 3929            this.refresh_inline_completion(true, false, window, cx);
 3930        });
 3931    }
 3932
 3933    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3934        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3935
 3936        let buffer = self.buffer.read(cx);
 3937        let snapshot = buffer.snapshot(cx);
 3938
 3939        let mut edits = Vec::new();
 3940        let mut rows = Vec::new();
 3941
 3942        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3943            let cursor = selection.head();
 3944            let row = cursor.row;
 3945
 3946            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3947
 3948            let newline = "\n".to_string();
 3949            edits.push((start_of_line..start_of_line, newline));
 3950
 3951            rows.push(row + rows_inserted as u32);
 3952        }
 3953
 3954        self.transact(window, cx, |editor, window, cx| {
 3955            editor.edit(edits, cx);
 3956
 3957            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3958                let mut index = 0;
 3959                s.move_cursors_with(|map, _, _| {
 3960                    let row = rows[index];
 3961                    index += 1;
 3962
 3963                    let point = Point::new(row, 0);
 3964                    let boundary = map.next_line_boundary(point).1;
 3965                    let clipped = map.clip_point(boundary, Bias::Left);
 3966
 3967                    (clipped, SelectionGoal::None)
 3968                });
 3969            });
 3970
 3971            let mut indent_edits = Vec::new();
 3972            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3973            for row in rows {
 3974                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3975                for (row, indent) in indents {
 3976                    if indent.len == 0 {
 3977                        continue;
 3978                    }
 3979
 3980                    let text = match indent.kind {
 3981                        IndentKind::Space => " ".repeat(indent.len as usize),
 3982                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3983                    };
 3984                    let point = Point::new(row.0, 0);
 3985                    indent_edits.push((point..point, text));
 3986                }
 3987            }
 3988            editor.edit(indent_edits, cx);
 3989        });
 3990    }
 3991
 3992    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3993        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3994
 3995        let buffer = self.buffer.read(cx);
 3996        let snapshot = buffer.snapshot(cx);
 3997
 3998        let mut edits = Vec::new();
 3999        let mut rows = Vec::new();
 4000        let mut rows_inserted = 0;
 4001
 4002        for selection in self.selections.all_adjusted(cx) {
 4003            let cursor = selection.head();
 4004            let row = cursor.row;
 4005
 4006            let point = Point::new(row + 1, 0);
 4007            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4008
 4009            let newline = "\n".to_string();
 4010            edits.push((start_of_line..start_of_line, newline));
 4011
 4012            rows_inserted += 1;
 4013            rows.push(row + rows_inserted);
 4014        }
 4015
 4016        self.transact(window, cx, |editor, window, cx| {
 4017            editor.edit(edits, cx);
 4018
 4019            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4020                let mut index = 0;
 4021                s.move_cursors_with(|map, _, _| {
 4022                    let row = rows[index];
 4023                    index += 1;
 4024
 4025                    let point = Point::new(row, 0);
 4026                    let boundary = map.next_line_boundary(point).1;
 4027                    let clipped = map.clip_point(boundary, Bias::Left);
 4028
 4029                    (clipped, SelectionGoal::None)
 4030                });
 4031            });
 4032
 4033            let mut indent_edits = Vec::new();
 4034            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4035            for row in rows {
 4036                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4037                for (row, indent) in indents {
 4038                    if indent.len == 0 {
 4039                        continue;
 4040                    }
 4041
 4042                    let text = match indent.kind {
 4043                        IndentKind::Space => " ".repeat(indent.len as usize),
 4044                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4045                    };
 4046                    let point = Point::new(row.0, 0);
 4047                    indent_edits.push((point..point, text));
 4048                }
 4049            }
 4050            editor.edit(indent_edits, cx);
 4051        });
 4052    }
 4053
 4054    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4055        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4056            original_indent_columns: Vec::new(),
 4057        });
 4058        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4059    }
 4060
 4061    fn insert_with_autoindent_mode(
 4062        &mut self,
 4063        text: &str,
 4064        autoindent_mode: Option<AutoindentMode>,
 4065        window: &mut Window,
 4066        cx: &mut Context<Self>,
 4067    ) {
 4068        if self.read_only(cx) {
 4069            return;
 4070        }
 4071
 4072        let text: Arc<str> = text.into();
 4073        self.transact(window, cx, |this, window, cx| {
 4074            let old_selections = this.selections.all_adjusted(cx);
 4075            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4076                let anchors = {
 4077                    let snapshot = buffer.read(cx);
 4078                    old_selections
 4079                        .iter()
 4080                        .map(|s| {
 4081                            let anchor = snapshot.anchor_after(s.head());
 4082                            s.map(|_| anchor)
 4083                        })
 4084                        .collect::<Vec<_>>()
 4085                };
 4086                buffer.edit(
 4087                    old_selections
 4088                        .iter()
 4089                        .map(|s| (s.start..s.end, text.clone())),
 4090                    autoindent_mode,
 4091                    cx,
 4092                );
 4093                anchors
 4094            });
 4095
 4096            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4097                s.select_anchors(selection_anchors);
 4098            });
 4099
 4100            cx.notify();
 4101        });
 4102    }
 4103
 4104    fn trigger_completion_on_input(
 4105        &mut self,
 4106        text: &str,
 4107        trigger_in_words: bool,
 4108        window: &mut Window,
 4109        cx: &mut Context<Self>,
 4110    ) {
 4111        let ignore_completion_provider = self
 4112            .context_menu
 4113            .borrow()
 4114            .as_ref()
 4115            .map(|menu| match menu {
 4116                CodeContextMenu::Completions(completions_menu) => {
 4117                    completions_menu.ignore_completion_provider
 4118                }
 4119                CodeContextMenu::CodeActions(_) => false,
 4120            })
 4121            .unwrap_or(false);
 4122
 4123        if ignore_completion_provider {
 4124            self.show_word_completions(&ShowWordCompletions, window, cx);
 4125        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4126            self.show_completions(
 4127                &ShowCompletions {
 4128                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4129                },
 4130                window,
 4131                cx,
 4132            );
 4133        } else {
 4134            self.hide_context_menu(window, cx);
 4135        }
 4136    }
 4137
 4138    fn is_completion_trigger(
 4139        &self,
 4140        text: &str,
 4141        trigger_in_words: bool,
 4142        cx: &mut Context<Self>,
 4143    ) -> bool {
 4144        let position = self.selections.newest_anchor().head();
 4145        let multibuffer = self.buffer.read(cx);
 4146        let Some(buffer) = position
 4147            .buffer_id
 4148            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4149        else {
 4150            return false;
 4151        };
 4152
 4153        if let Some(completion_provider) = &self.completion_provider {
 4154            completion_provider.is_completion_trigger(
 4155                &buffer,
 4156                position.text_anchor,
 4157                text,
 4158                trigger_in_words,
 4159                cx,
 4160            )
 4161        } else {
 4162            false
 4163        }
 4164    }
 4165
 4166    /// If any empty selections is touching the start of its innermost containing autoclose
 4167    /// region, expand it to select the brackets.
 4168    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4169        let selections = self.selections.all::<usize>(cx);
 4170        let buffer = self.buffer.read(cx).read(cx);
 4171        let new_selections = self
 4172            .selections_with_autoclose_regions(selections, &buffer)
 4173            .map(|(mut selection, region)| {
 4174                if !selection.is_empty() {
 4175                    return selection;
 4176                }
 4177
 4178                if let Some(region) = region {
 4179                    let mut range = region.range.to_offset(&buffer);
 4180                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4181                        range.start -= region.pair.start.len();
 4182                        if buffer.contains_str_at(range.start, &region.pair.start)
 4183                            && buffer.contains_str_at(range.end, &region.pair.end)
 4184                        {
 4185                            range.end += region.pair.end.len();
 4186                            selection.start = range.start;
 4187                            selection.end = range.end;
 4188
 4189                            return selection;
 4190                        }
 4191                    }
 4192                }
 4193
 4194                let always_treat_brackets_as_autoclosed = buffer
 4195                    .language_settings_at(selection.start, cx)
 4196                    .always_treat_brackets_as_autoclosed;
 4197
 4198                if !always_treat_brackets_as_autoclosed {
 4199                    return selection;
 4200                }
 4201
 4202                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4203                    for (pair, enabled) in scope.brackets() {
 4204                        if !enabled || !pair.close {
 4205                            continue;
 4206                        }
 4207
 4208                        if buffer.contains_str_at(selection.start, &pair.end) {
 4209                            let pair_start_len = pair.start.len();
 4210                            if buffer.contains_str_at(
 4211                                selection.start.saturating_sub(pair_start_len),
 4212                                &pair.start,
 4213                            ) {
 4214                                selection.start -= pair_start_len;
 4215                                selection.end += pair.end.len();
 4216
 4217                                return selection;
 4218                            }
 4219                        }
 4220                    }
 4221                }
 4222
 4223                selection
 4224            })
 4225            .collect();
 4226
 4227        drop(buffer);
 4228        self.change_selections(None, window, cx, |selections| {
 4229            selections.select(new_selections)
 4230        });
 4231    }
 4232
 4233    /// Iterate the given selections, and for each one, find the smallest surrounding
 4234    /// autoclose region. This uses the ordering of the selections and the autoclose
 4235    /// regions to avoid repeated comparisons.
 4236    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4237        &'a self,
 4238        selections: impl IntoIterator<Item = Selection<D>>,
 4239        buffer: &'a MultiBufferSnapshot,
 4240    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4241        let mut i = 0;
 4242        let mut regions = self.autoclose_regions.as_slice();
 4243        selections.into_iter().map(move |selection| {
 4244            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4245
 4246            let mut enclosing = None;
 4247            while let Some(pair_state) = regions.get(i) {
 4248                if pair_state.range.end.to_offset(buffer) < range.start {
 4249                    regions = &regions[i + 1..];
 4250                    i = 0;
 4251                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4252                    break;
 4253                } else {
 4254                    if pair_state.selection_id == selection.id {
 4255                        enclosing = Some(pair_state);
 4256                    }
 4257                    i += 1;
 4258                }
 4259            }
 4260
 4261            (selection, enclosing)
 4262        })
 4263    }
 4264
 4265    /// Remove any autoclose regions that no longer contain their selection.
 4266    fn invalidate_autoclose_regions(
 4267        &mut self,
 4268        mut selections: &[Selection<Anchor>],
 4269        buffer: &MultiBufferSnapshot,
 4270    ) {
 4271        self.autoclose_regions.retain(|state| {
 4272            let mut i = 0;
 4273            while let Some(selection) = selections.get(i) {
 4274                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4275                    selections = &selections[1..];
 4276                    continue;
 4277                }
 4278                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4279                    break;
 4280                }
 4281                if selection.id == state.selection_id {
 4282                    return true;
 4283                } else {
 4284                    i += 1;
 4285                }
 4286            }
 4287            false
 4288        });
 4289    }
 4290
 4291    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4292        let offset = position.to_offset(buffer);
 4293        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4294        if offset > word_range.start && kind == Some(CharKind::Word) {
 4295            Some(
 4296                buffer
 4297                    .text_for_range(word_range.start..offset)
 4298                    .collect::<String>(),
 4299            )
 4300        } else {
 4301            None
 4302        }
 4303    }
 4304
 4305    pub fn toggle_inline_values(
 4306        &mut self,
 4307        _: &ToggleInlineValues,
 4308        _: &mut Window,
 4309        cx: &mut Context<Self>,
 4310    ) {
 4311        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4312
 4313        self.refresh_inline_values(cx);
 4314    }
 4315
 4316    pub fn toggle_inlay_hints(
 4317        &mut self,
 4318        _: &ToggleInlayHints,
 4319        _: &mut Window,
 4320        cx: &mut Context<Self>,
 4321    ) {
 4322        self.refresh_inlay_hints(
 4323            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4324            cx,
 4325        );
 4326    }
 4327
 4328    pub fn inlay_hints_enabled(&self) -> bool {
 4329        self.inlay_hint_cache.enabled
 4330    }
 4331
 4332    pub fn inline_values_enabled(&self) -> bool {
 4333        self.inline_value_cache.enabled
 4334    }
 4335
 4336    #[cfg(any(test, feature = "test-support"))]
 4337    pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
 4338        self.display_map
 4339            .read(cx)
 4340            .current_inlays()
 4341            .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
 4342            .cloned()
 4343            .collect()
 4344    }
 4345
 4346    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4347        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4348            return;
 4349        }
 4350
 4351        let reason_description = reason.description();
 4352        let ignore_debounce = matches!(
 4353            reason,
 4354            InlayHintRefreshReason::SettingsChange(_)
 4355                | InlayHintRefreshReason::Toggle(_)
 4356                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4357                | InlayHintRefreshReason::ModifiersChanged(_)
 4358        );
 4359        let (invalidate_cache, required_languages) = match reason {
 4360            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4361                match self.inlay_hint_cache.modifiers_override(enabled) {
 4362                    Some(enabled) => {
 4363                        if enabled {
 4364                            (InvalidationStrategy::RefreshRequested, None)
 4365                        } else {
 4366                            self.splice_inlays(
 4367                                &self
 4368                                    .visible_inlay_hints(cx)
 4369                                    .iter()
 4370                                    .map(|inlay| inlay.id)
 4371                                    .collect::<Vec<InlayId>>(),
 4372                                Vec::new(),
 4373                                cx,
 4374                            );
 4375                            return;
 4376                        }
 4377                    }
 4378                    None => return,
 4379                }
 4380            }
 4381            InlayHintRefreshReason::Toggle(enabled) => {
 4382                if self.inlay_hint_cache.toggle(enabled) {
 4383                    if enabled {
 4384                        (InvalidationStrategy::RefreshRequested, None)
 4385                    } else {
 4386                        self.splice_inlays(
 4387                            &self
 4388                                .visible_inlay_hints(cx)
 4389                                .iter()
 4390                                .map(|inlay| inlay.id)
 4391                                .collect::<Vec<InlayId>>(),
 4392                            Vec::new(),
 4393                            cx,
 4394                        );
 4395                        return;
 4396                    }
 4397                } else {
 4398                    return;
 4399                }
 4400            }
 4401            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4402                match self.inlay_hint_cache.update_settings(
 4403                    &self.buffer,
 4404                    new_settings,
 4405                    self.visible_inlay_hints(cx),
 4406                    cx,
 4407                ) {
 4408                    ControlFlow::Break(Some(InlaySplice {
 4409                        to_remove,
 4410                        to_insert,
 4411                    })) => {
 4412                        self.splice_inlays(&to_remove, to_insert, cx);
 4413                        return;
 4414                    }
 4415                    ControlFlow::Break(None) => return,
 4416                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4417                }
 4418            }
 4419            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4420                if let Some(InlaySplice {
 4421                    to_remove,
 4422                    to_insert,
 4423                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4424                {
 4425                    self.splice_inlays(&to_remove, to_insert, cx);
 4426                }
 4427                self.display_map.update(cx, |display_map, _| {
 4428                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4429                });
 4430                return;
 4431            }
 4432            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4433            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4434                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4435            }
 4436            InlayHintRefreshReason::RefreshRequested => {
 4437                (InvalidationStrategy::RefreshRequested, None)
 4438            }
 4439        };
 4440
 4441        if let Some(InlaySplice {
 4442            to_remove,
 4443            to_insert,
 4444        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4445            reason_description,
 4446            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4447            invalidate_cache,
 4448            ignore_debounce,
 4449            cx,
 4450        ) {
 4451            self.splice_inlays(&to_remove, to_insert, cx);
 4452        }
 4453    }
 4454
 4455    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4456        self.display_map
 4457            .read(cx)
 4458            .current_inlays()
 4459            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4460            .cloned()
 4461            .collect()
 4462    }
 4463
 4464    pub fn excerpts_for_inlay_hints_query(
 4465        &self,
 4466        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4467        cx: &mut Context<Editor>,
 4468    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4469        let Some(project) = self.project.as_ref() else {
 4470            return HashMap::default();
 4471        };
 4472        let project = project.read(cx);
 4473        let multi_buffer = self.buffer().read(cx);
 4474        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4475        let multi_buffer_visible_start = self
 4476            .scroll_manager
 4477            .anchor()
 4478            .anchor
 4479            .to_point(&multi_buffer_snapshot);
 4480        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4481            multi_buffer_visible_start
 4482                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4483            Bias::Left,
 4484        );
 4485        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4486        multi_buffer_snapshot
 4487            .range_to_buffer_ranges(multi_buffer_visible_range)
 4488            .into_iter()
 4489            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4490            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4491                let buffer_file = project::File::from_dyn(buffer.file())?;
 4492                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4493                let worktree_entry = buffer_worktree
 4494                    .read(cx)
 4495                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4496                if worktree_entry.is_ignored {
 4497                    return None;
 4498                }
 4499
 4500                let language = buffer.language()?;
 4501                if let Some(restrict_to_languages) = restrict_to_languages {
 4502                    if !restrict_to_languages.contains(language) {
 4503                        return None;
 4504                    }
 4505                }
 4506                Some((
 4507                    excerpt_id,
 4508                    (
 4509                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4510                        buffer.version().clone(),
 4511                        excerpt_visible_range,
 4512                    ),
 4513                ))
 4514            })
 4515            .collect()
 4516    }
 4517
 4518    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4519        TextLayoutDetails {
 4520            text_system: window.text_system().clone(),
 4521            editor_style: self.style.clone().unwrap(),
 4522            rem_size: window.rem_size(),
 4523            scroll_anchor: self.scroll_manager.anchor(),
 4524            visible_rows: self.visible_line_count(),
 4525            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4526        }
 4527    }
 4528
 4529    pub fn splice_inlays(
 4530        &self,
 4531        to_remove: &[InlayId],
 4532        to_insert: Vec<Inlay>,
 4533        cx: &mut Context<Self>,
 4534    ) {
 4535        self.display_map.update(cx, |display_map, cx| {
 4536            display_map.splice_inlays(to_remove, to_insert, cx)
 4537        });
 4538        cx.notify();
 4539    }
 4540
 4541    fn trigger_on_type_formatting(
 4542        &self,
 4543        input: String,
 4544        window: &mut Window,
 4545        cx: &mut Context<Self>,
 4546    ) -> Option<Task<Result<()>>> {
 4547        if input.len() != 1 {
 4548            return None;
 4549        }
 4550
 4551        let project = self.project.as_ref()?;
 4552        let position = self.selections.newest_anchor().head();
 4553        let (buffer, buffer_position) = self
 4554            .buffer
 4555            .read(cx)
 4556            .text_anchor_for_position(position, cx)?;
 4557
 4558        let settings = language_settings::language_settings(
 4559            buffer
 4560                .read(cx)
 4561                .language_at(buffer_position)
 4562                .map(|l| l.name()),
 4563            buffer.read(cx).file(),
 4564            cx,
 4565        );
 4566        if !settings.use_on_type_format {
 4567            return None;
 4568        }
 4569
 4570        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4571        // hence we do LSP request & edit on host side only — add formats to host's history.
 4572        let push_to_lsp_host_history = true;
 4573        // If this is not the host, append its history with new edits.
 4574        let push_to_client_history = project.read(cx).is_via_collab();
 4575
 4576        let on_type_formatting = project.update(cx, |project, cx| {
 4577            project.on_type_format(
 4578                buffer.clone(),
 4579                buffer_position,
 4580                input,
 4581                push_to_lsp_host_history,
 4582                cx,
 4583            )
 4584        });
 4585        Some(cx.spawn_in(window, async move |editor, cx| {
 4586            if let Some(transaction) = on_type_formatting.await? {
 4587                if push_to_client_history {
 4588                    buffer
 4589                        .update(cx, |buffer, _| {
 4590                            buffer.push_transaction(transaction, Instant::now());
 4591                            buffer.finalize_last_transaction();
 4592                        })
 4593                        .ok();
 4594                }
 4595                editor.update(cx, |editor, cx| {
 4596                    editor.refresh_document_highlights(cx);
 4597                })?;
 4598            }
 4599            Ok(())
 4600        }))
 4601    }
 4602
 4603    pub fn show_word_completions(
 4604        &mut self,
 4605        _: &ShowWordCompletions,
 4606        window: &mut Window,
 4607        cx: &mut Context<Self>,
 4608    ) {
 4609        self.open_completions_menu(true, None, window, cx);
 4610    }
 4611
 4612    pub fn show_completions(
 4613        &mut self,
 4614        options: &ShowCompletions,
 4615        window: &mut Window,
 4616        cx: &mut Context<Self>,
 4617    ) {
 4618        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4619    }
 4620
 4621    fn open_completions_menu(
 4622        &mut self,
 4623        ignore_completion_provider: bool,
 4624        trigger: Option<&str>,
 4625        window: &mut Window,
 4626        cx: &mut Context<Self>,
 4627    ) {
 4628        if self.pending_rename.is_some() {
 4629            return;
 4630        }
 4631        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4632            return;
 4633        }
 4634
 4635        let position = self.selections.newest_anchor().head();
 4636        if position.diff_base_anchor.is_some() {
 4637            return;
 4638        }
 4639        let (buffer, buffer_position) =
 4640            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4641                output
 4642            } else {
 4643                return;
 4644            };
 4645        let buffer_snapshot = buffer.read(cx).snapshot();
 4646        let show_completion_documentation = buffer_snapshot
 4647            .settings_at(buffer_position, cx)
 4648            .show_completion_documentation;
 4649
 4650        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4651
 4652        let trigger_kind = match trigger {
 4653            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4654                CompletionTriggerKind::TRIGGER_CHARACTER
 4655            }
 4656            _ => CompletionTriggerKind::INVOKED,
 4657        };
 4658        let completion_context = CompletionContext {
 4659            trigger_character: trigger.and_then(|trigger| {
 4660                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4661                    Some(String::from(trigger))
 4662                } else {
 4663                    None
 4664                }
 4665            }),
 4666            trigger_kind,
 4667        };
 4668
 4669        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4670        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4671            let word_to_exclude = buffer_snapshot
 4672                .text_for_range(old_range.clone())
 4673                .collect::<String>();
 4674            (
 4675                buffer_snapshot.anchor_before(old_range.start)
 4676                    ..buffer_snapshot.anchor_after(old_range.end),
 4677                Some(word_to_exclude),
 4678            )
 4679        } else {
 4680            (buffer_position..buffer_position, None)
 4681        };
 4682
 4683        let completion_settings = language_settings(
 4684            buffer_snapshot
 4685                .language_at(buffer_position)
 4686                .map(|language| language.name()),
 4687            buffer_snapshot.file(),
 4688            cx,
 4689        )
 4690        .completions;
 4691
 4692        // The document can be large, so stay in reasonable bounds when searching for words,
 4693        // otherwise completion pop-up might be slow to appear.
 4694        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4695        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4696        let min_word_search = buffer_snapshot.clip_point(
 4697            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4698            Bias::Left,
 4699        );
 4700        let max_word_search = buffer_snapshot.clip_point(
 4701            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4702            Bias::Right,
 4703        );
 4704        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4705            ..buffer_snapshot.point_to_offset(max_word_search);
 4706
 4707        let provider = self
 4708            .completion_provider
 4709            .as_ref()
 4710            .filter(|_| !ignore_completion_provider);
 4711        let skip_digits = query
 4712            .as_ref()
 4713            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4714
 4715        let (mut words, provided_completions) = match provider {
 4716            Some(provider) => {
 4717                let completions = provider.completions(
 4718                    position.excerpt_id,
 4719                    &buffer,
 4720                    buffer_position,
 4721                    completion_context,
 4722                    window,
 4723                    cx,
 4724                );
 4725
 4726                let words = match completion_settings.words {
 4727                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4728                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4729                        .background_spawn(async move {
 4730                            buffer_snapshot.words_in_range(WordsQuery {
 4731                                fuzzy_contents: None,
 4732                                range: word_search_range,
 4733                                skip_digits,
 4734                            })
 4735                        }),
 4736                };
 4737
 4738                (words, completions)
 4739            }
 4740            None => (
 4741                cx.background_spawn(async move {
 4742                    buffer_snapshot.words_in_range(WordsQuery {
 4743                        fuzzy_contents: None,
 4744                        range: word_search_range,
 4745                        skip_digits,
 4746                    })
 4747                }),
 4748                Task::ready(Ok(None)),
 4749            ),
 4750        };
 4751
 4752        let sort_completions = provider
 4753            .as_ref()
 4754            .map_or(false, |provider| provider.sort_completions());
 4755
 4756        let filter_completions = provider
 4757            .as_ref()
 4758            .map_or(true, |provider| provider.filter_completions());
 4759
 4760        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4761
 4762        let id = post_inc(&mut self.next_completion_id);
 4763        let task = cx.spawn_in(window, async move |editor, cx| {
 4764            async move {
 4765                editor.update(cx, |this, _| {
 4766                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4767                })?;
 4768
 4769                let mut completions = Vec::new();
 4770                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4771                    completions.extend(provided_completions);
 4772                    if completion_settings.words == WordsCompletionMode::Fallback {
 4773                        words = Task::ready(BTreeMap::default());
 4774                    }
 4775                }
 4776
 4777                let mut words = words.await;
 4778                if let Some(word_to_exclude) = &word_to_exclude {
 4779                    words.remove(word_to_exclude);
 4780                }
 4781                for lsp_completion in &completions {
 4782                    words.remove(&lsp_completion.new_text);
 4783                }
 4784                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4785                    replace_range: old_range.clone(),
 4786                    new_text: word.clone(),
 4787                    label: CodeLabel::plain(word, None),
 4788                    icon_path: None,
 4789                    documentation: None,
 4790                    source: CompletionSource::BufferWord {
 4791                        word_range,
 4792                        resolved: false,
 4793                    },
 4794                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4795                    confirm: None,
 4796                }));
 4797
 4798                let menu = if completions.is_empty() {
 4799                    None
 4800                } else {
 4801                    let mut menu = CompletionsMenu::new(
 4802                        id,
 4803                        sort_completions,
 4804                        show_completion_documentation,
 4805                        ignore_completion_provider,
 4806                        position,
 4807                        buffer.clone(),
 4808                        completions.into(),
 4809                        snippet_sort_order,
 4810                    );
 4811
 4812                    menu.filter(
 4813                        if filter_completions {
 4814                            query.as_deref()
 4815                        } else {
 4816                            None
 4817                        },
 4818                        cx.background_executor().clone(),
 4819                    )
 4820                    .await;
 4821
 4822                    menu.visible().then_some(menu)
 4823                };
 4824
 4825                editor.update_in(cx, |editor, window, cx| {
 4826                    match editor.context_menu.borrow().as_ref() {
 4827                        None => {}
 4828                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4829                            if prev_menu.id > id {
 4830                                return;
 4831                            }
 4832                        }
 4833                        _ => return,
 4834                    }
 4835
 4836                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4837                        let mut menu = menu.unwrap();
 4838                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4839
 4840                        *editor.context_menu.borrow_mut() =
 4841                            Some(CodeContextMenu::Completions(menu));
 4842
 4843                        if editor.show_edit_predictions_in_menu() {
 4844                            editor.update_visible_inline_completion(window, cx);
 4845                        } else {
 4846                            editor.discard_inline_completion(false, cx);
 4847                        }
 4848
 4849                        cx.notify();
 4850                    } else if editor.completion_tasks.len() <= 1 {
 4851                        // If there are no more completion tasks and the last menu was
 4852                        // empty, we should hide it.
 4853                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4854                        // If it was already hidden and we don't show inline
 4855                        // completions in the menu, we should also show the
 4856                        // inline-completion when available.
 4857                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4858                            editor.update_visible_inline_completion(window, cx);
 4859                        }
 4860                    }
 4861                })?;
 4862
 4863                anyhow::Ok(())
 4864            }
 4865            .log_err()
 4866            .await
 4867        });
 4868
 4869        self.completion_tasks.push((id, task));
 4870    }
 4871
 4872    #[cfg(feature = "test-support")]
 4873    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4874        let menu = self.context_menu.borrow();
 4875        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4876            let completions = menu.completions.borrow();
 4877            Some(completions.to_vec())
 4878        } else {
 4879            None
 4880        }
 4881    }
 4882
 4883    pub fn confirm_completion(
 4884        &mut self,
 4885        action: &ConfirmCompletion,
 4886        window: &mut Window,
 4887        cx: &mut Context<Self>,
 4888    ) -> Option<Task<Result<()>>> {
 4889        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4890        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4891    }
 4892
 4893    pub fn confirm_completion_insert(
 4894        &mut self,
 4895        _: &ConfirmCompletionInsert,
 4896        window: &mut Window,
 4897        cx: &mut Context<Self>,
 4898    ) -> Option<Task<Result<()>>> {
 4899        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4900        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4901    }
 4902
 4903    pub fn confirm_completion_replace(
 4904        &mut self,
 4905        _: &ConfirmCompletionReplace,
 4906        window: &mut Window,
 4907        cx: &mut Context<Self>,
 4908    ) -> Option<Task<Result<()>>> {
 4909        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4910        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4911    }
 4912
 4913    pub fn compose_completion(
 4914        &mut self,
 4915        action: &ComposeCompletion,
 4916        window: &mut Window,
 4917        cx: &mut Context<Self>,
 4918    ) -> Option<Task<Result<()>>> {
 4919        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4920        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4921    }
 4922
 4923    fn do_completion(
 4924        &mut self,
 4925        item_ix: Option<usize>,
 4926        intent: CompletionIntent,
 4927        window: &mut Window,
 4928        cx: &mut Context<Editor>,
 4929    ) -> Option<Task<Result<()>>> {
 4930        use language::ToOffset as _;
 4931
 4932        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4933        else {
 4934            return None;
 4935        };
 4936
 4937        let candidate_id = {
 4938            let entries = completions_menu.entries.borrow();
 4939            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4940            if self.show_edit_predictions_in_menu() {
 4941                self.discard_inline_completion(true, cx);
 4942            }
 4943            mat.candidate_id
 4944        };
 4945
 4946        let buffer_handle = completions_menu.buffer;
 4947        let completion = completions_menu
 4948            .completions
 4949            .borrow()
 4950            .get(candidate_id)?
 4951            .clone();
 4952        cx.stop_propagation();
 4953
 4954        let snippet;
 4955        let new_text;
 4956        if completion.is_snippet() {
 4957            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4958            new_text = snippet.as_ref().unwrap().text.clone();
 4959        } else {
 4960            snippet = None;
 4961            new_text = completion.new_text.clone();
 4962        };
 4963
 4964        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4965        let buffer = buffer_handle.read(cx);
 4966        let snapshot = self.buffer.read(cx).snapshot(cx);
 4967        let replace_range_multibuffer = {
 4968            let excerpt = snapshot
 4969                .excerpt_containing(self.selections.newest_anchor().range())
 4970                .unwrap();
 4971            let multibuffer_anchor = snapshot
 4972                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4973                .unwrap()
 4974                ..snapshot
 4975                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4976                    .unwrap();
 4977            multibuffer_anchor.start.to_offset(&snapshot)
 4978                ..multibuffer_anchor.end.to_offset(&snapshot)
 4979        };
 4980        let newest_anchor = self.selections.newest_anchor();
 4981        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4982            return None;
 4983        }
 4984
 4985        let old_text = buffer
 4986            .text_for_range(replace_range.clone())
 4987            .collect::<String>();
 4988        let lookbehind = newest_anchor
 4989            .start
 4990            .text_anchor
 4991            .to_offset(buffer)
 4992            .saturating_sub(replace_range.start);
 4993        let lookahead = replace_range
 4994            .end
 4995            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4996        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4997        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4998
 4999        let selections = self.selections.all::<usize>(cx);
 5000        let mut ranges = Vec::new();
 5001        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 5002
 5003        for selection in &selections {
 5004            let range = if selection.id == newest_anchor.id {
 5005                replace_range_multibuffer.clone()
 5006            } else {
 5007                let mut range = selection.range();
 5008
 5009                // if prefix is present, don't duplicate it
 5010                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5011                    range.start = range.start.saturating_sub(lookbehind);
 5012
 5013                    // if suffix is also present, mimic the newest cursor and replace it
 5014                    if selection.id != newest_anchor.id
 5015                        && snapshot.contains_str_at(range.end, suffix)
 5016                    {
 5017                        range.end += lookahead;
 5018                    }
 5019                }
 5020                range
 5021            };
 5022
 5023            ranges.push(range.clone());
 5024
 5025            if !self.linked_edit_ranges.is_empty() {
 5026                let start_anchor = snapshot.anchor_before(range.start);
 5027                let end_anchor = snapshot.anchor_after(range.end);
 5028                if let Some(ranges) = self
 5029                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5030                {
 5031                    for (buffer, edits) in ranges {
 5032                        linked_edits
 5033                            .entry(buffer.clone())
 5034                            .or_default()
 5035                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5036                    }
 5037                }
 5038            }
 5039        }
 5040
 5041        cx.emit(EditorEvent::InputHandled {
 5042            utf16_range_to_replace: None,
 5043            text: new_text.clone().into(),
 5044        });
 5045
 5046        self.transact(window, cx, |this, window, cx| {
 5047            if let Some(mut snippet) = snippet {
 5048                snippet.text = new_text.to_string();
 5049                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5050            } else {
 5051                this.buffer.update(cx, |buffer, cx| {
 5052                    let auto_indent = match completion.insert_text_mode {
 5053                        Some(InsertTextMode::AS_IS) => None,
 5054                        _ => this.autoindent_mode.clone(),
 5055                    };
 5056                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5057                    buffer.edit(edits, auto_indent, cx);
 5058                });
 5059            }
 5060            for (buffer, edits) in linked_edits {
 5061                buffer.update(cx, |buffer, cx| {
 5062                    let snapshot = buffer.snapshot();
 5063                    let edits = edits
 5064                        .into_iter()
 5065                        .map(|(range, text)| {
 5066                            use text::ToPoint as TP;
 5067                            let end_point = TP::to_point(&range.end, &snapshot);
 5068                            let start_point = TP::to_point(&range.start, &snapshot);
 5069                            (start_point..end_point, text)
 5070                        })
 5071                        .sorted_by_key(|(range, _)| range.start);
 5072                    buffer.edit(edits, None, cx);
 5073                })
 5074            }
 5075
 5076            this.refresh_inline_completion(true, false, window, cx);
 5077        });
 5078
 5079        let show_new_completions_on_confirm = completion
 5080            .confirm
 5081            .as_ref()
 5082            .map_or(false, |confirm| confirm(intent, window, cx));
 5083        if show_new_completions_on_confirm {
 5084            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5085        }
 5086
 5087        let provider = self.completion_provider.as_ref()?;
 5088        drop(completion);
 5089        let apply_edits = provider.apply_additional_edits_for_completion(
 5090            buffer_handle,
 5091            completions_menu.completions.clone(),
 5092            candidate_id,
 5093            true,
 5094            cx,
 5095        );
 5096
 5097        let editor_settings = EditorSettings::get_global(cx);
 5098        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5099            // After the code completion is finished, users often want to know what signatures are needed.
 5100            // so we should automatically call signature_help
 5101            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5102        }
 5103
 5104        Some(cx.foreground_executor().spawn(async move {
 5105            apply_edits.await?;
 5106            Ok(())
 5107        }))
 5108    }
 5109
 5110    pub fn toggle_code_actions(
 5111        &mut self,
 5112        action: &ToggleCodeActions,
 5113        window: &mut Window,
 5114        cx: &mut Context<Self>,
 5115    ) {
 5116        let quick_launch = action.quick_launch;
 5117        let mut context_menu = self.context_menu.borrow_mut();
 5118        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5119            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5120                // Toggle if we're selecting the same one
 5121                *context_menu = None;
 5122                cx.notify();
 5123                return;
 5124            } else {
 5125                // Otherwise, clear it and start a new one
 5126                *context_menu = None;
 5127                cx.notify();
 5128            }
 5129        }
 5130        drop(context_menu);
 5131        let snapshot = self.snapshot(window, cx);
 5132        let deployed_from_indicator = action.deployed_from_indicator;
 5133        let mut task = self.code_actions_task.take();
 5134        let action = action.clone();
 5135        cx.spawn_in(window, async move |editor, cx| {
 5136            while let Some(prev_task) = task {
 5137                prev_task.await.log_err();
 5138                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5139            }
 5140
 5141            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5142                if editor.focus_handle.is_focused(window) {
 5143                    let multibuffer_point = action
 5144                        .deployed_from_indicator
 5145                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5146                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5147                    let (buffer, buffer_row) = snapshot
 5148                        .buffer_snapshot
 5149                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5150                        .and_then(|(buffer_snapshot, range)| {
 5151                            editor
 5152                                .buffer
 5153                                .read(cx)
 5154                                .buffer(buffer_snapshot.remote_id())
 5155                                .map(|buffer| (buffer, range.start.row))
 5156                        })?;
 5157                    let (_, code_actions) = editor
 5158                        .available_code_actions
 5159                        .clone()
 5160                        .and_then(|(location, code_actions)| {
 5161                            let snapshot = location.buffer.read(cx).snapshot();
 5162                            let point_range = location.range.to_point(&snapshot);
 5163                            let point_range = point_range.start.row..=point_range.end.row;
 5164                            if point_range.contains(&buffer_row) {
 5165                                Some((location, code_actions))
 5166                            } else {
 5167                                None
 5168                            }
 5169                        })
 5170                        .unzip();
 5171                    let buffer_id = buffer.read(cx).remote_id();
 5172                    let tasks = editor
 5173                        .tasks
 5174                        .get(&(buffer_id, buffer_row))
 5175                        .map(|t| Arc::new(t.to_owned()));
 5176                    if tasks.is_none() && code_actions.is_none() {
 5177                        return None;
 5178                    }
 5179
 5180                    editor.completion_tasks.clear();
 5181                    editor.discard_inline_completion(false, cx);
 5182                    let task_context =
 5183                        tasks
 5184                            .as_ref()
 5185                            .zip(editor.project.clone())
 5186                            .map(|(tasks, project)| {
 5187                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5188                            });
 5189
 5190                    Some(cx.spawn_in(window, async move |editor, cx| {
 5191                        let task_context = match task_context {
 5192                            Some(task_context) => task_context.await,
 5193                            None => None,
 5194                        };
 5195                        let resolved_tasks =
 5196                            tasks
 5197                                .zip(task_context.clone())
 5198                                .map(|(tasks, task_context)| ResolvedTasks {
 5199                                    templates: tasks.resolve(&task_context).collect(),
 5200                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5201                                        multibuffer_point.row,
 5202                                        tasks.column,
 5203                                    )),
 5204                                });
 5205                        let spawn_straight_away = quick_launch
 5206                            && resolved_tasks
 5207                                .as_ref()
 5208                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5209                            && code_actions
 5210                                .as_ref()
 5211                                .map_or(true, |actions| actions.is_empty());
 5212                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5213                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5214                                maybe!({
 5215                                    let project = editor.project.as_ref()?;
 5216                                    let dap_store = project.read(cx).dap_store();
 5217                                    let mut scenarios = vec![];
 5218                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5219                                    let buffer = buffer.read(cx);
 5220                                    let language = buffer.language()?;
 5221                                    let file = buffer.file();
 5222                                    let debug_adapter =
 5223                                        language_settings(language.name().into(), file, cx)
 5224                                            .debuggers
 5225                                            .first()
 5226                                            .map(SharedString::from)
 5227                                            .or_else(|| {
 5228                                                language
 5229                                                    .config()
 5230                                                    .debuggers
 5231                                                    .first()
 5232                                                    .map(SharedString::from)
 5233                                            })?;
 5234
 5235                                    dap_store.update(cx, |this, cx| {
 5236                                        for (_, task) in &resolved_tasks.templates {
 5237                                            if let Some(scenario) = this
 5238                                                .debug_scenario_for_build_task(
 5239                                                    task.original_task().clone(),
 5240                                                    debug_adapter.clone(),
 5241                                                    cx,
 5242                                                )
 5243                                            {
 5244                                                scenarios.push(scenario);
 5245                                            }
 5246                                        }
 5247                                    });
 5248                                    Some(scenarios)
 5249                                })
 5250                                .unwrap_or_default()
 5251                            } else {
 5252                                vec![]
 5253                            }
 5254                        })?;
 5255                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5256                            *editor.context_menu.borrow_mut() =
 5257                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5258                                    buffer,
 5259                                    actions: CodeActionContents::new(
 5260                                        resolved_tasks,
 5261                                        code_actions,
 5262                                        debug_scenarios,
 5263                                        task_context.unwrap_or_default(),
 5264                                    ),
 5265                                    selected_item: Default::default(),
 5266                                    scroll_handle: UniformListScrollHandle::default(),
 5267                                    deployed_from_indicator,
 5268                                }));
 5269                            if spawn_straight_away {
 5270                                if let Some(task) = editor.confirm_code_action(
 5271                                    &ConfirmCodeAction { item_ix: Some(0) },
 5272                                    window,
 5273                                    cx,
 5274                                ) {
 5275                                    cx.notify();
 5276                                    return task;
 5277                                }
 5278                            }
 5279                            cx.notify();
 5280                            Task::ready(Ok(()))
 5281                        }) {
 5282                            task.await
 5283                        } else {
 5284                            Ok(())
 5285                        }
 5286                    }))
 5287                } else {
 5288                    Some(Task::ready(Ok(())))
 5289                }
 5290            })?;
 5291            if let Some(task) = spawned_test_task {
 5292                task.await?;
 5293            }
 5294
 5295            Ok::<_, anyhow::Error>(())
 5296        })
 5297        .detach_and_log_err(cx);
 5298    }
 5299
 5300    pub fn confirm_code_action(
 5301        &mut self,
 5302        action: &ConfirmCodeAction,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) -> Option<Task<Result<()>>> {
 5306        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5307
 5308        let actions_menu =
 5309            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5310                menu
 5311            } else {
 5312                return None;
 5313            };
 5314
 5315        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5316        let action = actions_menu.actions.get(action_ix)?;
 5317        let title = action.label();
 5318        let buffer = actions_menu.buffer;
 5319        let workspace = self.workspace()?;
 5320
 5321        match action {
 5322            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5323                workspace.update(cx, |workspace, cx| {
 5324                    workspace.schedule_resolved_task(
 5325                        task_source_kind,
 5326                        resolved_task,
 5327                        false,
 5328                        window,
 5329                        cx,
 5330                    );
 5331
 5332                    Some(Task::ready(Ok(())))
 5333                })
 5334            }
 5335            CodeActionsItem::CodeAction {
 5336                excerpt_id,
 5337                action,
 5338                provider,
 5339            } => {
 5340                let apply_code_action =
 5341                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5342                let workspace = workspace.downgrade();
 5343                Some(cx.spawn_in(window, async move |editor, cx| {
 5344                    let project_transaction = apply_code_action.await?;
 5345                    Self::open_project_transaction(
 5346                        &editor,
 5347                        workspace,
 5348                        project_transaction,
 5349                        title,
 5350                        cx,
 5351                    )
 5352                    .await
 5353                }))
 5354            }
 5355            CodeActionsItem::DebugScenario(scenario) => {
 5356                let context = actions_menu.actions.context.clone();
 5357
 5358                workspace.update(cx, |workspace, cx| {
 5359                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5360                });
 5361                Some(Task::ready(Ok(())))
 5362            }
 5363        }
 5364    }
 5365
 5366    pub async fn open_project_transaction(
 5367        this: &WeakEntity<Editor>,
 5368        workspace: WeakEntity<Workspace>,
 5369        transaction: ProjectTransaction,
 5370        title: String,
 5371        cx: &mut AsyncWindowContext,
 5372    ) -> Result<()> {
 5373        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5374        cx.update(|_, cx| {
 5375            entries.sort_unstable_by_key(|(buffer, _)| {
 5376                buffer.read(cx).file().map(|f| f.path().clone())
 5377            });
 5378        })?;
 5379
 5380        // If the project transaction's edits are all contained within this editor, then
 5381        // avoid opening a new editor to display them.
 5382
 5383        if let Some((buffer, transaction)) = entries.first() {
 5384            if entries.len() == 1 {
 5385                let excerpt = this.update(cx, |editor, cx| {
 5386                    editor
 5387                        .buffer()
 5388                        .read(cx)
 5389                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5390                })?;
 5391                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5392                    if excerpted_buffer == *buffer {
 5393                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5394                            let excerpt_range = excerpt_range.to_offset(buffer);
 5395                            buffer
 5396                                .edited_ranges_for_transaction::<usize>(transaction)
 5397                                .all(|range| {
 5398                                    excerpt_range.start <= range.start
 5399                                        && excerpt_range.end >= range.end
 5400                                })
 5401                        })?;
 5402
 5403                        if all_edits_within_excerpt {
 5404                            return Ok(());
 5405                        }
 5406                    }
 5407                }
 5408            }
 5409        } else {
 5410            return Ok(());
 5411        }
 5412
 5413        let mut ranges_to_highlight = Vec::new();
 5414        let excerpt_buffer = cx.new(|cx| {
 5415            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5416            for (buffer_handle, transaction) in &entries {
 5417                let edited_ranges = buffer_handle
 5418                    .read(cx)
 5419                    .edited_ranges_for_transaction::<Point>(transaction)
 5420                    .collect::<Vec<_>>();
 5421                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5422                    PathKey::for_buffer(buffer_handle, cx),
 5423                    buffer_handle.clone(),
 5424                    edited_ranges,
 5425                    DEFAULT_MULTIBUFFER_CONTEXT,
 5426                    cx,
 5427                );
 5428
 5429                ranges_to_highlight.extend(ranges);
 5430            }
 5431            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5432            multibuffer
 5433        })?;
 5434
 5435        workspace.update_in(cx, |workspace, window, cx| {
 5436            let project = workspace.project().clone();
 5437            let editor =
 5438                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5439            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5440            editor.update(cx, |editor, cx| {
 5441                editor.highlight_background::<Self>(
 5442                    &ranges_to_highlight,
 5443                    |theme| theme.editor_highlighted_line_background,
 5444                    cx,
 5445                );
 5446            });
 5447        })?;
 5448
 5449        Ok(())
 5450    }
 5451
 5452    pub fn clear_code_action_providers(&mut self) {
 5453        self.code_action_providers.clear();
 5454        self.available_code_actions.take();
 5455    }
 5456
 5457    pub fn add_code_action_provider(
 5458        &mut self,
 5459        provider: Rc<dyn CodeActionProvider>,
 5460        window: &mut Window,
 5461        cx: &mut Context<Self>,
 5462    ) {
 5463        if self
 5464            .code_action_providers
 5465            .iter()
 5466            .any(|existing_provider| existing_provider.id() == provider.id())
 5467        {
 5468            return;
 5469        }
 5470
 5471        self.code_action_providers.push(provider);
 5472        self.refresh_code_actions(window, cx);
 5473    }
 5474
 5475    pub fn remove_code_action_provider(
 5476        &mut self,
 5477        id: Arc<str>,
 5478        window: &mut Window,
 5479        cx: &mut Context<Self>,
 5480    ) {
 5481        self.code_action_providers
 5482            .retain(|provider| provider.id() != id);
 5483        self.refresh_code_actions(window, cx);
 5484    }
 5485
 5486    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5487        let newest_selection = self.selections.newest_anchor().clone();
 5488        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5489        let buffer = self.buffer.read(cx);
 5490        if newest_selection.head().diff_base_anchor.is_some() {
 5491            return None;
 5492        }
 5493        let (start_buffer, start) =
 5494            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5495        let (end_buffer, end) =
 5496            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5497        if start_buffer != end_buffer {
 5498            return None;
 5499        }
 5500
 5501        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5502            cx.background_executor()
 5503                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5504                .await;
 5505
 5506            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5507                let providers = this.code_action_providers.clone();
 5508                let tasks = this
 5509                    .code_action_providers
 5510                    .iter()
 5511                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5512                    .collect::<Vec<_>>();
 5513                (providers, tasks)
 5514            })?;
 5515
 5516            let mut actions = Vec::new();
 5517            for (provider, provider_actions) in
 5518                providers.into_iter().zip(future::join_all(tasks).await)
 5519            {
 5520                if let Some(provider_actions) = provider_actions.log_err() {
 5521                    actions.extend(provider_actions.into_iter().map(|action| {
 5522                        AvailableCodeAction {
 5523                            excerpt_id: newest_selection.start.excerpt_id,
 5524                            action,
 5525                            provider: provider.clone(),
 5526                        }
 5527                    }));
 5528                }
 5529            }
 5530
 5531            this.update(cx, |this, cx| {
 5532                this.available_code_actions = if actions.is_empty() {
 5533                    None
 5534                } else {
 5535                    Some((
 5536                        Location {
 5537                            buffer: start_buffer,
 5538                            range: start..end,
 5539                        },
 5540                        actions.into(),
 5541                    ))
 5542                };
 5543                cx.notify();
 5544            })
 5545        }));
 5546        None
 5547    }
 5548
 5549    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5550        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5551            self.show_git_blame_inline = false;
 5552
 5553            self.show_git_blame_inline_delay_task =
 5554                Some(cx.spawn_in(window, async move |this, cx| {
 5555                    cx.background_executor().timer(delay).await;
 5556
 5557                    this.update(cx, |this, cx| {
 5558                        this.show_git_blame_inline = true;
 5559                        cx.notify();
 5560                    })
 5561                    .log_err();
 5562                }));
 5563        }
 5564    }
 5565
 5566    fn show_blame_popover(
 5567        &mut self,
 5568        blame_entry: &BlameEntry,
 5569        position: gpui::Point<Pixels>,
 5570        cx: &mut Context<Self>,
 5571    ) {
 5572        if let Some(state) = &mut self.inline_blame_popover {
 5573            state.hide_task.take();
 5574            cx.notify();
 5575        } else {
 5576            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5577            let show_task = cx.spawn(async move |editor, cx| {
 5578                cx.background_executor()
 5579                    .timer(std::time::Duration::from_millis(delay))
 5580                    .await;
 5581                editor
 5582                    .update(cx, |editor, cx| {
 5583                        if let Some(state) = &mut editor.inline_blame_popover {
 5584                            state.show_task = None;
 5585                            cx.notify();
 5586                        }
 5587                    })
 5588                    .ok();
 5589            });
 5590            let Some(blame) = self.blame.as_ref() else {
 5591                return;
 5592            };
 5593            let blame = blame.read(cx);
 5594            let details = blame.details_for_entry(&blame_entry);
 5595            let markdown = cx.new(|cx| {
 5596                Markdown::new(
 5597                    details
 5598                        .as_ref()
 5599                        .map(|message| message.message.clone())
 5600                        .unwrap_or_default(),
 5601                    None,
 5602                    None,
 5603                    cx,
 5604                )
 5605            });
 5606            self.inline_blame_popover = Some(InlineBlamePopover {
 5607                position,
 5608                show_task: Some(show_task),
 5609                hide_task: None,
 5610                popover_bounds: None,
 5611                popover_state: InlineBlamePopoverState {
 5612                    scroll_handle: ScrollHandle::new(),
 5613                    commit_message: details,
 5614                    markdown,
 5615                },
 5616            });
 5617        }
 5618    }
 5619
 5620    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5621        if let Some(state) = &mut self.inline_blame_popover {
 5622            if state.show_task.is_some() {
 5623                self.inline_blame_popover.take();
 5624                cx.notify();
 5625            } else {
 5626                let hide_task = cx.spawn(async move |editor, cx| {
 5627                    cx.background_executor()
 5628                        .timer(std::time::Duration::from_millis(100))
 5629                        .await;
 5630                    editor
 5631                        .update(cx, |editor, cx| {
 5632                            editor.inline_blame_popover.take();
 5633                            cx.notify();
 5634                        })
 5635                        .ok();
 5636                });
 5637                state.hide_task = Some(hide_task);
 5638            }
 5639        }
 5640    }
 5641
 5642    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5643        if self.pending_rename.is_some() {
 5644            return None;
 5645        }
 5646
 5647        let provider = self.semantics_provider.clone()?;
 5648        let buffer = self.buffer.read(cx);
 5649        let newest_selection = self.selections.newest_anchor().clone();
 5650        let cursor_position = newest_selection.head();
 5651        let (cursor_buffer, cursor_buffer_position) =
 5652            buffer.text_anchor_for_position(cursor_position, cx)?;
 5653        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5654        if cursor_buffer != tail_buffer {
 5655            return None;
 5656        }
 5657        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5658        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5659            cx.background_executor()
 5660                .timer(Duration::from_millis(debounce))
 5661                .await;
 5662
 5663            let highlights = if let Some(highlights) = cx
 5664                .update(|cx| {
 5665                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5666                })
 5667                .ok()
 5668                .flatten()
 5669            {
 5670                highlights.await.log_err()
 5671            } else {
 5672                None
 5673            };
 5674
 5675            if let Some(highlights) = highlights {
 5676                this.update(cx, |this, cx| {
 5677                    if this.pending_rename.is_some() {
 5678                        return;
 5679                    }
 5680
 5681                    let buffer_id = cursor_position.buffer_id;
 5682                    let buffer = this.buffer.read(cx);
 5683                    if !buffer
 5684                        .text_anchor_for_position(cursor_position, cx)
 5685                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5686                    {
 5687                        return;
 5688                    }
 5689
 5690                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5691                    let mut write_ranges = Vec::new();
 5692                    let mut read_ranges = Vec::new();
 5693                    for highlight in highlights {
 5694                        for (excerpt_id, excerpt_range) in
 5695                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5696                        {
 5697                            let start = highlight
 5698                                .range
 5699                                .start
 5700                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5701                            let end = highlight
 5702                                .range
 5703                                .end
 5704                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5705                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5706                                continue;
 5707                            }
 5708
 5709                            let range = Anchor {
 5710                                buffer_id,
 5711                                excerpt_id,
 5712                                text_anchor: start,
 5713                                diff_base_anchor: None,
 5714                            }..Anchor {
 5715                                buffer_id,
 5716                                excerpt_id,
 5717                                text_anchor: end,
 5718                                diff_base_anchor: None,
 5719                            };
 5720                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5721                                write_ranges.push(range);
 5722                            } else {
 5723                                read_ranges.push(range);
 5724                            }
 5725                        }
 5726                    }
 5727
 5728                    this.highlight_background::<DocumentHighlightRead>(
 5729                        &read_ranges,
 5730                        |theme| theme.editor_document_highlight_read_background,
 5731                        cx,
 5732                    );
 5733                    this.highlight_background::<DocumentHighlightWrite>(
 5734                        &write_ranges,
 5735                        |theme| theme.editor_document_highlight_write_background,
 5736                        cx,
 5737                    );
 5738                    cx.notify();
 5739                })
 5740                .log_err();
 5741            }
 5742        }));
 5743        None
 5744    }
 5745
 5746    fn prepare_highlight_query_from_selection(
 5747        &mut self,
 5748        cx: &mut Context<Editor>,
 5749    ) -> Option<(String, Range<Anchor>)> {
 5750        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5751            return None;
 5752        }
 5753        if !EditorSettings::get_global(cx).selection_highlight {
 5754            return None;
 5755        }
 5756        if self.selections.count() != 1 || self.selections.line_mode {
 5757            return None;
 5758        }
 5759        let selection = self.selections.newest::<Point>(cx);
 5760        if selection.is_empty() || selection.start.row != selection.end.row {
 5761            return None;
 5762        }
 5763        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5764        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5765        let query = multi_buffer_snapshot
 5766            .text_for_range(selection_anchor_range.clone())
 5767            .collect::<String>();
 5768        if query.trim().is_empty() {
 5769            return None;
 5770        }
 5771        Some((query, selection_anchor_range))
 5772    }
 5773
 5774    fn update_selection_occurrence_highlights(
 5775        &mut self,
 5776        query_text: String,
 5777        query_range: Range<Anchor>,
 5778        multi_buffer_range_to_query: Range<Point>,
 5779        use_debounce: bool,
 5780        window: &mut Window,
 5781        cx: &mut Context<Editor>,
 5782    ) -> Task<()> {
 5783        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5784        cx.spawn_in(window, async move |editor, cx| {
 5785            if use_debounce {
 5786                cx.background_executor()
 5787                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5788                    .await;
 5789            }
 5790            let match_task = cx.background_spawn(async move {
 5791                let buffer_ranges = multi_buffer_snapshot
 5792                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5793                    .into_iter()
 5794                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5795                let mut match_ranges = Vec::new();
 5796                let Ok(regex) = project::search::SearchQuery::text(
 5797                    query_text.clone(),
 5798                    false,
 5799                    false,
 5800                    false,
 5801                    Default::default(),
 5802                    Default::default(),
 5803                    false,
 5804                    None,
 5805                ) else {
 5806                    return Vec::default();
 5807                };
 5808                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5809                    match_ranges.extend(
 5810                        regex
 5811                            .search(&buffer_snapshot, Some(search_range.clone()))
 5812                            .await
 5813                            .into_iter()
 5814                            .filter_map(|match_range| {
 5815                                let match_start = buffer_snapshot
 5816                                    .anchor_after(search_range.start + match_range.start);
 5817                                let match_end = buffer_snapshot
 5818                                    .anchor_before(search_range.start + match_range.end);
 5819                                let match_anchor_range = Anchor::range_in_buffer(
 5820                                    excerpt_id,
 5821                                    buffer_snapshot.remote_id(),
 5822                                    match_start..match_end,
 5823                                );
 5824                                (match_anchor_range != query_range).then_some(match_anchor_range)
 5825                            }),
 5826                    );
 5827                }
 5828                match_ranges
 5829            });
 5830            let match_ranges = match_task.await;
 5831            editor
 5832                .update_in(cx, |editor, _, cx| {
 5833                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5834                    if !match_ranges.is_empty() {
 5835                        editor.highlight_background::<SelectedTextHighlight>(
 5836                            &match_ranges,
 5837                            |theme| theme.editor_document_highlight_bracket_background,
 5838                            cx,
 5839                        )
 5840                    }
 5841                })
 5842                .log_err();
 5843        })
 5844    }
 5845
 5846    fn refresh_selected_text_highlights(
 5847        &mut self,
 5848        on_buffer_edit: bool,
 5849        window: &mut Window,
 5850        cx: &mut Context<Editor>,
 5851    ) {
 5852        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5853        else {
 5854            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5855            self.quick_selection_highlight_task.take();
 5856            self.debounced_selection_highlight_task.take();
 5857            return;
 5858        };
 5859        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5860        if on_buffer_edit
 5861            || self
 5862                .quick_selection_highlight_task
 5863                .as_ref()
 5864                .map_or(true, |(prev_anchor_range, _)| {
 5865                    prev_anchor_range != &query_range
 5866                })
 5867        {
 5868            let multi_buffer_visible_start = self
 5869                .scroll_manager
 5870                .anchor()
 5871                .anchor
 5872                .to_point(&multi_buffer_snapshot);
 5873            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5874                multi_buffer_visible_start
 5875                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5876                Bias::Left,
 5877            );
 5878            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5879            self.quick_selection_highlight_task = Some((
 5880                query_range.clone(),
 5881                self.update_selection_occurrence_highlights(
 5882                    query_text.clone(),
 5883                    query_range.clone(),
 5884                    multi_buffer_visible_range,
 5885                    false,
 5886                    window,
 5887                    cx,
 5888                ),
 5889            ));
 5890        }
 5891        if on_buffer_edit
 5892            || self
 5893                .debounced_selection_highlight_task
 5894                .as_ref()
 5895                .map_or(true, |(prev_anchor_range, _)| {
 5896                    prev_anchor_range != &query_range
 5897                })
 5898        {
 5899            let multi_buffer_start = multi_buffer_snapshot
 5900                .anchor_before(0)
 5901                .to_point(&multi_buffer_snapshot);
 5902            let multi_buffer_end = multi_buffer_snapshot
 5903                .anchor_after(multi_buffer_snapshot.len())
 5904                .to_point(&multi_buffer_snapshot);
 5905            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5906            self.debounced_selection_highlight_task = Some((
 5907                query_range.clone(),
 5908                self.update_selection_occurrence_highlights(
 5909                    query_text,
 5910                    query_range,
 5911                    multi_buffer_full_range,
 5912                    true,
 5913                    window,
 5914                    cx,
 5915                ),
 5916            ));
 5917        }
 5918    }
 5919
 5920    pub fn refresh_inline_completion(
 5921        &mut self,
 5922        debounce: bool,
 5923        user_requested: bool,
 5924        window: &mut Window,
 5925        cx: &mut Context<Self>,
 5926    ) -> Option<()> {
 5927        let provider = self.edit_prediction_provider()?;
 5928        let cursor = self.selections.newest_anchor().head();
 5929        let (buffer, cursor_buffer_position) =
 5930            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5931
 5932        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5933            self.discard_inline_completion(false, cx);
 5934            return None;
 5935        }
 5936
 5937        if !user_requested
 5938            && (!self.should_show_edit_predictions()
 5939                || !self.is_focused(window)
 5940                || buffer.read(cx).is_empty())
 5941        {
 5942            self.discard_inline_completion(false, cx);
 5943            return None;
 5944        }
 5945
 5946        self.update_visible_inline_completion(window, cx);
 5947        provider.refresh(
 5948            self.project.clone(),
 5949            buffer,
 5950            cursor_buffer_position,
 5951            debounce,
 5952            cx,
 5953        );
 5954        Some(())
 5955    }
 5956
 5957    fn show_edit_predictions_in_menu(&self) -> bool {
 5958        match self.edit_prediction_settings {
 5959            EditPredictionSettings::Disabled => false,
 5960            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5961        }
 5962    }
 5963
 5964    pub fn edit_predictions_enabled(&self) -> bool {
 5965        match self.edit_prediction_settings {
 5966            EditPredictionSettings::Disabled => false,
 5967            EditPredictionSettings::Enabled { .. } => true,
 5968        }
 5969    }
 5970
 5971    fn edit_prediction_requires_modifier(&self) -> bool {
 5972        match self.edit_prediction_settings {
 5973            EditPredictionSettings::Disabled => false,
 5974            EditPredictionSettings::Enabled {
 5975                preview_requires_modifier,
 5976                ..
 5977            } => preview_requires_modifier,
 5978        }
 5979    }
 5980
 5981    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5982        if self.edit_prediction_provider.is_none() {
 5983            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5984        } else {
 5985            let selection = self.selections.newest_anchor();
 5986            let cursor = selection.head();
 5987
 5988            if let Some((buffer, cursor_buffer_position)) =
 5989                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5990            {
 5991                self.edit_prediction_settings =
 5992                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5993            }
 5994        }
 5995    }
 5996
 5997    fn edit_prediction_settings_at_position(
 5998        &self,
 5999        buffer: &Entity<Buffer>,
 6000        buffer_position: language::Anchor,
 6001        cx: &App,
 6002    ) -> EditPredictionSettings {
 6003        if !self.mode.is_full()
 6004            || !self.show_inline_completions_override.unwrap_or(true)
 6005            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 6006        {
 6007            return EditPredictionSettings::Disabled;
 6008        }
 6009
 6010        let buffer = buffer.read(cx);
 6011
 6012        let file = buffer.file();
 6013
 6014        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 6015            return EditPredictionSettings::Disabled;
 6016        };
 6017
 6018        let by_provider = matches!(
 6019            self.menu_inline_completions_policy,
 6020            MenuInlineCompletionsPolicy::ByProvider
 6021        );
 6022
 6023        let show_in_menu = by_provider
 6024            && self
 6025                .edit_prediction_provider
 6026                .as_ref()
 6027                .map_or(false, |provider| {
 6028                    provider.provider.show_completions_in_menu()
 6029                });
 6030
 6031        let preview_requires_modifier =
 6032            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6033
 6034        EditPredictionSettings::Enabled {
 6035            show_in_menu,
 6036            preview_requires_modifier,
 6037        }
 6038    }
 6039
 6040    fn should_show_edit_predictions(&self) -> bool {
 6041        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6042    }
 6043
 6044    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6045        matches!(
 6046            self.edit_prediction_preview,
 6047            EditPredictionPreview::Active { .. }
 6048        )
 6049    }
 6050
 6051    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6052        let cursor = self.selections.newest_anchor().head();
 6053        if let Some((buffer, cursor_position)) =
 6054            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6055        {
 6056            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6057        } else {
 6058            false
 6059        }
 6060    }
 6061
 6062    fn edit_predictions_enabled_in_buffer(
 6063        &self,
 6064        buffer: &Entity<Buffer>,
 6065        buffer_position: language::Anchor,
 6066        cx: &App,
 6067    ) -> bool {
 6068        maybe!({
 6069            if self.read_only(cx) {
 6070                return Some(false);
 6071            }
 6072            let provider = self.edit_prediction_provider()?;
 6073            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6074                return Some(false);
 6075            }
 6076            let buffer = buffer.read(cx);
 6077            let Some(file) = buffer.file() else {
 6078                return Some(true);
 6079            };
 6080            let settings = all_language_settings(Some(file), cx);
 6081            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6082        })
 6083        .unwrap_or(false)
 6084    }
 6085
 6086    fn cycle_inline_completion(
 6087        &mut self,
 6088        direction: Direction,
 6089        window: &mut Window,
 6090        cx: &mut Context<Self>,
 6091    ) -> Option<()> {
 6092        let provider = self.edit_prediction_provider()?;
 6093        let cursor = self.selections.newest_anchor().head();
 6094        let (buffer, cursor_buffer_position) =
 6095            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6096        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6097            return None;
 6098        }
 6099
 6100        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6101        self.update_visible_inline_completion(window, cx);
 6102
 6103        Some(())
 6104    }
 6105
 6106    pub fn show_inline_completion(
 6107        &mut self,
 6108        _: &ShowEditPrediction,
 6109        window: &mut Window,
 6110        cx: &mut Context<Self>,
 6111    ) {
 6112        if !self.has_active_inline_completion() {
 6113            self.refresh_inline_completion(false, true, window, cx);
 6114            return;
 6115        }
 6116
 6117        self.update_visible_inline_completion(window, cx);
 6118    }
 6119
 6120    pub fn display_cursor_names(
 6121        &mut self,
 6122        _: &DisplayCursorNames,
 6123        window: &mut Window,
 6124        cx: &mut Context<Self>,
 6125    ) {
 6126        self.show_cursor_names(window, cx);
 6127    }
 6128
 6129    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6130        self.show_cursor_names = true;
 6131        cx.notify();
 6132        cx.spawn_in(window, async move |this, cx| {
 6133            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6134            this.update(cx, |this, cx| {
 6135                this.show_cursor_names = false;
 6136                cx.notify()
 6137            })
 6138            .ok()
 6139        })
 6140        .detach();
 6141    }
 6142
 6143    pub fn next_edit_prediction(
 6144        &mut self,
 6145        _: &NextEditPrediction,
 6146        window: &mut Window,
 6147        cx: &mut Context<Self>,
 6148    ) {
 6149        if self.has_active_inline_completion() {
 6150            self.cycle_inline_completion(Direction::Next, 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 previous_edit_prediction(
 6162        &mut self,
 6163        _: &PreviousEditPrediction,
 6164        window: &mut Window,
 6165        cx: &mut Context<Self>,
 6166    ) {
 6167        if self.has_active_inline_completion() {
 6168            self.cycle_inline_completion(Direction::Prev, window, cx);
 6169        } else {
 6170            let is_copilot_disabled = self
 6171                .refresh_inline_completion(false, true, window, cx)
 6172                .is_none();
 6173            if is_copilot_disabled {
 6174                cx.propagate();
 6175            }
 6176        }
 6177    }
 6178
 6179    pub fn accept_edit_prediction(
 6180        &mut self,
 6181        _: &AcceptEditPrediction,
 6182        window: &mut Window,
 6183        cx: &mut Context<Self>,
 6184    ) {
 6185        if self.show_edit_predictions_in_menu() {
 6186            self.hide_context_menu(window, cx);
 6187        }
 6188
 6189        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6190            return;
 6191        };
 6192
 6193        self.report_inline_completion_event(
 6194            active_inline_completion.completion_id.clone(),
 6195            true,
 6196            cx,
 6197        );
 6198
 6199        match &active_inline_completion.completion {
 6200            InlineCompletion::Move { target, .. } => {
 6201                let target = *target;
 6202
 6203                if let Some(position_map) = &self.last_position_map {
 6204                    if position_map
 6205                        .visible_row_range
 6206                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6207                        || !self.edit_prediction_requires_modifier()
 6208                    {
 6209                        self.unfold_ranges(&[target..target], true, false, cx);
 6210                        // Note that this is also done in vim's handler of the Tab action.
 6211                        self.change_selections(
 6212                            Some(Autoscroll::newest()),
 6213                            window,
 6214                            cx,
 6215                            |selections| {
 6216                                selections.select_anchor_ranges([target..target]);
 6217                            },
 6218                        );
 6219                        self.clear_row_highlights::<EditPredictionPreview>();
 6220
 6221                        self.edit_prediction_preview
 6222                            .set_previous_scroll_position(None);
 6223                    } else {
 6224                        self.edit_prediction_preview
 6225                            .set_previous_scroll_position(Some(
 6226                                position_map.snapshot.scroll_anchor,
 6227                            ));
 6228
 6229                        self.highlight_rows::<EditPredictionPreview>(
 6230                            target..target,
 6231                            cx.theme().colors().editor_highlighted_line_background,
 6232                            RowHighlightOptions {
 6233                                autoscroll: true,
 6234                                ..Default::default()
 6235                            },
 6236                            cx,
 6237                        );
 6238                        self.request_autoscroll(Autoscroll::fit(), cx);
 6239                    }
 6240                }
 6241            }
 6242            InlineCompletion::Edit { edits, .. } => {
 6243                if let Some(provider) = self.edit_prediction_provider() {
 6244                    provider.accept(cx);
 6245                }
 6246
 6247                let snapshot = self.buffer.read(cx).snapshot(cx);
 6248                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6249
 6250                self.buffer.update(cx, |buffer, cx| {
 6251                    buffer.edit(edits.iter().cloned(), None, cx)
 6252                });
 6253
 6254                self.change_selections(None, window, cx, |s| {
 6255                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6256                });
 6257
 6258                self.update_visible_inline_completion(window, cx);
 6259                if self.active_inline_completion.is_none() {
 6260                    self.refresh_inline_completion(true, true, window, cx);
 6261                }
 6262
 6263                cx.notify();
 6264            }
 6265        }
 6266
 6267        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6268    }
 6269
 6270    pub fn accept_partial_inline_completion(
 6271        &mut self,
 6272        _: &AcceptPartialEditPrediction,
 6273        window: &mut Window,
 6274        cx: &mut Context<Self>,
 6275    ) {
 6276        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6277            return;
 6278        };
 6279        if self.selections.count() != 1 {
 6280            return;
 6281        }
 6282
 6283        self.report_inline_completion_event(
 6284            active_inline_completion.completion_id.clone(),
 6285            true,
 6286            cx,
 6287        );
 6288
 6289        match &active_inline_completion.completion {
 6290            InlineCompletion::Move { target, .. } => {
 6291                let target = *target;
 6292                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6293                    selections.select_anchor_ranges([target..target]);
 6294                });
 6295            }
 6296            InlineCompletion::Edit { edits, .. } => {
 6297                // Find an insertion that starts at the cursor position.
 6298                let snapshot = self.buffer.read(cx).snapshot(cx);
 6299                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6300                let insertion = edits.iter().find_map(|(range, text)| {
 6301                    let range = range.to_offset(&snapshot);
 6302                    if range.is_empty() && range.start == cursor_offset {
 6303                        Some(text)
 6304                    } else {
 6305                        None
 6306                    }
 6307                });
 6308
 6309                if let Some(text) = insertion {
 6310                    let mut partial_completion = text
 6311                        .chars()
 6312                        .by_ref()
 6313                        .take_while(|c| c.is_alphabetic())
 6314                        .collect::<String>();
 6315                    if partial_completion.is_empty() {
 6316                        partial_completion = text
 6317                            .chars()
 6318                            .by_ref()
 6319                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6320                            .collect::<String>();
 6321                    }
 6322
 6323                    cx.emit(EditorEvent::InputHandled {
 6324                        utf16_range_to_replace: None,
 6325                        text: partial_completion.clone().into(),
 6326                    });
 6327
 6328                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6329
 6330                    self.refresh_inline_completion(true, true, window, cx);
 6331                    cx.notify();
 6332                } else {
 6333                    self.accept_edit_prediction(&Default::default(), window, cx);
 6334                }
 6335            }
 6336        }
 6337    }
 6338
 6339    fn discard_inline_completion(
 6340        &mut self,
 6341        should_report_inline_completion_event: bool,
 6342        cx: &mut Context<Self>,
 6343    ) -> bool {
 6344        if should_report_inline_completion_event {
 6345            let completion_id = self
 6346                .active_inline_completion
 6347                .as_ref()
 6348                .and_then(|active_completion| active_completion.completion_id.clone());
 6349
 6350            self.report_inline_completion_event(completion_id, false, cx);
 6351        }
 6352
 6353        if let Some(provider) = self.edit_prediction_provider() {
 6354            provider.discard(cx);
 6355        }
 6356
 6357        self.take_active_inline_completion(cx)
 6358    }
 6359
 6360    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6361        let Some(provider) = self.edit_prediction_provider() else {
 6362            return;
 6363        };
 6364
 6365        let Some((_, buffer, _)) = self
 6366            .buffer
 6367            .read(cx)
 6368            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6369        else {
 6370            return;
 6371        };
 6372
 6373        let extension = buffer
 6374            .read(cx)
 6375            .file()
 6376            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6377
 6378        let event_type = match accepted {
 6379            true => "Edit Prediction Accepted",
 6380            false => "Edit Prediction Discarded",
 6381        };
 6382        telemetry::event!(
 6383            event_type,
 6384            provider = provider.name(),
 6385            prediction_id = id,
 6386            suggestion_accepted = accepted,
 6387            file_extension = extension,
 6388        );
 6389    }
 6390
 6391    pub fn has_active_inline_completion(&self) -> bool {
 6392        self.active_inline_completion.is_some()
 6393    }
 6394
 6395    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6396        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6397            return false;
 6398        };
 6399
 6400        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6401        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6402        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6403        true
 6404    }
 6405
 6406    /// Returns true when we're displaying the edit prediction popover below the cursor
 6407    /// like we are not previewing and the LSP autocomplete menu is visible
 6408    /// or we are in `when_holding_modifier` mode.
 6409    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6410        if self.edit_prediction_preview_is_active()
 6411            || !self.show_edit_predictions_in_menu()
 6412            || !self.edit_predictions_enabled()
 6413        {
 6414            return false;
 6415        }
 6416
 6417        if self.has_visible_completions_menu() {
 6418            return true;
 6419        }
 6420
 6421        has_completion && self.edit_prediction_requires_modifier()
 6422    }
 6423
 6424    fn handle_modifiers_changed(
 6425        &mut self,
 6426        modifiers: Modifiers,
 6427        position_map: &PositionMap,
 6428        window: &mut Window,
 6429        cx: &mut Context<Self>,
 6430    ) {
 6431        if self.show_edit_predictions_in_menu() {
 6432            self.update_edit_prediction_preview(&modifiers, window, cx);
 6433        }
 6434
 6435        self.update_selection_mode(&modifiers, position_map, window, cx);
 6436
 6437        let mouse_position = window.mouse_position();
 6438        if !position_map.text_hitbox.is_hovered(window) {
 6439            return;
 6440        }
 6441
 6442        self.update_hovered_link(
 6443            position_map.point_for_position(mouse_position),
 6444            &position_map.snapshot,
 6445            modifiers,
 6446            window,
 6447            cx,
 6448        )
 6449    }
 6450
 6451    fn update_selection_mode(
 6452        &mut self,
 6453        modifiers: &Modifiers,
 6454        position_map: &PositionMap,
 6455        window: &mut Window,
 6456        cx: &mut Context<Self>,
 6457    ) {
 6458        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6459            return;
 6460        }
 6461
 6462        let mouse_position = window.mouse_position();
 6463        let point_for_position = position_map.point_for_position(mouse_position);
 6464        let position = point_for_position.previous_valid;
 6465
 6466        self.select(
 6467            SelectPhase::BeginColumnar {
 6468                position,
 6469                reset: false,
 6470                goal_column: point_for_position.exact_unclipped.column(),
 6471            },
 6472            window,
 6473            cx,
 6474        );
 6475    }
 6476
 6477    fn update_edit_prediction_preview(
 6478        &mut self,
 6479        modifiers: &Modifiers,
 6480        window: &mut Window,
 6481        cx: &mut Context<Self>,
 6482    ) {
 6483        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6484        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6485            return;
 6486        };
 6487
 6488        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6489            if matches!(
 6490                self.edit_prediction_preview,
 6491                EditPredictionPreview::Inactive { .. }
 6492            ) {
 6493                self.edit_prediction_preview = EditPredictionPreview::Active {
 6494                    previous_scroll_position: None,
 6495                    since: Instant::now(),
 6496                };
 6497
 6498                self.update_visible_inline_completion(window, cx);
 6499                cx.notify();
 6500            }
 6501        } else if let EditPredictionPreview::Active {
 6502            previous_scroll_position,
 6503            since,
 6504        } = self.edit_prediction_preview
 6505        {
 6506            if let (Some(previous_scroll_position), Some(position_map)) =
 6507                (previous_scroll_position, self.last_position_map.as_ref())
 6508            {
 6509                self.set_scroll_position(
 6510                    previous_scroll_position
 6511                        .scroll_position(&position_map.snapshot.display_snapshot),
 6512                    window,
 6513                    cx,
 6514                );
 6515            }
 6516
 6517            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6518                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6519            };
 6520            self.clear_row_highlights::<EditPredictionPreview>();
 6521            self.update_visible_inline_completion(window, cx);
 6522            cx.notify();
 6523        }
 6524    }
 6525
 6526    fn update_visible_inline_completion(
 6527        &mut self,
 6528        _window: &mut Window,
 6529        cx: &mut Context<Self>,
 6530    ) -> Option<()> {
 6531        let selection = self.selections.newest_anchor();
 6532        let cursor = selection.head();
 6533        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6534        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6535        let excerpt_id = cursor.excerpt_id;
 6536
 6537        let show_in_menu = self.show_edit_predictions_in_menu();
 6538        let completions_menu_has_precedence = !show_in_menu
 6539            && (self.context_menu.borrow().is_some()
 6540                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6541
 6542        if completions_menu_has_precedence
 6543            || !offset_selection.is_empty()
 6544            || self
 6545                .active_inline_completion
 6546                .as_ref()
 6547                .map_or(false, |completion| {
 6548                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6549                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6550                    !invalidation_range.contains(&offset_selection.head())
 6551                })
 6552        {
 6553            self.discard_inline_completion(false, cx);
 6554            return None;
 6555        }
 6556
 6557        self.take_active_inline_completion(cx);
 6558        let Some(provider) = self.edit_prediction_provider() else {
 6559            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6560            return None;
 6561        };
 6562
 6563        let (buffer, cursor_buffer_position) =
 6564            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6565
 6566        self.edit_prediction_settings =
 6567            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6568
 6569        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6570
 6571        if self.edit_prediction_indent_conflict {
 6572            let cursor_point = cursor.to_point(&multibuffer);
 6573
 6574            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6575
 6576            if let Some((_, indent)) = indents.iter().next() {
 6577                if indent.len == cursor_point.column {
 6578                    self.edit_prediction_indent_conflict = false;
 6579                }
 6580            }
 6581        }
 6582
 6583        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6584        let edits = inline_completion
 6585            .edits
 6586            .into_iter()
 6587            .flat_map(|(range, new_text)| {
 6588                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6589                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6590                Some((start..end, new_text))
 6591            })
 6592            .collect::<Vec<_>>();
 6593        if edits.is_empty() {
 6594            return None;
 6595        }
 6596
 6597        let first_edit_start = edits.first().unwrap().0.start;
 6598        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6599        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6600
 6601        let last_edit_end = edits.last().unwrap().0.end;
 6602        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6603        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6604
 6605        let cursor_row = cursor.to_point(&multibuffer).row;
 6606
 6607        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6608
 6609        let mut inlay_ids = Vec::new();
 6610        let invalidation_row_range;
 6611        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6612            Some(cursor_row..edit_end_row)
 6613        } else if cursor_row > edit_end_row {
 6614            Some(edit_start_row..cursor_row)
 6615        } else {
 6616            None
 6617        };
 6618        let is_move =
 6619            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6620        let completion = if is_move {
 6621            invalidation_row_range =
 6622                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6623            let target = first_edit_start;
 6624            InlineCompletion::Move { target, snapshot }
 6625        } else {
 6626            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6627                && !self.inline_completions_hidden_for_vim_mode;
 6628
 6629            if show_completions_in_buffer {
 6630                if edits
 6631                    .iter()
 6632                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6633                {
 6634                    let mut inlays = Vec::new();
 6635                    for (range, new_text) in &edits {
 6636                        let inlay = Inlay::inline_completion(
 6637                            post_inc(&mut self.next_inlay_id),
 6638                            range.start,
 6639                            new_text.as_str(),
 6640                        );
 6641                        inlay_ids.push(inlay.id);
 6642                        inlays.push(inlay);
 6643                    }
 6644
 6645                    self.splice_inlays(&[], inlays, cx);
 6646                } else {
 6647                    let background_color = cx.theme().status().deleted_background;
 6648                    self.highlight_text::<InlineCompletionHighlight>(
 6649                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6650                        HighlightStyle {
 6651                            background_color: Some(background_color),
 6652                            ..Default::default()
 6653                        },
 6654                        cx,
 6655                    );
 6656                }
 6657            }
 6658
 6659            invalidation_row_range = edit_start_row..edit_end_row;
 6660
 6661            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6662                if provider.show_tab_accept_marker() {
 6663                    EditDisplayMode::TabAccept
 6664                } else {
 6665                    EditDisplayMode::Inline
 6666                }
 6667            } else {
 6668                EditDisplayMode::DiffPopover
 6669            };
 6670
 6671            InlineCompletion::Edit {
 6672                edits,
 6673                edit_preview: inline_completion.edit_preview,
 6674                display_mode,
 6675                snapshot,
 6676            }
 6677        };
 6678
 6679        let invalidation_range = multibuffer
 6680            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6681            ..multibuffer.anchor_after(Point::new(
 6682                invalidation_row_range.end,
 6683                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6684            ));
 6685
 6686        self.stale_inline_completion_in_menu = None;
 6687        self.active_inline_completion = Some(InlineCompletionState {
 6688            inlay_ids,
 6689            completion,
 6690            completion_id: inline_completion.id,
 6691            invalidation_range,
 6692        });
 6693
 6694        cx.notify();
 6695
 6696        Some(())
 6697    }
 6698
 6699    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6700        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6701    }
 6702
 6703    fn render_code_actions_indicator(
 6704        &self,
 6705        _style: &EditorStyle,
 6706        row: DisplayRow,
 6707        is_active: bool,
 6708        breakpoint: Option<&(Anchor, Breakpoint)>,
 6709        cx: &mut Context<Self>,
 6710    ) -> Option<IconButton> {
 6711        let color = Color::Muted;
 6712        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6713        let show_tooltip = !self.context_menu_visible();
 6714
 6715        if self.available_code_actions.is_some() {
 6716            Some(
 6717                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6718                    .shape(ui::IconButtonShape::Square)
 6719                    .icon_size(IconSize::XSmall)
 6720                    .icon_color(color)
 6721                    .toggle_state(is_active)
 6722                    .when(show_tooltip, |this| {
 6723                        this.tooltip({
 6724                            let focus_handle = self.focus_handle.clone();
 6725                            move |window, cx| {
 6726                                Tooltip::for_action_in(
 6727                                    "Toggle Code Actions",
 6728                                    &ToggleCodeActions {
 6729                                        deployed_from_indicator: None,
 6730                                        quick_launch: false,
 6731                                    },
 6732                                    &focus_handle,
 6733                                    window,
 6734                                    cx,
 6735                                )
 6736                            }
 6737                        })
 6738                    })
 6739                    .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 6740                        let quick_launch = e.down.button == MouseButton::Left;
 6741                        window.focus(&editor.focus_handle(cx));
 6742                        editor.toggle_code_actions(
 6743                            &ToggleCodeActions {
 6744                                deployed_from_indicator: Some(row),
 6745                                quick_launch,
 6746                            },
 6747                            window,
 6748                            cx,
 6749                        );
 6750                    }))
 6751                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6752                        editor.set_breakpoint_context_menu(
 6753                            row,
 6754                            position,
 6755                            event.down.position,
 6756                            window,
 6757                            cx,
 6758                        );
 6759                    })),
 6760            )
 6761        } else {
 6762            None
 6763        }
 6764    }
 6765
 6766    fn clear_tasks(&mut self) {
 6767        self.tasks.clear()
 6768    }
 6769
 6770    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6771        if self.tasks.insert(key, value).is_some() {
 6772            // This case should hopefully be rare, but just in case...
 6773            log::error!(
 6774                "multiple different run targets found on a single line, only the last target will be rendered"
 6775            )
 6776        }
 6777    }
 6778
 6779    /// Get all display points of breakpoints that will be rendered within editor
 6780    ///
 6781    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6782    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6783    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6784    fn active_breakpoints(
 6785        &self,
 6786        range: Range<DisplayRow>,
 6787        window: &mut Window,
 6788        cx: &mut Context<Self>,
 6789    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6790        let mut breakpoint_display_points = HashMap::default();
 6791
 6792        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6793            return breakpoint_display_points;
 6794        };
 6795
 6796        let snapshot = self.snapshot(window, cx);
 6797
 6798        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6799        let Some(project) = self.project.as_ref() else {
 6800            return breakpoint_display_points;
 6801        };
 6802
 6803        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6804            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6805
 6806        for (buffer_snapshot, range, excerpt_id) in
 6807            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6808        {
 6809            let Some(buffer) = project.read_with(cx, |this, cx| {
 6810                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6811            }) else {
 6812                continue;
 6813            };
 6814            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6815                &buffer,
 6816                Some(
 6817                    buffer_snapshot.anchor_before(range.start)
 6818                        ..buffer_snapshot.anchor_after(range.end),
 6819                ),
 6820                buffer_snapshot,
 6821                cx,
 6822            );
 6823            for (anchor, breakpoint) in breakpoints {
 6824                let multi_buffer_anchor =
 6825                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6826                let position = multi_buffer_anchor
 6827                    .to_point(&multi_buffer_snapshot)
 6828                    .to_display_point(&snapshot);
 6829
 6830                breakpoint_display_points
 6831                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6832            }
 6833        }
 6834
 6835        breakpoint_display_points
 6836    }
 6837
 6838    fn breakpoint_context_menu(
 6839        &self,
 6840        anchor: Anchor,
 6841        window: &mut Window,
 6842        cx: &mut Context<Self>,
 6843    ) -> Entity<ui::ContextMenu> {
 6844        let weak_editor = cx.weak_entity();
 6845        let focus_handle = self.focus_handle(cx);
 6846
 6847        let row = self
 6848            .buffer
 6849            .read(cx)
 6850            .snapshot(cx)
 6851            .summary_for_anchor::<Point>(&anchor)
 6852            .row;
 6853
 6854        let breakpoint = self
 6855            .breakpoint_at_row(row, window, cx)
 6856            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6857
 6858        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6859            "Edit Log Breakpoint"
 6860        } else {
 6861            "Set Log Breakpoint"
 6862        };
 6863
 6864        let condition_breakpoint_msg = if breakpoint
 6865            .as_ref()
 6866            .is_some_and(|bp| bp.1.condition.is_some())
 6867        {
 6868            "Edit Condition Breakpoint"
 6869        } else {
 6870            "Set Condition Breakpoint"
 6871        };
 6872
 6873        let hit_condition_breakpoint_msg = if breakpoint
 6874            .as_ref()
 6875            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6876        {
 6877            "Edit Hit Condition Breakpoint"
 6878        } else {
 6879            "Set Hit Condition Breakpoint"
 6880        };
 6881
 6882        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6883            "Unset Breakpoint"
 6884        } else {
 6885            "Set Breakpoint"
 6886        };
 6887
 6888        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6889            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6890
 6891        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6892            BreakpointState::Enabled => Some("Disable"),
 6893            BreakpointState::Disabled => Some("Enable"),
 6894        });
 6895
 6896        let (anchor, breakpoint) =
 6897            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6898
 6899        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6900            menu.on_blur_subscription(Subscription::new(|| {}))
 6901                .context(focus_handle)
 6902                .when(run_to_cursor, |this| {
 6903                    let weak_editor = weak_editor.clone();
 6904                    this.entry("Run to cursor", None, move |window, cx| {
 6905                        weak_editor
 6906                            .update(cx, |editor, cx| {
 6907                                editor.change_selections(None, window, cx, |s| {
 6908                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6909                                });
 6910                            })
 6911                            .ok();
 6912
 6913                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6914                    })
 6915                    .separator()
 6916                })
 6917                .when_some(toggle_state_msg, |this, msg| {
 6918                    this.entry(msg, None, {
 6919                        let weak_editor = weak_editor.clone();
 6920                        let breakpoint = breakpoint.clone();
 6921                        move |_window, cx| {
 6922                            weak_editor
 6923                                .update(cx, |this, cx| {
 6924                                    this.edit_breakpoint_at_anchor(
 6925                                        anchor,
 6926                                        breakpoint.as_ref().clone(),
 6927                                        BreakpointEditAction::InvertState,
 6928                                        cx,
 6929                                    );
 6930                                })
 6931                                .log_err();
 6932                        }
 6933                    })
 6934                })
 6935                .entry(set_breakpoint_msg, None, {
 6936                    let weak_editor = weak_editor.clone();
 6937                    let breakpoint = breakpoint.clone();
 6938                    move |_window, cx| {
 6939                        weak_editor
 6940                            .update(cx, |this, cx| {
 6941                                this.edit_breakpoint_at_anchor(
 6942                                    anchor,
 6943                                    breakpoint.as_ref().clone(),
 6944                                    BreakpointEditAction::Toggle,
 6945                                    cx,
 6946                                );
 6947                            })
 6948                            .log_err();
 6949                    }
 6950                })
 6951                .entry(log_breakpoint_msg, None, {
 6952                    let breakpoint = breakpoint.clone();
 6953                    let weak_editor = weak_editor.clone();
 6954                    move |window, cx| {
 6955                        weak_editor
 6956                            .update(cx, |this, cx| {
 6957                                this.add_edit_breakpoint_block(
 6958                                    anchor,
 6959                                    breakpoint.as_ref(),
 6960                                    BreakpointPromptEditAction::Log,
 6961                                    window,
 6962                                    cx,
 6963                                );
 6964                            })
 6965                            .log_err();
 6966                    }
 6967                })
 6968                .entry(condition_breakpoint_msg, None, {
 6969                    let breakpoint = breakpoint.clone();
 6970                    let weak_editor = weak_editor.clone();
 6971                    move |window, cx| {
 6972                        weak_editor
 6973                            .update(cx, |this, cx| {
 6974                                this.add_edit_breakpoint_block(
 6975                                    anchor,
 6976                                    breakpoint.as_ref(),
 6977                                    BreakpointPromptEditAction::Condition,
 6978                                    window,
 6979                                    cx,
 6980                                );
 6981                            })
 6982                            .log_err();
 6983                    }
 6984                })
 6985                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6986                    weak_editor
 6987                        .update(cx, |this, cx| {
 6988                            this.add_edit_breakpoint_block(
 6989                                anchor,
 6990                                breakpoint.as_ref(),
 6991                                BreakpointPromptEditAction::HitCondition,
 6992                                window,
 6993                                cx,
 6994                            );
 6995                        })
 6996                        .log_err();
 6997                })
 6998        })
 6999    }
 7000
 7001    fn render_breakpoint(
 7002        &self,
 7003        position: Anchor,
 7004        row: DisplayRow,
 7005        breakpoint: &Breakpoint,
 7006        cx: &mut Context<Self>,
 7007    ) -> IconButton {
 7008        // Is it a breakpoint that shows up when hovering over gutter?
 7009        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 7010            (false, false),
 7011            |PhantomBreakpointIndicator {
 7012                 is_active,
 7013                 display_row,
 7014                 collides_with_existing_breakpoint,
 7015             }| {
 7016                (
 7017                    is_active && display_row == row,
 7018                    collides_with_existing_breakpoint,
 7019                )
 7020            },
 7021        );
 7022
 7023        let (color, icon) = {
 7024            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 7025                (false, false) => ui::IconName::DebugBreakpoint,
 7026                (true, false) => ui::IconName::DebugLogBreakpoint,
 7027                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 7028                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 7029            };
 7030
 7031            let color = if is_phantom {
 7032                Color::Hint
 7033            } else {
 7034                Color::Debugger
 7035            };
 7036
 7037            (color, icon)
 7038        };
 7039
 7040        let breakpoint = Arc::from(breakpoint.clone());
 7041
 7042        let alt_as_text = gpui::Keystroke {
 7043            modifiers: Modifiers::secondary_key(),
 7044            ..Default::default()
 7045        };
 7046        let primary_action_text = if breakpoint.is_disabled() {
 7047            "enable"
 7048        } else if is_phantom && !collides_with_existing {
 7049            "set"
 7050        } else {
 7051            "unset"
 7052        };
 7053        let mut primary_text = format!("Click to {primary_action_text}");
 7054        if collides_with_existing && !breakpoint.is_disabled() {
 7055            use std::fmt::Write;
 7056            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7057        }
 7058        let primary_text = SharedString::from(primary_text);
 7059        let focus_handle = self.focus_handle.clone();
 7060        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7061            .icon_size(IconSize::XSmall)
 7062            .size(ui::ButtonSize::None)
 7063            .icon_color(color)
 7064            .style(ButtonStyle::Transparent)
 7065            .on_click(cx.listener({
 7066                let breakpoint = breakpoint.clone();
 7067
 7068                move |editor, event: &ClickEvent, window, cx| {
 7069                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7070                        BreakpointEditAction::InvertState
 7071                    } else {
 7072                        BreakpointEditAction::Toggle
 7073                    };
 7074
 7075                    window.focus(&editor.focus_handle(cx));
 7076                    editor.edit_breakpoint_at_anchor(
 7077                        position,
 7078                        breakpoint.as_ref().clone(),
 7079                        edit_action,
 7080                        cx,
 7081                    );
 7082                }
 7083            }))
 7084            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7085                editor.set_breakpoint_context_menu(
 7086                    row,
 7087                    Some(position),
 7088                    event.down.position,
 7089                    window,
 7090                    cx,
 7091                );
 7092            }))
 7093            .tooltip(move |window, cx| {
 7094                Tooltip::with_meta_in(
 7095                    primary_text.clone(),
 7096                    None,
 7097                    "Right-click for more options",
 7098                    &focus_handle,
 7099                    window,
 7100                    cx,
 7101                )
 7102            })
 7103    }
 7104
 7105    fn build_tasks_context(
 7106        project: &Entity<Project>,
 7107        buffer: &Entity<Buffer>,
 7108        buffer_row: u32,
 7109        tasks: &Arc<RunnableTasks>,
 7110        cx: &mut Context<Self>,
 7111    ) -> Task<Option<task::TaskContext>> {
 7112        let position = Point::new(buffer_row, tasks.column);
 7113        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7114        let location = Location {
 7115            buffer: buffer.clone(),
 7116            range: range_start..range_start,
 7117        };
 7118        // Fill in the environmental variables from the tree-sitter captures
 7119        let mut captured_task_variables = TaskVariables::default();
 7120        for (capture_name, value) in tasks.extra_variables.clone() {
 7121            captured_task_variables.insert(
 7122                task::VariableName::Custom(capture_name.into()),
 7123                value.clone(),
 7124            );
 7125        }
 7126        project.update(cx, |project, cx| {
 7127            project.task_store().update(cx, |task_store, cx| {
 7128                task_store.task_context_for_location(captured_task_variables, location, cx)
 7129            })
 7130        })
 7131    }
 7132
 7133    pub fn spawn_nearest_task(
 7134        &mut self,
 7135        action: &SpawnNearestTask,
 7136        window: &mut Window,
 7137        cx: &mut Context<Self>,
 7138    ) {
 7139        let Some((workspace, _)) = self.workspace.clone() else {
 7140            return;
 7141        };
 7142        let Some(project) = self.project.clone() else {
 7143            return;
 7144        };
 7145
 7146        // Try to find a closest, enclosing node using tree-sitter that has a
 7147        // task
 7148        let Some((buffer, buffer_row, tasks)) = self
 7149            .find_enclosing_node_task(cx)
 7150            // Or find the task that's closest in row-distance.
 7151            .or_else(|| self.find_closest_task(cx))
 7152        else {
 7153            return;
 7154        };
 7155
 7156        let reveal_strategy = action.reveal;
 7157        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7158        cx.spawn_in(window, async move |_, cx| {
 7159            let context = task_context.await?;
 7160            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7161
 7162            let resolved = &mut resolved_task.resolved;
 7163            resolved.reveal = reveal_strategy;
 7164
 7165            workspace
 7166                .update_in(cx, |workspace, window, cx| {
 7167                    workspace.schedule_resolved_task(
 7168                        task_source_kind,
 7169                        resolved_task,
 7170                        false,
 7171                        window,
 7172                        cx,
 7173                    );
 7174                })
 7175                .ok()
 7176        })
 7177        .detach();
 7178    }
 7179
 7180    fn find_closest_task(
 7181        &mut self,
 7182        cx: &mut Context<Self>,
 7183    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7184        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7185
 7186        let ((buffer_id, row), tasks) = self
 7187            .tasks
 7188            .iter()
 7189            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7190
 7191        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7192        let tasks = Arc::new(tasks.to_owned());
 7193        Some((buffer, *row, tasks))
 7194    }
 7195
 7196    fn find_enclosing_node_task(
 7197        &mut self,
 7198        cx: &mut Context<Self>,
 7199    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7200        let snapshot = self.buffer.read(cx).snapshot(cx);
 7201        let offset = self.selections.newest::<usize>(cx).head();
 7202        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7203        let buffer_id = excerpt.buffer().remote_id();
 7204
 7205        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7206        let mut cursor = layer.node().walk();
 7207
 7208        while cursor.goto_first_child_for_byte(offset).is_some() {
 7209            if cursor.node().end_byte() == offset {
 7210                cursor.goto_next_sibling();
 7211            }
 7212        }
 7213
 7214        // Ascend to the smallest ancestor that contains the range and has a task.
 7215        loop {
 7216            let node = cursor.node();
 7217            let node_range = node.byte_range();
 7218            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7219
 7220            // Check if this node contains our offset
 7221            if node_range.start <= offset && node_range.end >= offset {
 7222                // If it contains offset, check for task
 7223                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7224                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7225                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7226                }
 7227            }
 7228
 7229            if !cursor.goto_parent() {
 7230                break;
 7231            }
 7232        }
 7233        None
 7234    }
 7235
 7236    fn render_run_indicator(
 7237        &self,
 7238        _style: &EditorStyle,
 7239        is_active: bool,
 7240        row: DisplayRow,
 7241        breakpoint: Option<(Anchor, Breakpoint)>,
 7242        cx: &mut Context<Self>,
 7243    ) -> IconButton {
 7244        let color = Color::Muted;
 7245        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7246
 7247        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7248            .shape(ui::IconButtonShape::Square)
 7249            .icon_size(IconSize::XSmall)
 7250            .icon_color(color)
 7251            .toggle_state(is_active)
 7252            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7253                let quick_launch = e.down.button == MouseButton::Left;
 7254                window.focus(&editor.focus_handle(cx));
 7255                editor.toggle_code_actions(
 7256                    &ToggleCodeActions {
 7257                        deployed_from_indicator: Some(row),
 7258                        quick_launch,
 7259                    },
 7260                    window,
 7261                    cx,
 7262                );
 7263            }))
 7264            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7265                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7266            }))
 7267    }
 7268
 7269    pub fn context_menu_visible(&self) -> bool {
 7270        !self.edit_prediction_preview_is_active()
 7271            && self
 7272                .context_menu
 7273                .borrow()
 7274                .as_ref()
 7275                .map_or(false, |menu| menu.visible())
 7276    }
 7277
 7278    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7279        self.context_menu
 7280            .borrow()
 7281            .as_ref()
 7282            .map(|menu| menu.origin())
 7283    }
 7284
 7285    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7286        self.context_menu_options = Some(options);
 7287    }
 7288
 7289    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7290    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7291
 7292    fn render_edit_prediction_popover(
 7293        &mut self,
 7294        text_bounds: &Bounds<Pixels>,
 7295        content_origin: gpui::Point<Pixels>,
 7296        editor_snapshot: &EditorSnapshot,
 7297        visible_row_range: Range<DisplayRow>,
 7298        scroll_top: f32,
 7299        scroll_bottom: f32,
 7300        line_layouts: &[LineWithInvisibles],
 7301        line_height: Pixels,
 7302        scroll_pixel_position: gpui::Point<Pixels>,
 7303        newest_selection_head: Option<DisplayPoint>,
 7304        editor_width: Pixels,
 7305        style: &EditorStyle,
 7306        window: &mut Window,
 7307        cx: &mut App,
 7308    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7309        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7310
 7311        if self.edit_prediction_visible_in_cursor_popover(true) {
 7312            return None;
 7313        }
 7314
 7315        match &active_inline_completion.completion {
 7316            InlineCompletion::Move { target, .. } => {
 7317                let target_display_point = target.to_display_point(editor_snapshot);
 7318
 7319                if self.edit_prediction_requires_modifier() {
 7320                    if !self.edit_prediction_preview_is_active() {
 7321                        return None;
 7322                    }
 7323
 7324                    self.render_edit_prediction_modifier_jump_popover(
 7325                        text_bounds,
 7326                        content_origin,
 7327                        visible_row_range,
 7328                        line_layouts,
 7329                        line_height,
 7330                        scroll_pixel_position,
 7331                        newest_selection_head,
 7332                        target_display_point,
 7333                        window,
 7334                        cx,
 7335                    )
 7336                } else {
 7337                    self.render_edit_prediction_eager_jump_popover(
 7338                        text_bounds,
 7339                        content_origin,
 7340                        editor_snapshot,
 7341                        visible_row_range,
 7342                        scroll_top,
 7343                        scroll_bottom,
 7344                        line_height,
 7345                        scroll_pixel_position,
 7346                        target_display_point,
 7347                        editor_width,
 7348                        window,
 7349                        cx,
 7350                    )
 7351                }
 7352            }
 7353            InlineCompletion::Edit {
 7354                display_mode: EditDisplayMode::Inline,
 7355                ..
 7356            } => None,
 7357            InlineCompletion::Edit {
 7358                display_mode: EditDisplayMode::TabAccept,
 7359                edits,
 7360                ..
 7361            } => {
 7362                let range = &edits.first()?.0;
 7363                let target_display_point = range.end.to_display_point(editor_snapshot);
 7364
 7365                self.render_edit_prediction_end_of_line_popover(
 7366                    "Accept",
 7367                    editor_snapshot,
 7368                    visible_row_range,
 7369                    target_display_point,
 7370                    line_height,
 7371                    scroll_pixel_position,
 7372                    content_origin,
 7373                    editor_width,
 7374                    window,
 7375                    cx,
 7376                )
 7377            }
 7378            InlineCompletion::Edit {
 7379                edits,
 7380                edit_preview,
 7381                display_mode: EditDisplayMode::DiffPopover,
 7382                snapshot,
 7383            } => self.render_edit_prediction_diff_popover(
 7384                text_bounds,
 7385                content_origin,
 7386                editor_snapshot,
 7387                visible_row_range,
 7388                line_layouts,
 7389                line_height,
 7390                scroll_pixel_position,
 7391                newest_selection_head,
 7392                editor_width,
 7393                style,
 7394                edits,
 7395                edit_preview,
 7396                snapshot,
 7397                window,
 7398                cx,
 7399            ),
 7400        }
 7401    }
 7402
 7403    fn render_edit_prediction_modifier_jump_popover(
 7404        &mut self,
 7405        text_bounds: &Bounds<Pixels>,
 7406        content_origin: gpui::Point<Pixels>,
 7407        visible_row_range: Range<DisplayRow>,
 7408        line_layouts: &[LineWithInvisibles],
 7409        line_height: Pixels,
 7410        scroll_pixel_position: gpui::Point<Pixels>,
 7411        newest_selection_head: Option<DisplayPoint>,
 7412        target_display_point: DisplayPoint,
 7413        window: &mut Window,
 7414        cx: &mut App,
 7415    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7416        let scrolled_content_origin =
 7417            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7418
 7419        const SCROLL_PADDING_Y: Pixels = px(12.);
 7420
 7421        if target_display_point.row() < visible_row_range.start {
 7422            return self.render_edit_prediction_scroll_popover(
 7423                |_| SCROLL_PADDING_Y,
 7424                IconName::ArrowUp,
 7425                visible_row_range,
 7426                line_layouts,
 7427                newest_selection_head,
 7428                scrolled_content_origin,
 7429                window,
 7430                cx,
 7431            );
 7432        } else if target_display_point.row() >= visible_row_range.end {
 7433            return self.render_edit_prediction_scroll_popover(
 7434                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7435                IconName::ArrowDown,
 7436                visible_row_range,
 7437                line_layouts,
 7438                newest_selection_head,
 7439                scrolled_content_origin,
 7440                window,
 7441                cx,
 7442            );
 7443        }
 7444
 7445        const POLE_WIDTH: Pixels = px(2.);
 7446
 7447        let line_layout =
 7448            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7449        let target_column = target_display_point.column() as usize;
 7450
 7451        let target_x = line_layout.x_for_index(target_column);
 7452        let target_y =
 7453            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7454
 7455        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7456
 7457        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7458        border_color.l += 0.001;
 7459
 7460        let mut element = v_flex()
 7461            .items_end()
 7462            .when(flag_on_right, |el| el.items_start())
 7463            .child(if flag_on_right {
 7464                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7465                    .rounded_bl(px(0.))
 7466                    .rounded_tl(px(0.))
 7467                    .border_l_2()
 7468                    .border_color(border_color)
 7469            } else {
 7470                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7471                    .rounded_br(px(0.))
 7472                    .rounded_tr(px(0.))
 7473                    .border_r_2()
 7474                    .border_color(border_color)
 7475            })
 7476            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7477            .into_any();
 7478
 7479        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7480
 7481        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7482            - point(
 7483                if flag_on_right {
 7484                    POLE_WIDTH
 7485                } else {
 7486                    size.width - POLE_WIDTH
 7487                },
 7488                size.height - line_height,
 7489            );
 7490
 7491        origin.x = origin.x.max(content_origin.x);
 7492
 7493        element.prepaint_at(origin, window, cx);
 7494
 7495        Some((element, origin))
 7496    }
 7497
 7498    fn render_edit_prediction_scroll_popover(
 7499        &mut self,
 7500        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7501        scroll_icon: IconName,
 7502        visible_row_range: Range<DisplayRow>,
 7503        line_layouts: &[LineWithInvisibles],
 7504        newest_selection_head: Option<DisplayPoint>,
 7505        scrolled_content_origin: gpui::Point<Pixels>,
 7506        window: &mut Window,
 7507        cx: &mut App,
 7508    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7509        let mut element = self
 7510            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7511            .into_any();
 7512
 7513        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7514
 7515        let cursor = newest_selection_head?;
 7516        let cursor_row_layout =
 7517            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7518        let cursor_column = cursor.column() as usize;
 7519
 7520        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7521
 7522        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7523
 7524        element.prepaint_at(origin, window, cx);
 7525        Some((element, origin))
 7526    }
 7527
 7528    fn render_edit_prediction_eager_jump_popover(
 7529        &mut self,
 7530        text_bounds: &Bounds<Pixels>,
 7531        content_origin: gpui::Point<Pixels>,
 7532        editor_snapshot: &EditorSnapshot,
 7533        visible_row_range: Range<DisplayRow>,
 7534        scroll_top: f32,
 7535        scroll_bottom: f32,
 7536        line_height: Pixels,
 7537        scroll_pixel_position: gpui::Point<Pixels>,
 7538        target_display_point: DisplayPoint,
 7539        editor_width: Pixels,
 7540        window: &mut Window,
 7541        cx: &mut App,
 7542    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7543        if target_display_point.row().as_f32() < scroll_top {
 7544            let mut element = self
 7545                .render_edit_prediction_line_popover(
 7546                    "Jump to Edit",
 7547                    Some(IconName::ArrowUp),
 7548                    window,
 7549                    cx,
 7550                )?
 7551                .into_any();
 7552
 7553            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7554            let offset = point(
 7555                (text_bounds.size.width - size.width) / 2.,
 7556                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7557            );
 7558
 7559            let origin = text_bounds.origin + offset;
 7560            element.prepaint_at(origin, window, cx);
 7561            Some((element, origin))
 7562        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7563            let mut element = self
 7564                .render_edit_prediction_line_popover(
 7565                    "Jump to Edit",
 7566                    Some(IconName::ArrowDown),
 7567                    window,
 7568                    cx,
 7569                )?
 7570                .into_any();
 7571
 7572            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7573            let offset = point(
 7574                (text_bounds.size.width - size.width) / 2.,
 7575                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7576            );
 7577
 7578            let origin = text_bounds.origin + offset;
 7579            element.prepaint_at(origin, window, cx);
 7580            Some((element, origin))
 7581        } else {
 7582            self.render_edit_prediction_end_of_line_popover(
 7583                "Jump to Edit",
 7584                editor_snapshot,
 7585                visible_row_range,
 7586                target_display_point,
 7587                line_height,
 7588                scroll_pixel_position,
 7589                content_origin,
 7590                editor_width,
 7591                window,
 7592                cx,
 7593            )
 7594        }
 7595    }
 7596
 7597    fn render_edit_prediction_end_of_line_popover(
 7598        self: &mut Editor,
 7599        label: &'static str,
 7600        editor_snapshot: &EditorSnapshot,
 7601        visible_row_range: Range<DisplayRow>,
 7602        target_display_point: DisplayPoint,
 7603        line_height: Pixels,
 7604        scroll_pixel_position: gpui::Point<Pixels>,
 7605        content_origin: gpui::Point<Pixels>,
 7606        editor_width: Pixels,
 7607        window: &mut Window,
 7608        cx: &mut App,
 7609    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7610        let target_line_end = DisplayPoint::new(
 7611            target_display_point.row(),
 7612            editor_snapshot.line_len(target_display_point.row()),
 7613        );
 7614
 7615        let mut element = self
 7616            .render_edit_prediction_line_popover(label, None, window, cx)?
 7617            .into_any();
 7618
 7619        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7620
 7621        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7622
 7623        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7624        let mut origin = start_point
 7625            + line_origin
 7626            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7627        origin.x = origin.x.max(content_origin.x);
 7628
 7629        let max_x = content_origin.x + editor_width - size.width;
 7630
 7631        if origin.x > max_x {
 7632            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7633
 7634            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7635                origin.y += offset;
 7636                IconName::ArrowUp
 7637            } else {
 7638                origin.y -= offset;
 7639                IconName::ArrowDown
 7640            };
 7641
 7642            element = self
 7643                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7644                .into_any();
 7645
 7646            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7647
 7648            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7649        }
 7650
 7651        element.prepaint_at(origin, window, cx);
 7652        Some((element, origin))
 7653    }
 7654
 7655    fn render_edit_prediction_diff_popover(
 7656        self: &Editor,
 7657        text_bounds: &Bounds<Pixels>,
 7658        content_origin: gpui::Point<Pixels>,
 7659        editor_snapshot: &EditorSnapshot,
 7660        visible_row_range: Range<DisplayRow>,
 7661        line_layouts: &[LineWithInvisibles],
 7662        line_height: Pixels,
 7663        scroll_pixel_position: gpui::Point<Pixels>,
 7664        newest_selection_head: Option<DisplayPoint>,
 7665        editor_width: Pixels,
 7666        style: &EditorStyle,
 7667        edits: &Vec<(Range<Anchor>, String)>,
 7668        edit_preview: &Option<language::EditPreview>,
 7669        snapshot: &language::BufferSnapshot,
 7670        window: &mut Window,
 7671        cx: &mut App,
 7672    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7673        let edit_start = edits
 7674            .first()
 7675            .unwrap()
 7676            .0
 7677            .start
 7678            .to_display_point(editor_snapshot);
 7679        let edit_end = edits
 7680            .last()
 7681            .unwrap()
 7682            .0
 7683            .end
 7684            .to_display_point(editor_snapshot);
 7685
 7686        let is_visible = visible_row_range.contains(&edit_start.row())
 7687            || visible_row_range.contains(&edit_end.row());
 7688        if !is_visible {
 7689            return None;
 7690        }
 7691
 7692        let highlighted_edits =
 7693            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7694
 7695        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7696        let line_count = highlighted_edits.text.lines().count();
 7697
 7698        const BORDER_WIDTH: Pixels = px(1.);
 7699
 7700        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7701        let has_keybind = keybind.is_some();
 7702
 7703        let mut element = h_flex()
 7704            .items_start()
 7705            .child(
 7706                h_flex()
 7707                    .bg(cx.theme().colors().editor_background)
 7708                    .border(BORDER_WIDTH)
 7709                    .shadow_sm()
 7710                    .border_color(cx.theme().colors().border)
 7711                    .rounded_l_lg()
 7712                    .when(line_count > 1, |el| el.rounded_br_lg())
 7713                    .pr_1()
 7714                    .child(styled_text),
 7715            )
 7716            .child(
 7717                h_flex()
 7718                    .h(line_height + BORDER_WIDTH * 2.)
 7719                    .px_1p5()
 7720                    .gap_1()
 7721                    // Workaround: For some reason, there's a gap if we don't do this
 7722                    .ml(-BORDER_WIDTH)
 7723                    .shadow(smallvec![gpui::BoxShadow {
 7724                        color: gpui::black().opacity(0.05),
 7725                        offset: point(px(1.), px(1.)),
 7726                        blur_radius: px(2.),
 7727                        spread_radius: px(0.),
 7728                    }])
 7729                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7730                    .border(BORDER_WIDTH)
 7731                    .border_color(cx.theme().colors().border)
 7732                    .rounded_r_lg()
 7733                    .id("edit_prediction_diff_popover_keybind")
 7734                    .when(!has_keybind, |el| {
 7735                        let status_colors = cx.theme().status();
 7736
 7737                        el.bg(status_colors.error_background)
 7738                            .border_color(status_colors.error.opacity(0.6))
 7739                            .child(Icon::new(IconName::Info).color(Color::Error))
 7740                            .cursor_default()
 7741                            .hoverable_tooltip(move |_window, cx| {
 7742                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7743                            })
 7744                    })
 7745                    .children(keybind),
 7746            )
 7747            .into_any();
 7748
 7749        let longest_row =
 7750            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7751        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7752            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7753        } else {
 7754            layout_line(
 7755                longest_row,
 7756                editor_snapshot,
 7757                style,
 7758                editor_width,
 7759                |_| false,
 7760                window,
 7761                cx,
 7762            )
 7763            .width
 7764        };
 7765
 7766        let viewport_bounds =
 7767            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7768                right: -EditorElement::SCROLLBAR_WIDTH,
 7769                ..Default::default()
 7770            });
 7771
 7772        let x_after_longest =
 7773            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7774                - scroll_pixel_position.x;
 7775
 7776        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7777
 7778        // Fully visible if it can be displayed within the window (allow overlapping other
 7779        // panes). However, this is only allowed if the popover starts within text_bounds.
 7780        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7781            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7782
 7783        let mut origin = if can_position_to_the_right {
 7784            point(
 7785                x_after_longest,
 7786                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7787                    - scroll_pixel_position.y,
 7788            )
 7789        } else {
 7790            let cursor_row = newest_selection_head.map(|head| head.row());
 7791            let above_edit = edit_start
 7792                .row()
 7793                .0
 7794                .checked_sub(line_count as u32)
 7795                .map(DisplayRow);
 7796            let below_edit = Some(edit_end.row() + 1);
 7797            let above_cursor =
 7798                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7799            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7800
 7801            // Place the edit popover adjacent to the edit if there is a location
 7802            // available that is onscreen and does not obscure the cursor. Otherwise,
 7803            // place it adjacent to the cursor.
 7804            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7805                .into_iter()
 7806                .flatten()
 7807                .find(|&start_row| {
 7808                    let end_row = start_row + line_count as u32;
 7809                    visible_row_range.contains(&start_row)
 7810                        && visible_row_range.contains(&end_row)
 7811                        && cursor_row.map_or(true, |cursor_row| {
 7812                            !((start_row..end_row).contains(&cursor_row))
 7813                        })
 7814                })?;
 7815
 7816            content_origin
 7817                + point(
 7818                    -scroll_pixel_position.x,
 7819                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7820                )
 7821        };
 7822
 7823        origin.x -= BORDER_WIDTH;
 7824
 7825        window.defer_draw(element, origin, 1);
 7826
 7827        // Do not return an element, since it will already be drawn due to defer_draw.
 7828        None
 7829    }
 7830
 7831    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7832        px(30.)
 7833    }
 7834
 7835    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7836        if self.read_only(cx) {
 7837            cx.theme().players().read_only()
 7838        } else {
 7839            self.style.as_ref().unwrap().local_player
 7840        }
 7841    }
 7842
 7843    fn render_edit_prediction_accept_keybind(
 7844        &self,
 7845        window: &mut Window,
 7846        cx: &App,
 7847    ) -> Option<AnyElement> {
 7848        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7849        let accept_keystroke = accept_binding.keystroke()?;
 7850
 7851        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7852
 7853        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7854            Color::Accent
 7855        } else {
 7856            Color::Muted
 7857        };
 7858
 7859        h_flex()
 7860            .px_0p5()
 7861            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7862            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7863            .text_size(TextSize::XSmall.rems(cx))
 7864            .child(h_flex().children(ui::render_modifiers(
 7865                &accept_keystroke.modifiers,
 7866                PlatformStyle::platform(),
 7867                Some(modifiers_color),
 7868                Some(IconSize::XSmall.rems().into()),
 7869                true,
 7870            )))
 7871            .when(is_platform_style_mac, |parent| {
 7872                parent.child(accept_keystroke.key.clone())
 7873            })
 7874            .when(!is_platform_style_mac, |parent| {
 7875                parent.child(
 7876                    Key::new(
 7877                        util::capitalize(&accept_keystroke.key),
 7878                        Some(Color::Default),
 7879                    )
 7880                    .size(Some(IconSize::XSmall.rems().into())),
 7881                )
 7882            })
 7883            .into_any()
 7884            .into()
 7885    }
 7886
 7887    fn render_edit_prediction_line_popover(
 7888        &self,
 7889        label: impl Into<SharedString>,
 7890        icon: Option<IconName>,
 7891        window: &mut Window,
 7892        cx: &App,
 7893    ) -> Option<Stateful<Div>> {
 7894        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7895
 7896        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7897        let has_keybind = keybind.is_some();
 7898
 7899        let result = h_flex()
 7900            .id("ep-line-popover")
 7901            .py_0p5()
 7902            .pl_1()
 7903            .pr(padding_right)
 7904            .gap_1()
 7905            .rounded_md()
 7906            .border_1()
 7907            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7908            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7909            .shadow_sm()
 7910            .when(!has_keybind, |el| {
 7911                let status_colors = cx.theme().status();
 7912
 7913                el.bg(status_colors.error_background)
 7914                    .border_color(status_colors.error.opacity(0.6))
 7915                    .pl_2()
 7916                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7917                    .cursor_default()
 7918                    .hoverable_tooltip(move |_window, cx| {
 7919                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7920                    })
 7921            })
 7922            .children(keybind)
 7923            .child(
 7924                Label::new(label)
 7925                    .size(LabelSize::Small)
 7926                    .when(!has_keybind, |el| {
 7927                        el.color(cx.theme().status().error.into()).strikethrough()
 7928                    }),
 7929            )
 7930            .when(!has_keybind, |el| {
 7931                el.child(
 7932                    h_flex().ml_1().child(
 7933                        Icon::new(IconName::Info)
 7934                            .size(IconSize::Small)
 7935                            .color(cx.theme().status().error.into()),
 7936                    ),
 7937                )
 7938            })
 7939            .when_some(icon, |element, icon| {
 7940                element.child(
 7941                    div()
 7942                        .mt(px(1.5))
 7943                        .child(Icon::new(icon).size(IconSize::Small)),
 7944                )
 7945            });
 7946
 7947        Some(result)
 7948    }
 7949
 7950    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7951        let accent_color = cx.theme().colors().text_accent;
 7952        let editor_bg_color = cx.theme().colors().editor_background;
 7953        editor_bg_color.blend(accent_color.opacity(0.1))
 7954    }
 7955
 7956    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7957        let accent_color = cx.theme().colors().text_accent;
 7958        let editor_bg_color = cx.theme().colors().editor_background;
 7959        editor_bg_color.blend(accent_color.opacity(0.6))
 7960    }
 7961
 7962    fn render_edit_prediction_cursor_popover(
 7963        &self,
 7964        min_width: Pixels,
 7965        max_width: Pixels,
 7966        cursor_point: Point,
 7967        style: &EditorStyle,
 7968        accept_keystroke: Option<&gpui::Keystroke>,
 7969        _window: &Window,
 7970        cx: &mut Context<Editor>,
 7971    ) -> Option<AnyElement> {
 7972        let provider = self.edit_prediction_provider.as_ref()?;
 7973
 7974        if provider.provider.needs_terms_acceptance(cx) {
 7975            return Some(
 7976                h_flex()
 7977                    .min_w(min_width)
 7978                    .flex_1()
 7979                    .px_2()
 7980                    .py_1()
 7981                    .gap_3()
 7982                    .elevation_2(cx)
 7983                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7984                    .id("accept-terms")
 7985                    .cursor_pointer()
 7986                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7987                    .on_click(cx.listener(|this, _event, window, cx| {
 7988                        cx.stop_propagation();
 7989                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7990                        window.dispatch_action(
 7991                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7992                            cx,
 7993                        );
 7994                    }))
 7995                    .child(
 7996                        h_flex()
 7997                            .flex_1()
 7998                            .gap_2()
 7999                            .child(Icon::new(IconName::ZedPredict))
 8000                            .child(Label::new("Accept Terms of Service"))
 8001                            .child(div().w_full())
 8002                            .child(
 8003                                Icon::new(IconName::ArrowUpRight)
 8004                                    .color(Color::Muted)
 8005                                    .size(IconSize::Small),
 8006                            )
 8007                            .into_any_element(),
 8008                    )
 8009                    .into_any(),
 8010            );
 8011        }
 8012
 8013        let is_refreshing = provider.provider.is_refreshing(cx);
 8014
 8015        fn pending_completion_container() -> Div {
 8016            h_flex()
 8017                .h_full()
 8018                .flex_1()
 8019                .gap_2()
 8020                .child(Icon::new(IconName::ZedPredict))
 8021        }
 8022
 8023        let completion = match &self.active_inline_completion {
 8024            Some(prediction) => {
 8025                if !self.has_visible_completions_menu() {
 8026                    const RADIUS: Pixels = px(6.);
 8027                    const BORDER_WIDTH: Pixels = px(1.);
 8028
 8029                    return Some(
 8030                        h_flex()
 8031                            .elevation_2(cx)
 8032                            .border(BORDER_WIDTH)
 8033                            .border_color(cx.theme().colors().border)
 8034                            .when(accept_keystroke.is_none(), |el| {
 8035                                el.border_color(cx.theme().status().error)
 8036                            })
 8037                            .rounded(RADIUS)
 8038                            .rounded_tl(px(0.))
 8039                            .overflow_hidden()
 8040                            .child(div().px_1p5().child(match &prediction.completion {
 8041                                InlineCompletion::Move { target, snapshot } => {
 8042                                    use text::ToPoint as _;
 8043                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 8044                                    {
 8045                                        Icon::new(IconName::ZedPredictDown)
 8046                                    } else {
 8047                                        Icon::new(IconName::ZedPredictUp)
 8048                                    }
 8049                                }
 8050                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 8051                            }))
 8052                            .child(
 8053                                h_flex()
 8054                                    .gap_1()
 8055                                    .py_1()
 8056                                    .px_2()
 8057                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8058                                    .border_l_1()
 8059                                    .border_color(cx.theme().colors().border)
 8060                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8061                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8062                                        el.child(
 8063                                            Label::new("Hold")
 8064                                                .size(LabelSize::Small)
 8065                                                .when(accept_keystroke.is_none(), |el| {
 8066                                                    el.strikethrough()
 8067                                                })
 8068                                                .line_height_style(LineHeightStyle::UiLabel),
 8069                                        )
 8070                                    })
 8071                                    .id("edit_prediction_cursor_popover_keybind")
 8072                                    .when(accept_keystroke.is_none(), |el| {
 8073                                        let status_colors = cx.theme().status();
 8074
 8075                                        el.bg(status_colors.error_background)
 8076                                            .border_color(status_colors.error.opacity(0.6))
 8077                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8078                                            .cursor_default()
 8079                                            .hoverable_tooltip(move |_window, cx| {
 8080                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8081                                                    .into()
 8082                                            })
 8083                                    })
 8084                                    .when_some(
 8085                                        accept_keystroke.as_ref(),
 8086                                        |el, accept_keystroke| {
 8087                                            el.child(h_flex().children(ui::render_modifiers(
 8088                                                &accept_keystroke.modifiers,
 8089                                                PlatformStyle::platform(),
 8090                                                Some(Color::Default),
 8091                                                Some(IconSize::XSmall.rems().into()),
 8092                                                false,
 8093                                            )))
 8094                                        },
 8095                                    ),
 8096                            )
 8097                            .into_any(),
 8098                    );
 8099                }
 8100
 8101                self.render_edit_prediction_cursor_popover_preview(
 8102                    prediction,
 8103                    cursor_point,
 8104                    style,
 8105                    cx,
 8106                )?
 8107            }
 8108
 8109            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8110                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8111                    stale_completion,
 8112                    cursor_point,
 8113                    style,
 8114                    cx,
 8115                )?,
 8116
 8117                None => {
 8118                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8119                }
 8120            },
 8121
 8122            None => pending_completion_container().child(Label::new("No Prediction")),
 8123        };
 8124
 8125        let completion = if is_refreshing {
 8126            completion
 8127                .with_animation(
 8128                    "loading-completion",
 8129                    Animation::new(Duration::from_secs(2))
 8130                        .repeat()
 8131                        .with_easing(pulsating_between(0.4, 0.8)),
 8132                    |label, delta| label.opacity(delta),
 8133                )
 8134                .into_any_element()
 8135        } else {
 8136            completion.into_any_element()
 8137        };
 8138
 8139        let has_completion = self.active_inline_completion.is_some();
 8140
 8141        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8142        Some(
 8143            h_flex()
 8144                .min_w(min_width)
 8145                .max_w(max_width)
 8146                .flex_1()
 8147                .elevation_2(cx)
 8148                .border_color(cx.theme().colors().border)
 8149                .child(
 8150                    div()
 8151                        .flex_1()
 8152                        .py_1()
 8153                        .px_2()
 8154                        .overflow_hidden()
 8155                        .child(completion),
 8156                )
 8157                .when_some(accept_keystroke, |el, accept_keystroke| {
 8158                    if !accept_keystroke.modifiers.modified() {
 8159                        return el;
 8160                    }
 8161
 8162                    el.child(
 8163                        h_flex()
 8164                            .h_full()
 8165                            .border_l_1()
 8166                            .rounded_r_lg()
 8167                            .border_color(cx.theme().colors().border)
 8168                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8169                            .gap_1()
 8170                            .py_1()
 8171                            .px_2()
 8172                            .child(
 8173                                h_flex()
 8174                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8175                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8176                                    .child(h_flex().children(ui::render_modifiers(
 8177                                        &accept_keystroke.modifiers,
 8178                                        PlatformStyle::platform(),
 8179                                        Some(if !has_completion {
 8180                                            Color::Muted
 8181                                        } else {
 8182                                            Color::Default
 8183                                        }),
 8184                                        None,
 8185                                        false,
 8186                                    ))),
 8187                            )
 8188                            .child(Label::new("Preview").into_any_element())
 8189                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8190                    )
 8191                })
 8192                .into_any(),
 8193        )
 8194    }
 8195
 8196    fn render_edit_prediction_cursor_popover_preview(
 8197        &self,
 8198        completion: &InlineCompletionState,
 8199        cursor_point: Point,
 8200        style: &EditorStyle,
 8201        cx: &mut Context<Editor>,
 8202    ) -> Option<Div> {
 8203        use text::ToPoint as _;
 8204
 8205        fn render_relative_row_jump(
 8206            prefix: impl Into<String>,
 8207            current_row: u32,
 8208            target_row: u32,
 8209        ) -> Div {
 8210            let (row_diff, arrow) = if target_row < current_row {
 8211                (current_row - target_row, IconName::ArrowUp)
 8212            } else {
 8213                (target_row - current_row, IconName::ArrowDown)
 8214            };
 8215
 8216            h_flex()
 8217                .child(
 8218                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8219                        .color(Color::Muted)
 8220                        .size(LabelSize::Small),
 8221                )
 8222                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8223        }
 8224
 8225        match &completion.completion {
 8226            InlineCompletion::Move {
 8227                target, snapshot, ..
 8228            } => Some(
 8229                h_flex()
 8230                    .px_2()
 8231                    .gap_2()
 8232                    .flex_1()
 8233                    .child(
 8234                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8235                            Icon::new(IconName::ZedPredictDown)
 8236                        } else {
 8237                            Icon::new(IconName::ZedPredictUp)
 8238                        },
 8239                    )
 8240                    .child(Label::new("Jump to Edit")),
 8241            ),
 8242
 8243            InlineCompletion::Edit {
 8244                edits,
 8245                edit_preview,
 8246                snapshot,
 8247                display_mode: _,
 8248            } => {
 8249                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8250
 8251                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8252                    &snapshot,
 8253                    &edits,
 8254                    edit_preview.as_ref()?,
 8255                    true,
 8256                    cx,
 8257                )
 8258                .first_line_preview();
 8259
 8260                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8261                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8262
 8263                let preview = h_flex()
 8264                    .gap_1()
 8265                    .min_w_16()
 8266                    .child(styled_text)
 8267                    .when(has_more_lines, |parent| parent.child(""));
 8268
 8269                let left = if first_edit_row != cursor_point.row {
 8270                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8271                        .into_any_element()
 8272                } else {
 8273                    Icon::new(IconName::ZedPredict).into_any_element()
 8274                };
 8275
 8276                Some(
 8277                    h_flex()
 8278                        .h_full()
 8279                        .flex_1()
 8280                        .gap_2()
 8281                        .pr_1()
 8282                        .overflow_x_hidden()
 8283                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8284                        .child(left)
 8285                        .child(preview),
 8286                )
 8287            }
 8288        }
 8289    }
 8290
 8291    fn render_context_menu(
 8292        &self,
 8293        style: &EditorStyle,
 8294        max_height_in_lines: u32,
 8295        window: &mut Window,
 8296        cx: &mut Context<Editor>,
 8297    ) -> Option<AnyElement> {
 8298        let menu = self.context_menu.borrow();
 8299        let menu = menu.as_ref()?;
 8300        if !menu.visible() {
 8301            return None;
 8302        };
 8303        Some(menu.render(style, max_height_in_lines, window, cx))
 8304    }
 8305
 8306    fn render_context_menu_aside(
 8307        &mut self,
 8308        max_size: Size<Pixels>,
 8309        window: &mut Window,
 8310        cx: &mut Context<Editor>,
 8311    ) -> Option<AnyElement> {
 8312        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8313            if menu.visible() {
 8314                menu.render_aside(self, max_size, window, cx)
 8315            } else {
 8316                None
 8317            }
 8318        })
 8319    }
 8320
 8321    fn hide_context_menu(
 8322        &mut self,
 8323        window: &mut Window,
 8324        cx: &mut Context<Self>,
 8325    ) -> Option<CodeContextMenu> {
 8326        cx.notify();
 8327        self.completion_tasks.clear();
 8328        let context_menu = self.context_menu.borrow_mut().take();
 8329        self.stale_inline_completion_in_menu.take();
 8330        self.update_visible_inline_completion(window, cx);
 8331        context_menu
 8332    }
 8333
 8334    fn show_snippet_choices(
 8335        &mut self,
 8336        choices: &Vec<String>,
 8337        selection: Range<Anchor>,
 8338        cx: &mut Context<Self>,
 8339    ) {
 8340        if selection.start.buffer_id.is_none() {
 8341            return;
 8342        }
 8343        let buffer_id = selection.start.buffer_id.unwrap();
 8344        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8345        let id = post_inc(&mut self.next_completion_id);
 8346        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8347
 8348        if let Some(buffer) = buffer {
 8349            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8350                CompletionsMenu::new_snippet_choices(
 8351                    id,
 8352                    true,
 8353                    choices,
 8354                    selection,
 8355                    buffer,
 8356                    snippet_sort_order,
 8357                ),
 8358            ));
 8359        }
 8360    }
 8361
 8362    pub fn insert_snippet(
 8363        &mut self,
 8364        insertion_ranges: &[Range<usize>],
 8365        snippet: Snippet,
 8366        window: &mut Window,
 8367        cx: &mut Context<Self>,
 8368    ) -> Result<()> {
 8369        struct Tabstop<T> {
 8370            is_end_tabstop: bool,
 8371            ranges: Vec<Range<T>>,
 8372            choices: Option<Vec<String>>,
 8373        }
 8374
 8375        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8376            let snippet_text: Arc<str> = snippet.text.clone().into();
 8377            let edits = insertion_ranges
 8378                .iter()
 8379                .cloned()
 8380                .map(|range| (range, snippet_text.clone()));
 8381            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8382
 8383            let snapshot = &*buffer.read(cx);
 8384            let snippet = &snippet;
 8385            snippet
 8386                .tabstops
 8387                .iter()
 8388                .map(|tabstop| {
 8389                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8390                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8391                    });
 8392                    let mut tabstop_ranges = tabstop
 8393                        .ranges
 8394                        .iter()
 8395                        .flat_map(|tabstop_range| {
 8396                            let mut delta = 0_isize;
 8397                            insertion_ranges.iter().map(move |insertion_range| {
 8398                                let insertion_start = insertion_range.start as isize + delta;
 8399                                delta +=
 8400                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8401
 8402                                let start = ((insertion_start + tabstop_range.start) as usize)
 8403                                    .min(snapshot.len());
 8404                                let end = ((insertion_start + tabstop_range.end) as usize)
 8405                                    .min(snapshot.len());
 8406                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8407                            })
 8408                        })
 8409                        .collect::<Vec<_>>();
 8410                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8411
 8412                    Tabstop {
 8413                        is_end_tabstop,
 8414                        ranges: tabstop_ranges,
 8415                        choices: tabstop.choices.clone(),
 8416                    }
 8417                })
 8418                .collect::<Vec<_>>()
 8419        });
 8420        if let Some(tabstop) = tabstops.first() {
 8421            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8422                s.select_ranges(tabstop.ranges.iter().cloned());
 8423            });
 8424
 8425            if let Some(choices) = &tabstop.choices {
 8426                if let Some(selection) = tabstop.ranges.first() {
 8427                    self.show_snippet_choices(choices, selection.clone(), cx)
 8428                }
 8429            }
 8430
 8431            // If we're already at the last tabstop and it's at the end of the snippet,
 8432            // we're done, we don't need to keep the state around.
 8433            if !tabstop.is_end_tabstop {
 8434                let choices = tabstops
 8435                    .iter()
 8436                    .map(|tabstop| tabstop.choices.clone())
 8437                    .collect();
 8438
 8439                let ranges = tabstops
 8440                    .into_iter()
 8441                    .map(|tabstop| tabstop.ranges)
 8442                    .collect::<Vec<_>>();
 8443
 8444                self.snippet_stack.push(SnippetState {
 8445                    active_index: 0,
 8446                    ranges,
 8447                    choices,
 8448                });
 8449            }
 8450
 8451            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8452            if self.autoclose_regions.is_empty() {
 8453                let snapshot = self.buffer.read(cx).snapshot(cx);
 8454                for selection in &mut self.selections.all::<Point>(cx) {
 8455                    let selection_head = selection.head();
 8456                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8457                        continue;
 8458                    };
 8459
 8460                    let mut bracket_pair = None;
 8461                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8462                    let prev_chars = snapshot
 8463                        .reversed_chars_at(selection_head)
 8464                        .collect::<String>();
 8465                    for (pair, enabled) in scope.brackets() {
 8466                        if enabled
 8467                            && pair.close
 8468                            && prev_chars.starts_with(pair.start.as_str())
 8469                            && next_chars.starts_with(pair.end.as_str())
 8470                        {
 8471                            bracket_pair = Some(pair.clone());
 8472                            break;
 8473                        }
 8474                    }
 8475                    if let Some(pair) = bracket_pair {
 8476                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8477                        let autoclose_enabled =
 8478                            self.use_autoclose && snapshot_settings.use_autoclose;
 8479                        if autoclose_enabled {
 8480                            let start = snapshot.anchor_after(selection_head);
 8481                            let end = snapshot.anchor_after(selection_head);
 8482                            self.autoclose_regions.push(AutocloseRegion {
 8483                                selection_id: selection.id,
 8484                                range: start..end,
 8485                                pair,
 8486                            });
 8487                        }
 8488                    }
 8489                }
 8490            }
 8491        }
 8492        Ok(())
 8493    }
 8494
 8495    pub fn move_to_next_snippet_tabstop(
 8496        &mut self,
 8497        window: &mut Window,
 8498        cx: &mut Context<Self>,
 8499    ) -> bool {
 8500        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8501    }
 8502
 8503    pub fn move_to_prev_snippet_tabstop(
 8504        &mut self,
 8505        window: &mut Window,
 8506        cx: &mut Context<Self>,
 8507    ) -> bool {
 8508        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8509    }
 8510
 8511    pub fn move_to_snippet_tabstop(
 8512        &mut self,
 8513        bias: Bias,
 8514        window: &mut Window,
 8515        cx: &mut Context<Self>,
 8516    ) -> bool {
 8517        if let Some(mut snippet) = self.snippet_stack.pop() {
 8518            match bias {
 8519                Bias::Left => {
 8520                    if snippet.active_index > 0 {
 8521                        snippet.active_index -= 1;
 8522                    } else {
 8523                        self.snippet_stack.push(snippet);
 8524                        return false;
 8525                    }
 8526                }
 8527                Bias::Right => {
 8528                    if snippet.active_index + 1 < snippet.ranges.len() {
 8529                        snippet.active_index += 1;
 8530                    } else {
 8531                        self.snippet_stack.push(snippet);
 8532                        return false;
 8533                    }
 8534                }
 8535            }
 8536            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8537                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8538                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8539                });
 8540
 8541                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8542                    if let Some(selection) = current_ranges.first() {
 8543                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8544                    }
 8545                }
 8546
 8547                // If snippet state is not at the last tabstop, push it back on the stack
 8548                if snippet.active_index + 1 < snippet.ranges.len() {
 8549                    self.snippet_stack.push(snippet);
 8550                }
 8551                return true;
 8552            }
 8553        }
 8554
 8555        false
 8556    }
 8557
 8558    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8559        self.transact(window, cx, |this, window, cx| {
 8560            this.select_all(&SelectAll, window, cx);
 8561            this.insert("", window, cx);
 8562        });
 8563    }
 8564
 8565    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8566        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8567        self.transact(window, cx, |this, window, cx| {
 8568            this.select_autoclose_pair(window, cx);
 8569            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8570            if !this.linked_edit_ranges.is_empty() {
 8571                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8572                let snapshot = this.buffer.read(cx).snapshot(cx);
 8573
 8574                for selection in selections.iter() {
 8575                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8576                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8577                    if selection_start.buffer_id != selection_end.buffer_id {
 8578                        continue;
 8579                    }
 8580                    if let Some(ranges) =
 8581                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8582                    {
 8583                        for (buffer, entries) in ranges {
 8584                            linked_ranges.entry(buffer).or_default().extend(entries);
 8585                        }
 8586                    }
 8587                }
 8588            }
 8589
 8590            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8591            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8592            for selection in &mut selections {
 8593                if selection.is_empty() {
 8594                    let old_head = selection.head();
 8595                    let mut new_head =
 8596                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8597                            .to_point(&display_map);
 8598                    if let Some((buffer, line_buffer_range)) = display_map
 8599                        .buffer_snapshot
 8600                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8601                    {
 8602                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8603                        let indent_len = match indent_size.kind {
 8604                            IndentKind::Space => {
 8605                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8606                            }
 8607                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8608                        };
 8609                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8610                            let indent_len = indent_len.get();
 8611                            new_head = cmp::min(
 8612                                new_head,
 8613                                MultiBufferPoint::new(
 8614                                    old_head.row,
 8615                                    ((old_head.column - 1) / indent_len) * indent_len,
 8616                                ),
 8617                            );
 8618                        }
 8619                    }
 8620
 8621                    selection.set_head(new_head, SelectionGoal::None);
 8622                }
 8623            }
 8624
 8625            this.signature_help_state.set_backspace_pressed(true);
 8626            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8627                s.select(selections)
 8628            });
 8629            this.insert("", window, cx);
 8630            let empty_str: Arc<str> = Arc::from("");
 8631            for (buffer, edits) in linked_ranges {
 8632                let snapshot = buffer.read(cx).snapshot();
 8633                use text::ToPoint as TP;
 8634
 8635                let edits = edits
 8636                    .into_iter()
 8637                    .map(|range| {
 8638                        let end_point = TP::to_point(&range.end, &snapshot);
 8639                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8640
 8641                        if end_point == start_point {
 8642                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8643                                .saturating_sub(1);
 8644                            start_point =
 8645                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8646                        };
 8647
 8648                        (start_point..end_point, empty_str.clone())
 8649                    })
 8650                    .sorted_by_key(|(range, _)| range.start)
 8651                    .collect::<Vec<_>>();
 8652                buffer.update(cx, |this, cx| {
 8653                    this.edit(edits, None, cx);
 8654                })
 8655            }
 8656            this.refresh_inline_completion(true, false, window, cx);
 8657            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8658        });
 8659    }
 8660
 8661    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8662        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8663        self.transact(window, cx, |this, window, cx| {
 8664            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8665                s.move_with(|map, selection| {
 8666                    if selection.is_empty() {
 8667                        let cursor = movement::right(map, selection.head());
 8668                        selection.end = cursor;
 8669                        selection.reversed = true;
 8670                        selection.goal = SelectionGoal::None;
 8671                    }
 8672                })
 8673            });
 8674            this.insert("", window, cx);
 8675            this.refresh_inline_completion(true, false, window, cx);
 8676        });
 8677    }
 8678
 8679    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8680        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8681        if self.move_to_prev_snippet_tabstop(window, cx) {
 8682            return;
 8683        }
 8684        self.outdent(&Outdent, window, cx);
 8685    }
 8686
 8687    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8688        if self.move_to_next_snippet_tabstop(window, cx) {
 8689            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8690            return;
 8691        }
 8692        if self.read_only(cx) {
 8693            return;
 8694        }
 8695        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8696        let mut selections = self.selections.all_adjusted(cx);
 8697        let buffer = self.buffer.read(cx);
 8698        let snapshot = buffer.snapshot(cx);
 8699        let rows_iter = selections.iter().map(|s| s.head().row);
 8700        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8701
 8702        let has_some_cursor_in_whitespace = selections
 8703            .iter()
 8704            .filter(|selection| selection.is_empty())
 8705            .any(|selection| {
 8706                let cursor = selection.head();
 8707                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8708                cursor.column < current_indent.len
 8709            });
 8710
 8711        let mut edits = Vec::new();
 8712        let mut prev_edited_row = 0;
 8713        let mut row_delta = 0;
 8714        for selection in &mut selections {
 8715            if selection.start.row != prev_edited_row {
 8716                row_delta = 0;
 8717            }
 8718            prev_edited_row = selection.end.row;
 8719
 8720            // If the selection is non-empty, then increase the indentation of the selected lines.
 8721            if !selection.is_empty() {
 8722                row_delta =
 8723                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8724                continue;
 8725            }
 8726
 8727            // If the selection is empty and the cursor is in the leading whitespace before the
 8728            // suggested indentation, then auto-indent the line.
 8729            let cursor = selection.head();
 8730            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8731            if let Some(suggested_indent) =
 8732                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8733            {
 8734                // If there exist any empty selection in the leading whitespace, then skip
 8735                // indent for selections at the boundary.
 8736                if has_some_cursor_in_whitespace
 8737                    && cursor.column == current_indent.len
 8738                    && current_indent.len == suggested_indent.len
 8739                {
 8740                    continue;
 8741                }
 8742
 8743                if cursor.column < suggested_indent.len
 8744                    && cursor.column <= current_indent.len
 8745                    && current_indent.len <= suggested_indent.len
 8746                {
 8747                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8748                    selection.end = selection.start;
 8749                    if row_delta == 0 {
 8750                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8751                            cursor.row,
 8752                            current_indent,
 8753                            suggested_indent,
 8754                        ));
 8755                        row_delta = suggested_indent.len - current_indent.len;
 8756                    }
 8757                    continue;
 8758                }
 8759            }
 8760
 8761            // Otherwise, insert a hard or soft tab.
 8762            let settings = buffer.language_settings_at(cursor, cx);
 8763            let tab_size = if settings.hard_tabs {
 8764                IndentSize::tab()
 8765            } else {
 8766                let tab_size = settings.tab_size.get();
 8767                let indent_remainder = snapshot
 8768                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8769                    .flat_map(str::chars)
 8770                    .fold(row_delta % tab_size, |counter: u32, c| {
 8771                        if c == '\t' {
 8772                            0
 8773                        } else {
 8774                            (counter + 1) % tab_size
 8775                        }
 8776                    });
 8777
 8778                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8779                IndentSize::spaces(chars_to_next_tab_stop)
 8780            };
 8781            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8782            selection.end = selection.start;
 8783            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8784            row_delta += tab_size.len;
 8785        }
 8786
 8787        self.transact(window, cx, |this, window, cx| {
 8788            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8789            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8790                s.select(selections)
 8791            });
 8792            this.refresh_inline_completion(true, false, window, cx);
 8793        });
 8794    }
 8795
 8796    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8797        if self.read_only(cx) {
 8798            return;
 8799        }
 8800        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8801        let mut selections = self.selections.all::<Point>(cx);
 8802        let mut prev_edited_row = 0;
 8803        let mut row_delta = 0;
 8804        let mut edits = Vec::new();
 8805        let buffer = self.buffer.read(cx);
 8806        let snapshot = buffer.snapshot(cx);
 8807        for selection in &mut selections {
 8808            if selection.start.row != prev_edited_row {
 8809                row_delta = 0;
 8810            }
 8811            prev_edited_row = selection.end.row;
 8812
 8813            row_delta =
 8814                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8815        }
 8816
 8817        self.transact(window, cx, |this, window, cx| {
 8818            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8819            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8820                s.select(selections)
 8821            });
 8822        });
 8823    }
 8824
 8825    fn indent_selection(
 8826        buffer: &MultiBuffer,
 8827        snapshot: &MultiBufferSnapshot,
 8828        selection: &mut Selection<Point>,
 8829        edits: &mut Vec<(Range<Point>, String)>,
 8830        delta_for_start_row: u32,
 8831        cx: &App,
 8832    ) -> u32 {
 8833        let settings = buffer.language_settings_at(selection.start, cx);
 8834        let tab_size = settings.tab_size.get();
 8835        let indent_kind = if settings.hard_tabs {
 8836            IndentKind::Tab
 8837        } else {
 8838            IndentKind::Space
 8839        };
 8840        let mut start_row = selection.start.row;
 8841        let mut end_row = selection.end.row + 1;
 8842
 8843        // If a selection ends at the beginning of a line, don't indent
 8844        // that last line.
 8845        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8846            end_row -= 1;
 8847        }
 8848
 8849        // Avoid re-indenting a row that has already been indented by a
 8850        // previous selection, but still update this selection's column
 8851        // to reflect that indentation.
 8852        if delta_for_start_row > 0 {
 8853            start_row += 1;
 8854            selection.start.column += delta_for_start_row;
 8855            if selection.end.row == selection.start.row {
 8856                selection.end.column += delta_for_start_row;
 8857            }
 8858        }
 8859
 8860        let mut delta_for_end_row = 0;
 8861        let has_multiple_rows = start_row + 1 != end_row;
 8862        for row in start_row..end_row {
 8863            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8864            let indent_delta = match (current_indent.kind, indent_kind) {
 8865                (IndentKind::Space, IndentKind::Space) => {
 8866                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8867                    IndentSize::spaces(columns_to_next_tab_stop)
 8868                }
 8869                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8870                (_, IndentKind::Tab) => IndentSize::tab(),
 8871            };
 8872
 8873            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8874                0
 8875            } else {
 8876                selection.start.column
 8877            };
 8878            let row_start = Point::new(row, start);
 8879            edits.push((
 8880                row_start..row_start,
 8881                indent_delta.chars().collect::<String>(),
 8882            ));
 8883
 8884            // Update this selection's endpoints to reflect the indentation.
 8885            if row == selection.start.row {
 8886                selection.start.column += indent_delta.len;
 8887            }
 8888            if row == selection.end.row {
 8889                selection.end.column += indent_delta.len;
 8890                delta_for_end_row = indent_delta.len;
 8891            }
 8892        }
 8893
 8894        if selection.start.row == selection.end.row {
 8895            delta_for_start_row + delta_for_end_row
 8896        } else {
 8897            delta_for_end_row
 8898        }
 8899    }
 8900
 8901    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8902        if self.read_only(cx) {
 8903            return;
 8904        }
 8905        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8906        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8907        let selections = self.selections.all::<Point>(cx);
 8908        let mut deletion_ranges = Vec::new();
 8909        let mut last_outdent = None;
 8910        {
 8911            let buffer = self.buffer.read(cx);
 8912            let snapshot = buffer.snapshot(cx);
 8913            for selection in &selections {
 8914                let settings = buffer.language_settings_at(selection.start, cx);
 8915                let tab_size = settings.tab_size.get();
 8916                let mut rows = selection.spanned_rows(false, &display_map);
 8917
 8918                // Avoid re-outdenting a row that has already been outdented by a
 8919                // previous selection.
 8920                if let Some(last_row) = last_outdent {
 8921                    if last_row == rows.start {
 8922                        rows.start = rows.start.next_row();
 8923                    }
 8924                }
 8925                let has_multiple_rows = rows.len() > 1;
 8926                for row in rows.iter_rows() {
 8927                    let indent_size = snapshot.indent_size_for_line(row);
 8928                    if indent_size.len > 0 {
 8929                        let deletion_len = match indent_size.kind {
 8930                            IndentKind::Space => {
 8931                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8932                                if columns_to_prev_tab_stop == 0 {
 8933                                    tab_size
 8934                                } else {
 8935                                    columns_to_prev_tab_stop
 8936                                }
 8937                            }
 8938                            IndentKind::Tab => 1,
 8939                        };
 8940                        let start = if has_multiple_rows
 8941                            || deletion_len > selection.start.column
 8942                            || indent_size.len < selection.start.column
 8943                        {
 8944                            0
 8945                        } else {
 8946                            selection.start.column - deletion_len
 8947                        };
 8948                        deletion_ranges.push(
 8949                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8950                        );
 8951                        last_outdent = Some(row);
 8952                    }
 8953                }
 8954            }
 8955        }
 8956
 8957        self.transact(window, cx, |this, window, cx| {
 8958            this.buffer.update(cx, |buffer, cx| {
 8959                let empty_str: Arc<str> = Arc::default();
 8960                buffer.edit(
 8961                    deletion_ranges
 8962                        .into_iter()
 8963                        .map(|range| (range, empty_str.clone())),
 8964                    None,
 8965                    cx,
 8966                );
 8967            });
 8968            let selections = this.selections.all::<usize>(cx);
 8969            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8970                s.select(selections)
 8971            });
 8972        });
 8973    }
 8974
 8975    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8976        if self.read_only(cx) {
 8977            return;
 8978        }
 8979        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8980        let selections = self
 8981            .selections
 8982            .all::<usize>(cx)
 8983            .into_iter()
 8984            .map(|s| s.range());
 8985
 8986        self.transact(window, cx, |this, window, cx| {
 8987            this.buffer.update(cx, |buffer, cx| {
 8988                buffer.autoindent_ranges(selections, cx);
 8989            });
 8990            let selections = this.selections.all::<usize>(cx);
 8991            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8992                s.select(selections)
 8993            });
 8994        });
 8995    }
 8996
 8997    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8998        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8999        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9000        let selections = self.selections.all::<Point>(cx);
 9001
 9002        let mut new_cursors = Vec::new();
 9003        let mut edit_ranges = Vec::new();
 9004        let mut selections = selections.iter().peekable();
 9005        while let Some(selection) = selections.next() {
 9006            let mut rows = selection.spanned_rows(false, &display_map);
 9007            let goal_display_column = selection.head().to_display_point(&display_map).column();
 9008
 9009            // Accumulate contiguous regions of rows that we want to delete.
 9010            while let Some(next_selection) = selections.peek() {
 9011                let next_rows = next_selection.spanned_rows(false, &display_map);
 9012                if next_rows.start <= rows.end {
 9013                    rows.end = next_rows.end;
 9014                    selections.next().unwrap();
 9015                } else {
 9016                    break;
 9017                }
 9018            }
 9019
 9020            let buffer = &display_map.buffer_snapshot;
 9021            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 9022            let edit_end;
 9023            let cursor_buffer_row;
 9024            if buffer.max_point().row >= rows.end.0 {
 9025                // If there's a line after the range, delete the \n from the end of the row range
 9026                // and position the cursor on the next line.
 9027                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 9028                cursor_buffer_row = rows.end;
 9029            } else {
 9030                // If there isn't a line after the range, delete the \n from the line before the
 9031                // start of the row range and position the cursor there.
 9032                edit_start = edit_start.saturating_sub(1);
 9033                edit_end = buffer.len();
 9034                cursor_buffer_row = rows.start.previous_row();
 9035            }
 9036
 9037            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 9038            *cursor.column_mut() =
 9039                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 9040
 9041            new_cursors.push((
 9042                selection.id,
 9043                buffer.anchor_after(cursor.to_point(&display_map)),
 9044            ));
 9045            edit_ranges.push(edit_start..edit_end);
 9046        }
 9047
 9048        self.transact(window, cx, |this, window, cx| {
 9049            let buffer = this.buffer.update(cx, |buffer, cx| {
 9050                let empty_str: Arc<str> = Arc::default();
 9051                buffer.edit(
 9052                    edit_ranges
 9053                        .into_iter()
 9054                        .map(|range| (range, empty_str.clone())),
 9055                    None,
 9056                    cx,
 9057                );
 9058                buffer.snapshot(cx)
 9059            });
 9060            let new_selections = new_cursors
 9061                .into_iter()
 9062                .map(|(id, cursor)| {
 9063                    let cursor = cursor.to_point(&buffer);
 9064                    Selection {
 9065                        id,
 9066                        start: cursor,
 9067                        end: cursor,
 9068                        reversed: false,
 9069                        goal: SelectionGoal::None,
 9070                    }
 9071                })
 9072                .collect();
 9073
 9074            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9075                s.select(new_selections);
 9076            });
 9077        });
 9078    }
 9079
 9080    pub fn join_lines_impl(
 9081        &mut self,
 9082        insert_whitespace: bool,
 9083        window: &mut Window,
 9084        cx: &mut Context<Self>,
 9085    ) {
 9086        if self.read_only(cx) {
 9087            return;
 9088        }
 9089        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9090        for selection in self.selections.all::<Point>(cx) {
 9091            let start = MultiBufferRow(selection.start.row);
 9092            // Treat single line selections as if they include the next line. Otherwise this action
 9093            // would do nothing for single line selections individual cursors.
 9094            let end = if selection.start.row == selection.end.row {
 9095                MultiBufferRow(selection.start.row + 1)
 9096            } else {
 9097                MultiBufferRow(selection.end.row)
 9098            };
 9099
 9100            if let Some(last_row_range) = row_ranges.last_mut() {
 9101                if start <= last_row_range.end {
 9102                    last_row_range.end = end;
 9103                    continue;
 9104                }
 9105            }
 9106            row_ranges.push(start..end);
 9107        }
 9108
 9109        let snapshot = self.buffer.read(cx).snapshot(cx);
 9110        let mut cursor_positions = Vec::new();
 9111        for row_range in &row_ranges {
 9112            let anchor = snapshot.anchor_before(Point::new(
 9113                row_range.end.previous_row().0,
 9114                snapshot.line_len(row_range.end.previous_row()),
 9115            ));
 9116            cursor_positions.push(anchor..anchor);
 9117        }
 9118
 9119        self.transact(window, cx, |this, window, cx| {
 9120            for row_range in row_ranges.into_iter().rev() {
 9121                for row in row_range.iter_rows().rev() {
 9122                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9123                    let next_line_row = row.next_row();
 9124                    let indent = snapshot.indent_size_for_line(next_line_row);
 9125                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9126
 9127                    let replace =
 9128                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9129                            " "
 9130                        } else {
 9131                            ""
 9132                        };
 9133
 9134                    this.buffer.update(cx, |buffer, cx| {
 9135                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9136                    });
 9137                }
 9138            }
 9139
 9140            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9141                s.select_anchor_ranges(cursor_positions)
 9142            });
 9143        });
 9144    }
 9145
 9146    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9147        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9148        self.join_lines_impl(true, window, cx);
 9149    }
 9150
 9151    pub fn sort_lines_case_sensitive(
 9152        &mut self,
 9153        _: &SortLinesCaseSensitive,
 9154        window: &mut Window,
 9155        cx: &mut Context<Self>,
 9156    ) {
 9157        self.manipulate_lines(window, cx, |lines| lines.sort())
 9158    }
 9159
 9160    pub fn sort_lines_case_insensitive(
 9161        &mut self,
 9162        _: &SortLinesCaseInsensitive,
 9163        window: &mut Window,
 9164        cx: &mut Context<Self>,
 9165    ) {
 9166        self.manipulate_lines(window, cx, |lines| {
 9167            lines.sort_by_key(|line| line.to_lowercase())
 9168        })
 9169    }
 9170
 9171    pub fn unique_lines_case_insensitive(
 9172        &mut self,
 9173        _: &UniqueLinesCaseInsensitive,
 9174        window: &mut Window,
 9175        cx: &mut Context<Self>,
 9176    ) {
 9177        self.manipulate_lines(window, cx, |lines| {
 9178            let mut seen = HashSet::default();
 9179            lines.retain(|line| seen.insert(line.to_lowercase()));
 9180        })
 9181    }
 9182
 9183    pub fn unique_lines_case_sensitive(
 9184        &mut self,
 9185        _: &UniqueLinesCaseSensitive,
 9186        window: &mut Window,
 9187        cx: &mut Context<Self>,
 9188    ) {
 9189        self.manipulate_lines(window, cx, |lines| {
 9190            let mut seen = HashSet::default();
 9191            lines.retain(|line| seen.insert(*line));
 9192        })
 9193    }
 9194
 9195    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9196        let Some(project) = self.project.clone() else {
 9197            return;
 9198        };
 9199        self.reload(project, window, cx)
 9200            .detach_and_notify_err(window, cx);
 9201    }
 9202
 9203    pub fn restore_file(
 9204        &mut self,
 9205        _: &::git::RestoreFile,
 9206        window: &mut Window,
 9207        cx: &mut Context<Self>,
 9208    ) {
 9209        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9210        let mut buffer_ids = HashSet::default();
 9211        let snapshot = self.buffer().read(cx).snapshot(cx);
 9212        for selection in self.selections.all::<usize>(cx) {
 9213            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9214        }
 9215
 9216        let buffer = self.buffer().read(cx);
 9217        let ranges = buffer_ids
 9218            .into_iter()
 9219            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9220            .collect::<Vec<_>>();
 9221
 9222        self.restore_hunks_in_ranges(ranges, window, cx);
 9223    }
 9224
 9225    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9226        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9227        let selections = self
 9228            .selections
 9229            .all(cx)
 9230            .into_iter()
 9231            .map(|s| s.range())
 9232            .collect();
 9233        self.restore_hunks_in_ranges(selections, window, cx);
 9234    }
 9235
 9236    pub fn restore_hunks_in_ranges(
 9237        &mut self,
 9238        ranges: Vec<Range<Point>>,
 9239        window: &mut Window,
 9240        cx: &mut Context<Editor>,
 9241    ) {
 9242        let mut revert_changes = HashMap::default();
 9243        let chunk_by = self
 9244            .snapshot(window, cx)
 9245            .hunks_for_ranges(ranges)
 9246            .into_iter()
 9247            .chunk_by(|hunk| hunk.buffer_id);
 9248        for (buffer_id, hunks) in &chunk_by {
 9249            let hunks = hunks.collect::<Vec<_>>();
 9250            for hunk in &hunks {
 9251                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9252            }
 9253            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9254        }
 9255        drop(chunk_by);
 9256        if !revert_changes.is_empty() {
 9257            self.transact(window, cx, |editor, window, cx| {
 9258                editor.restore(revert_changes, window, cx);
 9259            });
 9260        }
 9261    }
 9262
 9263    pub fn open_active_item_in_terminal(
 9264        &mut self,
 9265        _: &OpenInTerminal,
 9266        window: &mut Window,
 9267        cx: &mut Context<Self>,
 9268    ) {
 9269        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9270            let project_path = buffer.read(cx).project_path(cx)?;
 9271            let project = self.project.as_ref()?.read(cx);
 9272            let entry = project.entry_for_path(&project_path, cx)?;
 9273            let parent = match &entry.canonical_path {
 9274                Some(canonical_path) => canonical_path.to_path_buf(),
 9275                None => project.absolute_path(&project_path, cx)?,
 9276            }
 9277            .parent()?
 9278            .to_path_buf();
 9279            Some(parent)
 9280        }) {
 9281            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9282        }
 9283    }
 9284
 9285    fn set_breakpoint_context_menu(
 9286        &mut self,
 9287        display_row: DisplayRow,
 9288        position: Option<Anchor>,
 9289        clicked_point: gpui::Point<Pixels>,
 9290        window: &mut Window,
 9291        cx: &mut Context<Self>,
 9292    ) {
 9293        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9294            return;
 9295        }
 9296        let source = self
 9297            .buffer
 9298            .read(cx)
 9299            .snapshot(cx)
 9300            .anchor_before(Point::new(display_row.0, 0u32));
 9301
 9302        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9303
 9304        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9305            self,
 9306            source,
 9307            clicked_point,
 9308            context_menu,
 9309            window,
 9310            cx,
 9311        );
 9312    }
 9313
 9314    fn add_edit_breakpoint_block(
 9315        &mut self,
 9316        anchor: Anchor,
 9317        breakpoint: &Breakpoint,
 9318        edit_action: BreakpointPromptEditAction,
 9319        window: &mut Window,
 9320        cx: &mut Context<Self>,
 9321    ) {
 9322        let weak_editor = cx.weak_entity();
 9323        let bp_prompt = cx.new(|cx| {
 9324            BreakpointPromptEditor::new(
 9325                weak_editor,
 9326                anchor,
 9327                breakpoint.clone(),
 9328                edit_action,
 9329                window,
 9330                cx,
 9331            )
 9332        });
 9333
 9334        let height = bp_prompt.update(cx, |this, cx| {
 9335            this.prompt
 9336                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9337        });
 9338        let cloned_prompt = bp_prompt.clone();
 9339        let blocks = vec![BlockProperties {
 9340            style: BlockStyle::Sticky,
 9341            placement: BlockPlacement::Above(anchor),
 9342            height: Some(height),
 9343            render: Arc::new(move |cx| {
 9344                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9345                cloned_prompt.clone().into_any_element()
 9346            }),
 9347            priority: 0,
 9348        }];
 9349
 9350        let focus_handle = bp_prompt.focus_handle(cx);
 9351        window.focus(&focus_handle);
 9352
 9353        let block_ids = self.insert_blocks(blocks, None, cx);
 9354        bp_prompt.update(cx, |prompt, _| {
 9355            prompt.add_block_ids(block_ids);
 9356        });
 9357    }
 9358
 9359    pub(crate) fn breakpoint_at_row(
 9360        &self,
 9361        row: u32,
 9362        window: &mut Window,
 9363        cx: &mut Context<Self>,
 9364    ) -> Option<(Anchor, Breakpoint)> {
 9365        let snapshot = self.snapshot(window, cx);
 9366        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9367
 9368        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9369    }
 9370
 9371    pub(crate) fn breakpoint_at_anchor(
 9372        &self,
 9373        breakpoint_position: Anchor,
 9374        snapshot: &EditorSnapshot,
 9375        cx: &mut Context<Self>,
 9376    ) -> Option<(Anchor, Breakpoint)> {
 9377        let project = self.project.clone()?;
 9378
 9379        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9380            snapshot
 9381                .buffer_snapshot
 9382                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9383        })?;
 9384
 9385        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9386        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9387        let buffer_snapshot = buffer.read(cx).snapshot();
 9388
 9389        let row = buffer_snapshot
 9390            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9391            .row;
 9392
 9393        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9394        let anchor_end = snapshot
 9395            .buffer_snapshot
 9396            .anchor_after(Point::new(row, line_len));
 9397
 9398        let bp = self
 9399            .breakpoint_store
 9400            .as_ref()?
 9401            .read_with(cx, |breakpoint_store, cx| {
 9402                breakpoint_store
 9403                    .breakpoints(
 9404                        &buffer,
 9405                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9406                        &buffer_snapshot,
 9407                        cx,
 9408                    )
 9409                    .next()
 9410                    .and_then(|(anchor, bp)| {
 9411                        let breakpoint_row = buffer_snapshot
 9412                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9413                            .row;
 9414
 9415                        if breakpoint_row == row {
 9416                            snapshot
 9417                                .buffer_snapshot
 9418                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9419                                .map(|anchor| (anchor, bp.clone()))
 9420                        } else {
 9421                            None
 9422                        }
 9423                    })
 9424            });
 9425        bp
 9426    }
 9427
 9428    pub fn edit_log_breakpoint(
 9429        &mut self,
 9430        _: &EditLogBreakpoint,
 9431        window: &mut Window,
 9432        cx: &mut Context<Self>,
 9433    ) {
 9434        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9435            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9436                message: None,
 9437                state: BreakpointState::Enabled,
 9438                condition: None,
 9439                hit_condition: None,
 9440            });
 9441
 9442            self.add_edit_breakpoint_block(
 9443                anchor,
 9444                &breakpoint,
 9445                BreakpointPromptEditAction::Log,
 9446                window,
 9447                cx,
 9448            );
 9449        }
 9450    }
 9451
 9452    fn breakpoints_at_cursors(
 9453        &self,
 9454        window: &mut Window,
 9455        cx: &mut Context<Self>,
 9456    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9457        let snapshot = self.snapshot(window, cx);
 9458        let cursors = self
 9459            .selections
 9460            .disjoint_anchors()
 9461            .into_iter()
 9462            .map(|selection| {
 9463                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9464
 9465                let breakpoint_position = self
 9466                    .breakpoint_at_row(cursor_position.row, window, cx)
 9467                    .map(|bp| bp.0)
 9468                    .unwrap_or_else(|| {
 9469                        snapshot
 9470                            .display_snapshot
 9471                            .buffer_snapshot
 9472                            .anchor_after(Point::new(cursor_position.row, 0))
 9473                    });
 9474
 9475                let breakpoint = self
 9476                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9477                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9478
 9479                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9480            })
 9481            // 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.
 9482            .collect::<HashMap<Anchor, _>>();
 9483
 9484        cursors.into_iter().collect()
 9485    }
 9486
 9487    pub fn enable_breakpoint(
 9488        &mut self,
 9489        _: &crate::actions::EnableBreakpoint,
 9490        window: &mut Window,
 9491        cx: &mut Context<Self>,
 9492    ) {
 9493        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9494            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9495                continue;
 9496            };
 9497            self.edit_breakpoint_at_anchor(
 9498                anchor,
 9499                breakpoint,
 9500                BreakpointEditAction::InvertState,
 9501                cx,
 9502            );
 9503        }
 9504    }
 9505
 9506    pub fn disable_breakpoint(
 9507        &mut self,
 9508        _: &crate::actions::DisableBreakpoint,
 9509        window: &mut Window,
 9510        cx: &mut Context<Self>,
 9511    ) {
 9512        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9513            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9514                continue;
 9515            };
 9516            self.edit_breakpoint_at_anchor(
 9517                anchor,
 9518                breakpoint,
 9519                BreakpointEditAction::InvertState,
 9520                cx,
 9521            );
 9522        }
 9523    }
 9524
 9525    pub fn toggle_breakpoint(
 9526        &mut self,
 9527        _: &crate::actions::ToggleBreakpoint,
 9528        window: &mut Window,
 9529        cx: &mut Context<Self>,
 9530    ) {
 9531        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9532            if let Some(breakpoint) = breakpoint {
 9533                self.edit_breakpoint_at_anchor(
 9534                    anchor,
 9535                    breakpoint,
 9536                    BreakpointEditAction::Toggle,
 9537                    cx,
 9538                );
 9539            } else {
 9540                self.edit_breakpoint_at_anchor(
 9541                    anchor,
 9542                    Breakpoint::new_standard(),
 9543                    BreakpointEditAction::Toggle,
 9544                    cx,
 9545                );
 9546            }
 9547        }
 9548    }
 9549
 9550    pub fn edit_breakpoint_at_anchor(
 9551        &mut self,
 9552        breakpoint_position: Anchor,
 9553        breakpoint: Breakpoint,
 9554        edit_action: BreakpointEditAction,
 9555        cx: &mut Context<Self>,
 9556    ) {
 9557        let Some(breakpoint_store) = &self.breakpoint_store else {
 9558            return;
 9559        };
 9560
 9561        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9562            if breakpoint_position == Anchor::min() {
 9563                self.buffer()
 9564                    .read(cx)
 9565                    .excerpt_buffer_ids()
 9566                    .into_iter()
 9567                    .next()
 9568            } else {
 9569                None
 9570            }
 9571        }) else {
 9572            return;
 9573        };
 9574
 9575        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9576            return;
 9577        };
 9578
 9579        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9580            breakpoint_store.toggle_breakpoint(
 9581                buffer,
 9582                (breakpoint_position.text_anchor, breakpoint),
 9583                edit_action,
 9584                cx,
 9585            );
 9586        });
 9587
 9588        cx.notify();
 9589    }
 9590
 9591    #[cfg(any(test, feature = "test-support"))]
 9592    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9593        self.breakpoint_store.clone()
 9594    }
 9595
 9596    pub fn prepare_restore_change(
 9597        &self,
 9598        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9599        hunk: &MultiBufferDiffHunk,
 9600        cx: &mut App,
 9601    ) -> Option<()> {
 9602        if hunk.is_created_file() {
 9603            return None;
 9604        }
 9605        let buffer = self.buffer.read(cx);
 9606        let diff = buffer.diff_for(hunk.buffer_id)?;
 9607        let buffer = buffer.buffer(hunk.buffer_id)?;
 9608        let buffer = buffer.read(cx);
 9609        let original_text = diff
 9610            .read(cx)
 9611            .base_text()
 9612            .as_rope()
 9613            .slice(hunk.diff_base_byte_range.clone());
 9614        let buffer_snapshot = buffer.snapshot();
 9615        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9616        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9617            probe
 9618                .0
 9619                .start
 9620                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9621                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9622        }) {
 9623            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9624            Some(())
 9625        } else {
 9626            None
 9627        }
 9628    }
 9629
 9630    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9631        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9632    }
 9633
 9634    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9635        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9636    }
 9637
 9638    fn manipulate_lines<Fn>(
 9639        &mut self,
 9640        window: &mut Window,
 9641        cx: &mut Context<Self>,
 9642        mut callback: Fn,
 9643    ) where
 9644        Fn: FnMut(&mut Vec<&str>),
 9645    {
 9646        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9647
 9648        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9649        let buffer = self.buffer.read(cx).snapshot(cx);
 9650
 9651        let mut edits = Vec::new();
 9652
 9653        let selections = self.selections.all::<Point>(cx);
 9654        let mut selections = selections.iter().peekable();
 9655        let mut contiguous_row_selections = Vec::new();
 9656        let mut new_selections = Vec::new();
 9657        let mut added_lines = 0;
 9658        let mut removed_lines = 0;
 9659
 9660        while let Some(selection) = selections.next() {
 9661            let (start_row, end_row) = consume_contiguous_rows(
 9662                &mut contiguous_row_selections,
 9663                selection,
 9664                &display_map,
 9665                &mut selections,
 9666            );
 9667
 9668            let start_point = Point::new(start_row.0, 0);
 9669            let end_point = Point::new(
 9670                end_row.previous_row().0,
 9671                buffer.line_len(end_row.previous_row()),
 9672            );
 9673            let text = buffer
 9674                .text_for_range(start_point..end_point)
 9675                .collect::<String>();
 9676
 9677            let mut lines = text.split('\n').collect_vec();
 9678
 9679            let lines_before = lines.len();
 9680            callback(&mut lines);
 9681            let lines_after = lines.len();
 9682
 9683            edits.push((start_point..end_point, lines.join("\n")));
 9684
 9685            // Selections must change based on added and removed line count
 9686            let start_row =
 9687                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9688            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9689            new_selections.push(Selection {
 9690                id: selection.id,
 9691                start: start_row,
 9692                end: end_row,
 9693                goal: SelectionGoal::None,
 9694                reversed: selection.reversed,
 9695            });
 9696
 9697            if lines_after > lines_before {
 9698                added_lines += lines_after - lines_before;
 9699            } else if lines_before > lines_after {
 9700                removed_lines += lines_before - lines_after;
 9701            }
 9702        }
 9703
 9704        self.transact(window, cx, |this, window, cx| {
 9705            let buffer = this.buffer.update(cx, |buffer, cx| {
 9706                buffer.edit(edits, None, cx);
 9707                buffer.snapshot(cx)
 9708            });
 9709
 9710            // Recalculate offsets on newly edited buffer
 9711            let new_selections = new_selections
 9712                .iter()
 9713                .map(|s| {
 9714                    let start_point = Point::new(s.start.0, 0);
 9715                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9716                    Selection {
 9717                        id: s.id,
 9718                        start: buffer.point_to_offset(start_point),
 9719                        end: buffer.point_to_offset(end_point),
 9720                        goal: s.goal,
 9721                        reversed: s.reversed,
 9722                    }
 9723                })
 9724                .collect();
 9725
 9726            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9727                s.select(new_selections);
 9728            });
 9729
 9730            this.request_autoscroll(Autoscroll::fit(), cx);
 9731        });
 9732    }
 9733
 9734    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9735        self.manipulate_text(window, cx, |text| {
 9736            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9737            if has_upper_case_characters {
 9738                text.to_lowercase()
 9739            } else {
 9740                text.to_uppercase()
 9741            }
 9742        })
 9743    }
 9744
 9745    pub fn convert_to_upper_case(
 9746        &mut self,
 9747        _: &ConvertToUpperCase,
 9748        window: &mut Window,
 9749        cx: &mut Context<Self>,
 9750    ) {
 9751        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9752    }
 9753
 9754    pub fn convert_to_lower_case(
 9755        &mut self,
 9756        _: &ConvertToLowerCase,
 9757        window: &mut Window,
 9758        cx: &mut Context<Self>,
 9759    ) {
 9760        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9761    }
 9762
 9763    pub fn convert_to_title_case(
 9764        &mut self,
 9765        _: &ConvertToTitleCase,
 9766        window: &mut Window,
 9767        cx: &mut Context<Self>,
 9768    ) {
 9769        self.manipulate_text(window, cx, |text| {
 9770            text.split('\n')
 9771                .map(|line| line.to_case(Case::Title))
 9772                .join("\n")
 9773        })
 9774    }
 9775
 9776    pub fn convert_to_snake_case(
 9777        &mut self,
 9778        _: &ConvertToSnakeCase,
 9779        window: &mut Window,
 9780        cx: &mut Context<Self>,
 9781    ) {
 9782        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9783    }
 9784
 9785    pub fn convert_to_kebab_case(
 9786        &mut self,
 9787        _: &ConvertToKebabCase,
 9788        window: &mut Window,
 9789        cx: &mut Context<Self>,
 9790    ) {
 9791        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9792    }
 9793
 9794    pub fn convert_to_upper_camel_case(
 9795        &mut self,
 9796        _: &ConvertToUpperCamelCase,
 9797        window: &mut Window,
 9798        cx: &mut Context<Self>,
 9799    ) {
 9800        self.manipulate_text(window, cx, |text| {
 9801            text.split('\n')
 9802                .map(|line| line.to_case(Case::UpperCamel))
 9803                .join("\n")
 9804        })
 9805    }
 9806
 9807    pub fn convert_to_lower_camel_case(
 9808        &mut self,
 9809        _: &ConvertToLowerCamelCase,
 9810        window: &mut Window,
 9811        cx: &mut Context<Self>,
 9812    ) {
 9813        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9814    }
 9815
 9816    pub fn convert_to_opposite_case(
 9817        &mut self,
 9818        _: &ConvertToOppositeCase,
 9819        window: &mut Window,
 9820        cx: &mut Context<Self>,
 9821    ) {
 9822        self.manipulate_text(window, cx, |text| {
 9823            text.chars()
 9824                .fold(String::with_capacity(text.len()), |mut t, c| {
 9825                    if c.is_uppercase() {
 9826                        t.extend(c.to_lowercase());
 9827                    } else {
 9828                        t.extend(c.to_uppercase());
 9829                    }
 9830                    t
 9831                })
 9832        })
 9833    }
 9834
 9835    pub fn convert_to_rot13(
 9836        &mut self,
 9837        _: &ConvertToRot13,
 9838        window: &mut Window,
 9839        cx: &mut Context<Self>,
 9840    ) {
 9841        self.manipulate_text(window, cx, |text| {
 9842            text.chars()
 9843                .map(|c| match c {
 9844                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9845                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9846                    _ => c,
 9847                })
 9848                .collect()
 9849        })
 9850    }
 9851
 9852    pub fn convert_to_rot47(
 9853        &mut self,
 9854        _: &ConvertToRot47,
 9855        window: &mut Window,
 9856        cx: &mut Context<Self>,
 9857    ) {
 9858        self.manipulate_text(window, cx, |text| {
 9859            text.chars()
 9860                .map(|c| {
 9861                    let code_point = c as u32;
 9862                    if code_point >= 33 && code_point <= 126 {
 9863                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9864                    }
 9865                    c
 9866                })
 9867                .collect()
 9868        })
 9869    }
 9870
 9871    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9872    where
 9873        Fn: FnMut(&str) -> String,
 9874    {
 9875        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9876        let buffer = self.buffer.read(cx).snapshot(cx);
 9877
 9878        let mut new_selections = Vec::new();
 9879        let mut edits = Vec::new();
 9880        let mut selection_adjustment = 0i32;
 9881
 9882        for selection in self.selections.all::<usize>(cx) {
 9883            let selection_is_empty = selection.is_empty();
 9884
 9885            let (start, end) = if selection_is_empty {
 9886                let word_range = movement::surrounding_word(
 9887                    &display_map,
 9888                    selection.start.to_display_point(&display_map),
 9889                );
 9890                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9891                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9892                (start, end)
 9893            } else {
 9894                (selection.start, selection.end)
 9895            };
 9896
 9897            let text = buffer.text_for_range(start..end).collect::<String>();
 9898            let old_length = text.len() as i32;
 9899            let text = callback(&text);
 9900
 9901            new_selections.push(Selection {
 9902                start: (start as i32 - selection_adjustment) as usize,
 9903                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9904                goal: SelectionGoal::None,
 9905                ..selection
 9906            });
 9907
 9908            selection_adjustment += old_length - text.len() as i32;
 9909
 9910            edits.push((start..end, text));
 9911        }
 9912
 9913        self.transact(window, cx, |this, window, cx| {
 9914            this.buffer.update(cx, |buffer, cx| {
 9915                buffer.edit(edits, None, cx);
 9916            });
 9917
 9918            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9919                s.select(new_selections);
 9920            });
 9921
 9922            this.request_autoscroll(Autoscroll::fit(), cx);
 9923        });
 9924    }
 9925
 9926    pub fn duplicate(
 9927        &mut self,
 9928        upwards: bool,
 9929        whole_lines: bool,
 9930        window: &mut Window,
 9931        cx: &mut Context<Self>,
 9932    ) {
 9933        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9934
 9935        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9936        let buffer = &display_map.buffer_snapshot;
 9937        let selections = self.selections.all::<Point>(cx);
 9938
 9939        let mut edits = Vec::new();
 9940        let mut selections_iter = selections.iter().peekable();
 9941        while let Some(selection) = selections_iter.next() {
 9942            let mut rows = selection.spanned_rows(false, &display_map);
 9943            // duplicate line-wise
 9944            if whole_lines || selection.start == selection.end {
 9945                // Avoid duplicating the same lines twice.
 9946                while let Some(next_selection) = selections_iter.peek() {
 9947                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9948                    if next_rows.start < rows.end {
 9949                        rows.end = next_rows.end;
 9950                        selections_iter.next().unwrap();
 9951                    } else {
 9952                        break;
 9953                    }
 9954                }
 9955
 9956                // Copy the text from the selected row region and splice it either at the start
 9957                // or end of the region.
 9958                let start = Point::new(rows.start.0, 0);
 9959                let end = Point::new(
 9960                    rows.end.previous_row().0,
 9961                    buffer.line_len(rows.end.previous_row()),
 9962                );
 9963                let text = buffer
 9964                    .text_for_range(start..end)
 9965                    .chain(Some("\n"))
 9966                    .collect::<String>();
 9967                let insert_location = if upwards {
 9968                    Point::new(rows.end.0, 0)
 9969                } else {
 9970                    start
 9971                };
 9972                edits.push((insert_location..insert_location, text));
 9973            } else {
 9974                // duplicate character-wise
 9975                let start = selection.start;
 9976                let end = selection.end;
 9977                let text = buffer.text_for_range(start..end).collect::<String>();
 9978                edits.push((selection.end..selection.end, text));
 9979            }
 9980        }
 9981
 9982        self.transact(window, cx, |this, _, cx| {
 9983            this.buffer.update(cx, |buffer, cx| {
 9984                buffer.edit(edits, None, cx);
 9985            });
 9986
 9987            this.request_autoscroll(Autoscroll::fit(), cx);
 9988        });
 9989    }
 9990
 9991    pub fn duplicate_line_up(
 9992        &mut self,
 9993        _: &DuplicateLineUp,
 9994        window: &mut Window,
 9995        cx: &mut Context<Self>,
 9996    ) {
 9997        self.duplicate(true, true, window, cx);
 9998    }
 9999
10000    pub fn duplicate_line_down(
10001        &mut self,
10002        _: &DuplicateLineDown,
10003        window: &mut Window,
10004        cx: &mut Context<Self>,
10005    ) {
10006        self.duplicate(false, true, window, cx);
10007    }
10008
10009    pub fn duplicate_selection(
10010        &mut self,
10011        _: &DuplicateSelection,
10012        window: &mut Window,
10013        cx: &mut Context<Self>,
10014    ) {
10015        self.duplicate(false, false, window, cx);
10016    }
10017
10018    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10019        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10020
10021        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10022        let buffer = self.buffer.read(cx).snapshot(cx);
10023
10024        let mut edits = Vec::new();
10025        let mut unfold_ranges = Vec::new();
10026        let mut refold_creases = Vec::new();
10027
10028        let selections = self.selections.all::<Point>(cx);
10029        let mut selections = selections.iter().peekable();
10030        let mut contiguous_row_selections = Vec::new();
10031        let mut new_selections = Vec::new();
10032
10033        while let Some(selection) = selections.next() {
10034            // Find all the selections that span a contiguous row range
10035            let (start_row, end_row) = consume_contiguous_rows(
10036                &mut contiguous_row_selections,
10037                selection,
10038                &display_map,
10039                &mut selections,
10040            );
10041
10042            // Move the text spanned by the row range to be before the line preceding the row range
10043            if start_row.0 > 0 {
10044                let range_to_move = Point::new(
10045                    start_row.previous_row().0,
10046                    buffer.line_len(start_row.previous_row()),
10047                )
10048                    ..Point::new(
10049                        end_row.previous_row().0,
10050                        buffer.line_len(end_row.previous_row()),
10051                    );
10052                let insertion_point = display_map
10053                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10054                    .0;
10055
10056                // Don't move lines across excerpts
10057                if buffer
10058                    .excerpt_containing(insertion_point..range_to_move.end)
10059                    .is_some()
10060                {
10061                    let text = buffer
10062                        .text_for_range(range_to_move.clone())
10063                        .flat_map(|s| s.chars())
10064                        .skip(1)
10065                        .chain(['\n'])
10066                        .collect::<String>();
10067
10068                    edits.push((
10069                        buffer.anchor_after(range_to_move.start)
10070                            ..buffer.anchor_before(range_to_move.end),
10071                        String::new(),
10072                    ));
10073                    let insertion_anchor = buffer.anchor_after(insertion_point);
10074                    edits.push((insertion_anchor..insertion_anchor, text));
10075
10076                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10077
10078                    // Move selections up
10079                    new_selections.extend(contiguous_row_selections.drain(..).map(
10080                        |mut selection| {
10081                            selection.start.row -= row_delta;
10082                            selection.end.row -= row_delta;
10083                            selection
10084                        },
10085                    ));
10086
10087                    // Move folds up
10088                    unfold_ranges.push(range_to_move.clone());
10089                    for fold in display_map.folds_in_range(
10090                        buffer.anchor_before(range_to_move.start)
10091                            ..buffer.anchor_after(range_to_move.end),
10092                    ) {
10093                        let mut start = fold.range.start.to_point(&buffer);
10094                        let mut end = fold.range.end.to_point(&buffer);
10095                        start.row -= row_delta;
10096                        end.row -= row_delta;
10097                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10098                    }
10099                }
10100            }
10101
10102            // If we didn't move line(s), preserve the existing selections
10103            new_selections.append(&mut contiguous_row_selections);
10104        }
10105
10106        self.transact(window, cx, |this, window, cx| {
10107            this.unfold_ranges(&unfold_ranges, true, true, cx);
10108            this.buffer.update(cx, |buffer, cx| {
10109                for (range, text) in edits {
10110                    buffer.edit([(range, text)], None, cx);
10111                }
10112            });
10113            this.fold_creases(refold_creases, true, window, cx);
10114            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10115                s.select(new_selections);
10116            })
10117        });
10118    }
10119
10120    pub fn move_line_down(
10121        &mut self,
10122        _: &MoveLineDown,
10123        window: &mut Window,
10124        cx: &mut Context<Self>,
10125    ) {
10126        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10127
10128        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10129        let buffer = self.buffer.read(cx).snapshot(cx);
10130
10131        let mut edits = Vec::new();
10132        let mut unfold_ranges = Vec::new();
10133        let mut refold_creases = Vec::new();
10134
10135        let selections = self.selections.all::<Point>(cx);
10136        let mut selections = selections.iter().peekable();
10137        let mut contiguous_row_selections = Vec::new();
10138        let mut new_selections = Vec::new();
10139
10140        while let Some(selection) = selections.next() {
10141            // Find all the selections that span a contiguous row range
10142            let (start_row, end_row) = consume_contiguous_rows(
10143                &mut contiguous_row_selections,
10144                selection,
10145                &display_map,
10146                &mut selections,
10147            );
10148
10149            // Move the text spanned by the row range to be after the last line of the row range
10150            if end_row.0 <= buffer.max_point().row {
10151                let range_to_move =
10152                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10153                let insertion_point = display_map
10154                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10155                    .0;
10156
10157                // Don't move lines across excerpt boundaries
10158                if buffer
10159                    .excerpt_containing(range_to_move.start..insertion_point)
10160                    .is_some()
10161                {
10162                    let mut text = String::from("\n");
10163                    text.extend(buffer.text_for_range(range_to_move.clone()));
10164                    text.pop(); // Drop trailing newline
10165                    edits.push((
10166                        buffer.anchor_after(range_to_move.start)
10167                            ..buffer.anchor_before(range_to_move.end),
10168                        String::new(),
10169                    ));
10170                    let insertion_anchor = buffer.anchor_after(insertion_point);
10171                    edits.push((insertion_anchor..insertion_anchor, text));
10172
10173                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10174
10175                    // Move selections down
10176                    new_selections.extend(contiguous_row_selections.drain(..).map(
10177                        |mut selection| {
10178                            selection.start.row += row_delta;
10179                            selection.end.row += row_delta;
10180                            selection
10181                        },
10182                    ));
10183
10184                    // Move folds down
10185                    unfold_ranges.push(range_to_move.clone());
10186                    for fold in display_map.folds_in_range(
10187                        buffer.anchor_before(range_to_move.start)
10188                            ..buffer.anchor_after(range_to_move.end),
10189                    ) {
10190                        let mut start = fold.range.start.to_point(&buffer);
10191                        let mut end = fold.range.end.to_point(&buffer);
10192                        start.row += row_delta;
10193                        end.row += row_delta;
10194                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10195                    }
10196                }
10197            }
10198
10199            // If we didn't move line(s), preserve the existing selections
10200            new_selections.append(&mut contiguous_row_selections);
10201        }
10202
10203        self.transact(window, cx, |this, window, cx| {
10204            this.unfold_ranges(&unfold_ranges, true, true, cx);
10205            this.buffer.update(cx, |buffer, cx| {
10206                for (range, text) in edits {
10207                    buffer.edit([(range, text)], None, cx);
10208                }
10209            });
10210            this.fold_creases(refold_creases, true, window, cx);
10211            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10212                s.select(new_selections)
10213            });
10214        });
10215    }
10216
10217    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10218        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10219        let text_layout_details = &self.text_layout_details(window);
10220        self.transact(window, cx, |this, window, cx| {
10221            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10222                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10223                s.move_with(|display_map, selection| {
10224                    if !selection.is_empty() {
10225                        return;
10226                    }
10227
10228                    let mut head = selection.head();
10229                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10230                    if head.column() == display_map.line_len(head.row()) {
10231                        transpose_offset = display_map
10232                            .buffer_snapshot
10233                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10234                    }
10235
10236                    if transpose_offset == 0 {
10237                        return;
10238                    }
10239
10240                    *head.column_mut() += 1;
10241                    head = display_map.clip_point(head, Bias::Right);
10242                    let goal = SelectionGoal::HorizontalPosition(
10243                        display_map
10244                            .x_for_display_point(head, text_layout_details)
10245                            .into(),
10246                    );
10247                    selection.collapse_to(head, goal);
10248
10249                    let transpose_start = display_map
10250                        .buffer_snapshot
10251                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10252                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10253                        let transpose_end = display_map
10254                            .buffer_snapshot
10255                            .clip_offset(transpose_offset + 1, Bias::Right);
10256                        if let Some(ch) =
10257                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10258                        {
10259                            edits.push((transpose_start..transpose_offset, String::new()));
10260                            edits.push((transpose_end..transpose_end, ch.to_string()));
10261                        }
10262                    }
10263                });
10264                edits
10265            });
10266            this.buffer
10267                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10268            let selections = this.selections.all::<usize>(cx);
10269            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10270                s.select(selections);
10271            });
10272        });
10273    }
10274
10275    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10276        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10277        self.rewrap_impl(RewrapOptions::default(), cx)
10278    }
10279
10280    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10281        let buffer = self.buffer.read(cx).snapshot(cx);
10282        let selections = self.selections.all::<Point>(cx);
10283        let mut selections = selections.iter().peekable();
10284
10285        let mut edits = Vec::new();
10286        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10287
10288        while let Some(selection) = selections.next() {
10289            let mut start_row = selection.start.row;
10290            let mut end_row = selection.end.row;
10291
10292            // Skip selections that overlap with a range that has already been rewrapped.
10293            let selection_range = start_row..end_row;
10294            if rewrapped_row_ranges
10295                .iter()
10296                .any(|range| range.overlaps(&selection_range))
10297            {
10298                continue;
10299            }
10300
10301            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10302
10303            // Since not all lines in the selection may be at the same indent
10304            // level, choose the indent size that is the most common between all
10305            // of the lines.
10306            //
10307            // If there is a tie, we use the deepest indent.
10308            let (indent_size, indent_end) = {
10309                let mut indent_size_occurrences = HashMap::default();
10310                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10311
10312                for row in start_row..=end_row {
10313                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10314                    rows_by_indent_size.entry(indent).or_default().push(row);
10315                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10316                }
10317
10318                let indent_size = indent_size_occurrences
10319                    .into_iter()
10320                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10321                    .map(|(indent, _)| indent)
10322                    .unwrap_or_default();
10323                let row = rows_by_indent_size[&indent_size][0];
10324                let indent_end = Point::new(row, indent_size.len);
10325
10326                (indent_size, indent_end)
10327            };
10328
10329            let mut line_prefix = indent_size.chars().collect::<String>();
10330
10331            let mut inside_comment = false;
10332            if let Some(comment_prefix) =
10333                buffer
10334                    .language_scope_at(selection.head())
10335                    .and_then(|language| {
10336                        language
10337                            .line_comment_prefixes()
10338                            .iter()
10339                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10340                            .cloned()
10341                    })
10342            {
10343                line_prefix.push_str(&comment_prefix);
10344                inside_comment = true;
10345            }
10346
10347            let language_settings = buffer.language_settings_at(selection.head(), cx);
10348            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10349                RewrapBehavior::InComments => inside_comment,
10350                RewrapBehavior::InSelections => !selection.is_empty(),
10351                RewrapBehavior::Anywhere => true,
10352            };
10353
10354            let should_rewrap = options.override_language_settings
10355                || allow_rewrap_based_on_language
10356                || self.hard_wrap.is_some();
10357            if !should_rewrap {
10358                continue;
10359            }
10360
10361            if selection.is_empty() {
10362                'expand_upwards: while start_row > 0 {
10363                    let prev_row = start_row - 1;
10364                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10365                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10366                    {
10367                        start_row = prev_row;
10368                    } else {
10369                        break 'expand_upwards;
10370                    }
10371                }
10372
10373                'expand_downwards: while end_row < buffer.max_point().row {
10374                    let next_row = end_row + 1;
10375                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10376                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10377                    {
10378                        end_row = next_row;
10379                    } else {
10380                        break 'expand_downwards;
10381                    }
10382                }
10383            }
10384
10385            let start = Point::new(start_row, 0);
10386            let start_offset = start.to_offset(&buffer);
10387            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10388            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10389            let Some(lines_without_prefixes) = selection_text
10390                .lines()
10391                .map(|line| {
10392                    line.strip_prefix(&line_prefix)
10393                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10394                        .ok_or_else(|| {
10395                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10396                        })
10397                })
10398                .collect::<Result<Vec<_>, _>>()
10399                .log_err()
10400            else {
10401                continue;
10402            };
10403
10404            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10405                buffer
10406                    .language_settings_at(Point::new(start_row, 0), cx)
10407                    .preferred_line_length as usize
10408            });
10409            let wrapped_text = wrap_with_prefix(
10410                line_prefix,
10411                lines_without_prefixes.join("\n"),
10412                wrap_column,
10413                tab_size,
10414                options.preserve_existing_whitespace,
10415            );
10416
10417            // TODO: should always use char-based diff while still supporting cursor behavior that
10418            // matches vim.
10419            let mut diff_options = DiffOptions::default();
10420            if options.override_language_settings {
10421                diff_options.max_word_diff_len = 0;
10422                diff_options.max_word_diff_line_count = 0;
10423            } else {
10424                diff_options.max_word_diff_len = usize::MAX;
10425                diff_options.max_word_diff_line_count = usize::MAX;
10426            }
10427
10428            for (old_range, new_text) in
10429                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10430            {
10431                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10432                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10433                edits.push((edit_start..edit_end, new_text));
10434            }
10435
10436            rewrapped_row_ranges.push(start_row..=end_row);
10437        }
10438
10439        self.buffer
10440            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10441    }
10442
10443    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10444        let mut text = String::new();
10445        let buffer = self.buffer.read(cx).snapshot(cx);
10446        let mut selections = self.selections.all::<Point>(cx);
10447        let mut clipboard_selections = Vec::with_capacity(selections.len());
10448        {
10449            let max_point = buffer.max_point();
10450            let mut is_first = true;
10451            for selection in &mut selections {
10452                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10453                if is_entire_line {
10454                    selection.start = Point::new(selection.start.row, 0);
10455                    if !selection.is_empty() && selection.end.column == 0 {
10456                        selection.end = cmp::min(max_point, selection.end);
10457                    } else {
10458                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10459                    }
10460                    selection.goal = SelectionGoal::None;
10461                }
10462                if is_first {
10463                    is_first = false;
10464                } else {
10465                    text += "\n";
10466                }
10467                let mut len = 0;
10468                for chunk in buffer.text_for_range(selection.start..selection.end) {
10469                    text.push_str(chunk);
10470                    len += chunk.len();
10471                }
10472                clipboard_selections.push(ClipboardSelection {
10473                    len,
10474                    is_entire_line,
10475                    first_line_indent: buffer
10476                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10477                        .len,
10478                });
10479            }
10480        }
10481
10482        self.transact(window, cx, |this, window, cx| {
10483            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10484                s.select(selections);
10485            });
10486            this.insert("", window, cx);
10487        });
10488        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10489    }
10490
10491    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10492        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10493        let item = self.cut_common(window, cx);
10494        cx.write_to_clipboard(item);
10495    }
10496
10497    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10498        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10499        self.change_selections(None, window, cx, |s| {
10500            s.move_with(|snapshot, sel| {
10501                if sel.is_empty() {
10502                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10503                }
10504            });
10505        });
10506        let item = self.cut_common(window, cx);
10507        cx.set_global(KillRing(item))
10508    }
10509
10510    pub fn kill_ring_yank(
10511        &mut self,
10512        _: &KillRingYank,
10513        window: &mut Window,
10514        cx: &mut Context<Self>,
10515    ) {
10516        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10517        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10518            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10519                (kill_ring.text().to_string(), kill_ring.metadata_json())
10520            } else {
10521                return;
10522            }
10523        } else {
10524            return;
10525        };
10526        self.do_paste(&text, metadata, false, window, cx);
10527    }
10528
10529    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10530        self.do_copy(true, cx);
10531    }
10532
10533    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10534        self.do_copy(false, cx);
10535    }
10536
10537    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10538        let selections = self.selections.all::<Point>(cx);
10539        let buffer = self.buffer.read(cx).read(cx);
10540        let mut text = String::new();
10541
10542        let mut clipboard_selections = Vec::with_capacity(selections.len());
10543        {
10544            let max_point = buffer.max_point();
10545            let mut is_first = true;
10546            for selection in &selections {
10547                let mut start = selection.start;
10548                let mut end = selection.end;
10549                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10550                if is_entire_line {
10551                    start = Point::new(start.row, 0);
10552                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10553                }
10554
10555                let mut trimmed_selections = Vec::new();
10556                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10557                    let row = MultiBufferRow(start.row);
10558                    let first_indent = buffer.indent_size_for_line(row);
10559                    if first_indent.len == 0 || start.column > first_indent.len {
10560                        trimmed_selections.push(start..end);
10561                    } else {
10562                        trimmed_selections.push(
10563                            Point::new(row.0, first_indent.len)
10564                                ..Point::new(row.0, buffer.line_len(row)),
10565                        );
10566                        for row in start.row + 1..=end.row {
10567                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10568                            if row == end.row {
10569                                line_len = end.column;
10570                            }
10571                            if line_len == 0 {
10572                                trimmed_selections
10573                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10574                                continue;
10575                            }
10576                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10577                            if row_indent_size.len >= first_indent.len {
10578                                trimmed_selections.push(
10579                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10580                                );
10581                            } else {
10582                                trimmed_selections.clear();
10583                                trimmed_selections.push(start..end);
10584                                break;
10585                            }
10586                        }
10587                    }
10588                } else {
10589                    trimmed_selections.push(start..end);
10590                }
10591
10592                for trimmed_range in trimmed_selections {
10593                    if is_first {
10594                        is_first = false;
10595                    } else {
10596                        text += "\n";
10597                    }
10598                    let mut len = 0;
10599                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10600                        text.push_str(chunk);
10601                        len += chunk.len();
10602                    }
10603                    clipboard_selections.push(ClipboardSelection {
10604                        len,
10605                        is_entire_line,
10606                        first_line_indent: buffer
10607                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10608                            .len,
10609                    });
10610                }
10611            }
10612        }
10613
10614        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10615            text,
10616            clipboard_selections,
10617        ));
10618    }
10619
10620    pub fn do_paste(
10621        &mut self,
10622        text: &String,
10623        clipboard_selections: Option<Vec<ClipboardSelection>>,
10624        handle_entire_lines: bool,
10625        window: &mut Window,
10626        cx: &mut Context<Self>,
10627    ) {
10628        if self.read_only(cx) {
10629            return;
10630        }
10631
10632        let clipboard_text = Cow::Borrowed(text);
10633
10634        self.transact(window, cx, |this, window, cx| {
10635            if let Some(mut clipboard_selections) = clipboard_selections {
10636                let old_selections = this.selections.all::<usize>(cx);
10637                let all_selections_were_entire_line =
10638                    clipboard_selections.iter().all(|s| s.is_entire_line);
10639                let first_selection_indent_column =
10640                    clipboard_selections.first().map(|s| s.first_line_indent);
10641                if clipboard_selections.len() != old_selections.len() {
10642                    clipboard_selections.drain(..);
10643                }
10644                let cursor_offset = this.selections.last::<usize>(cx).head();
10645                let mut auto_indent_on_paste = true;
10646
10647                this.buffer.update(cx, |buffer, cx| {
10648                    let snapshot = buffer.read(cx);
10649                    auto_indent_on_paste = snapshot
10650                        .language_settings_at(cursor_offset, cx)
10651                        .auto_indent_on_paste;
10652
10653                    let mut start_offset = 0;
10654                    let mut edits = Vec::new();
10655                    let mut original_indent_columns = Vec::new();
10656                    for (ix, selection) in old_selections.iter().enumerate() {
10657                        let to_insert;
10658                        let entire_line;
10659                        let original_indent_column;
10660                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10661                            let end_offset = start_offset + clipboard_selection.len;
10662                            to_insert = &clipboard_text[start_offset..end_offset];
10663                            entire_line = clipboard_selection.is_entire_line;
10664                            start_offset = end_offset + 1;
10665                            original_indent_column = Some(clipboard_selection.first_line_indent);
10666                        } else {
10667                            to_insert = clipboard_text.as_str();
10668                            entire_line = all_selections_were_entire_line;
10669                            original_indent_column = first_selection_indent_column
10670                        }
10671
10672                        // If the corresponding selection was empty when this slice of the
10673                        // clipboard text was written, then the entire line containing the
10674                        // selection was copied. If this selection is also currently empty,
10675                        // then paste the line before the current line of the buffer.
10676                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10677                            let column = selection.start.to_point(&snapshot).column as usize;
10678                            let line_start = selection.start - column;
10679                            line_start..line_start
10680                        } else {
10681                            selection.range()
10682                        };
10683
10684                        edits.push((range, to_insert));
10685                        original_indent_columns.push(original_indent_column);
10686                    }
10687                    drop(snapshot);
10688
10689                    buffer.edit(
10690                        edits,
10691                        if auto_indent_on_paste {
10692                            Some(AutoindentMode::Block {
10693                                original_indent_columns,
10694                            })
10695                        } else {
10696                            None
10697                        },
10698                        cx,
10699                    );
10700                });
10701
10702                let selections = this.selections.all::<usize>(cx);
10703                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704                    s.select(selections)
10705                });
10706            } else {
10707                this.insert(&clipboard_text, window, cx);
10708            }
10709        });
10710    }
10711
10712    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10713        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10714        if let Some(item) = cx.read_from_clipboard() {
10715            let entries = item.entries();
10716
10717            match entries.first() {
10718                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10719                // of all the pasted entries.
10720                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10721                    .do_paste(
10722                        clipboard_string.text(),
10723                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10724                        true,
10725                        window,
10726                        cx,
10727                    ),
10728                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10729            }
10730        }
10731    }
10732
10733    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10734        if self.read_only(cx) {
10735            return;
10736        }
10737
10738        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10739
10740        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10741            if let Some((selections, _)) =
10742                self.selection_history.transaction(transaction_id).cloned()
10743            {
10744                self.change_selections(None, window, cx, |s| {
10745                    s.select_anchors(selections.to_vec());
10746                });
10747            } else {
10748                log::error!(
10749                    "No entry in selection_history found for undo. \
10750                     This may correspond to a bug where undo does not update the selection. \
10751                     If this is occurring, please add details to \
10752                     https://github.com/zed-industries/zed/issues/22692"
10753                );
10754            }
10755            self.request_autoscroll(Autoscroll::fit(), cx);
10756            self.unmark_text(window, cx);
10757            self.refresh_inline_completion(true, false, window, cx);
10758            cx.emit(EditorEvent::Edited { transaction_id });
10759            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10760        }
10761    }
10762
10763    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10764        if self.read_only(cx) {
10765            return;
10766        }
10767
10768        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10769
10770        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10771            if let Some((_, Some(selections))) =
10772                self.selection_history.transaction(transaction_id).cloned()
10773            {
10774                self.change_selections(None, window, cx, |s| {
10775                    s.select_anchors(selections.to_vec());
10776                });
10777            } else {
10778                log::error!(
10779                    "No entry in selection_history found for redo. \
10780                     This may correspond to a bug where undo does not update the selection. \
10781                     If this is occurring, please add details to \
10782                     https://github.com/zed-industries/zed/issues/22692"
10783                );
10784            }
10785            self.request_autoscroll(Autoscroll::fit(), cx);
10786            self.unmark_text(window, cx);
10787            self.refresh_inline_completion(true, false, window, cx);
10788            cx.emit(EditorEvent::Edited { transaction_id });
10789        }
10790    }
10791
10792    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10793        self.buffer
10794            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10795    }
10796
10797    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10798        self.buffer
10799            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10800    }
10801
10802    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10803        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10804        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10805            s.move_with(|map, selection| {
10806                let cursor = if selection.is_empty() {
10807                    movement::left(map, selection.start)
10808                } else {
10809                    selection.start
10810                };
10811                selection.collapse_to(cursor, SelectionGoal::None);
10812            });
10813        })
10814    }
10815
10816    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10817        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10818        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10819            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10820        })
10821    }
10822
10823    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10824        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10825        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10826            s.move_with(|map, selection| {
10827                let cursor = if selection.is_empty() {
10828                    movement::right(map, selection.end)
10829                } else {
10830                    selection.end
10831                };
10832                selection.collapse_to(cursor, SelectionGoal::None)
10833            });
10834        })
10835    }
10836
10837    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10838        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10839        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10841        })
10842    }
10843
10844    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10845        if self.take_rename(true, window, cx).is_some() {
10846            return;
10847        }
10848
10849        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10850            cx.propagate();
10851            return;
10852        }
10853
10854        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10855
10856        let text_layout_details = &self.text_layout_details(window);
10857        let selection_count = self.selections.count();
10858        let first_selection = self.selections.first_anchor();
10859
10860        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10861            s.move_with(|map, selection| {
10862                if !selection.is_empty() {
10863                    selection.goal = SelectionGoal::None;
10864                }
10865                let (cursor, goal) = movement::up(
10866                    map,
10867                    selection.start,
10868                    selection.goal,
10869                    false,
10870                    text_layout_details,
10871                );
10872                selection.collapse_to(cursor, goal);
10873            });
10874        });
10875
10876        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10877        {
10878            cx.propagate();
10879        }
10880    }
10881
10882    pub fn move_up_by_lines(
10883        &mut self,
10884        action: &MoveUpByLines,
10885        window: &mut Window,
10886        cx: &mut Context<Self>,
10887    ) {
10888        if self.take_rename(true, window, cx).is_some() {
10889            return;
10890        }
10891
10892        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10893            cx.propagate();
10894            return;
10895        }
10896
10897        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10898
10899        let text_layout_details = &self.text_layout_details(window);
10900
10901        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10902            s.move_with(|map, selection| {
10903                if !selection.is_empty() {
10904                    selection.goal = SelectionGoal::None;
10905                }
10906                let (cursor, goal) = movement::up_by_rows(
10907                    map,
10908                    selection.start,
10909                    action.lines,
10910                    selection.goal,
10911                    false,
10912                    text_layout_details,
10913                );
10914                selection.collapse_to(cursor, goal);
10915            });
10916        })
10917    }
10918
10919    pub fn move_down_by_lines(
10920        &mut self,
10921        action: &MoveDownByLines,
10922        window: &mut Window,
10923        cx: &mut Context<Self>,
10924    ) {
10925        if self.take_rename(true, window, cx).is_some() {
10926            return;
10927        }
10928
10929        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10930            cx.propagate();
10931            return;
10932        }
10933
10934        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10935
10936        let text_layout_details = &self.text_layout_details(window);
10937
10938        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10939            s.move_with(|map, selection| {
10940                if !selection.is_empty() {
10941                    selection.goal = SelectionGoal::None;
10942                }
10943                let (cursor, goal) = movement::down_by_rows(
10944                    map,
10945                    selection.start,
10946                    action.lines,
10947                    selection.goal,
10948                    false,
10949                    text_layout_details,
10950                );
10951                selection.collapse_to(cursor, goal);
10952            });
10953        })
10954    }
10955
10956    pub fn select_down_by_lines(
10957        &mut self,
10958        action: &SelectDownByLines,
10959        window: &mut Window,
10960        cx: &mut Context<Self>,
10961    ) {
10962        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10963        let text_layout_details = &self.text_layout_details(window);
10964        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10965            s.move_heads_with(|map, head, goal| {
10966                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10967            })
10968        })
10969    }
10970
10971    pub fn select_up_by_lines(
10972        &mut self,
10973        action: &SelectUpByLines,
10974        window: &mut Window,
10975        cx: &mut Context<Self>,
10976    ) {
10977        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10978        let text_layout_details = &self.text_layout_details(window);
10979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10980            s.move_heads_with(|map, head, goal| {
10981                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10982            })
10983        })
10984    }
10985
10986    pub fn select_page_up(
10987        &mut self,
10988        _: &SelectPageUp,
10989        window: &mut Window,
10990        cx: &mut Context<Self>,
10991    ) {
10992        let Some(row_count) = self.visible_row_count() else {
10993            return;
10994        };
10995
10996        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10997
10998        let text_layout_details = &self.text_layout_details(window);
10999
11000        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11001            s.move_heads_with(|map, head, goal| {
11002                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
11003            })
11004        })
11005    }
11006
11007    pub fn move_page_up(
11008        &mut self,
11009        action: &MovePageUp,
11010        window: &mut Window,
11011        cx: &mut Context<Self>,
11012    ) {
11013        if self.take_rename(true, window, cx).is_some() {
11014            return;
11015        }
11016
11017        if self
11018            .context_menu
11019            .borrow_mut()
11020            .as_mut()
11021            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11022            .unwrap_or(false)
11023        {
11024            return;
11025        }
11026
11027        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11028            cx.propagate();
11029            return;
11030        }
11031
11032        let Some(row_count) = self.visible_row_count() else {
11033            return;
11034        };
11035
11036        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11037
11038        let autoscroll = if action.center_cursor {
11039            Autoscroll::center()
11040        } else {
11041            Autoscroll::fit()
11042        };
11043
11044        let text_layout_details = &self.text_layout_details(window);
11045
11046        self.change_selections(Some(autoscroll), window, cx, |s| {
11047            s.move_with(|map, selection| {
11048                if !selection.is_empty() {
11049                    selection.goal = SelectionGoal::None;
11050                }
11051                let (cursor, goal) = movement::up_by_rows(
11052                    map,
11053                    selection.end,
11054                    row_count,
11055                    selection.goal,
11056                    false,
11057                    text_layout_details,
11058                );
11059                selection.collapse_to(cursor, goal);
11060            });
11061        });
11062    }
11063
11064    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11065        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11066        let text_layout_details = &self.text_layout_details(window);
11067        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11068            s.move_heads_with(|map, head, goal| {
11069                movement::up(map, head, goal, false, text_layout_details)
11070            })
11071        })
11072    }
11073
11074    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11075        self.take_rename(true, window, cx);
11076
11077        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11078            cx.propagate();
11079            return;
11080        }
11081
11082        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11083
11084        let text_layout_details = &self.text_layout_details(window);
11085        let selection_count = self.selections.count();
11086        let first_selection = self.selections.first_anchor();
11087
11088        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11089            s.move_with(|map, selection| {
11090                if !selection.is_empty() {
11091                    selection.goal = SelectionGoal::None;
11092                }
11093                let (cursor, goal) = movement::down(
11094                    map,
11095                    selection.end,
11096                    selection.goal,
11097                    false,
11098                    text_layout_details,
11099                );
11100                selection.collapse_to(cursor, goal);
11101            });
11102        });
11103
11104        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11105        {
11106            cx.propagate();
11107        }
11108    }
11109
11110    pub fn select_page_down(
11111        &mut self,
11112        _: &SelectPageDown,
11113        window: &mut Window,
11114        cx: &mut Context<Self>,
11115    ) {
11116        let Some(row_count) = self.visible_row_count() else {
11117            return;
11118        };
11119
11120        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11121
11122        let text_layout_details = &self.text_layout_details(window);
11123
11124        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11125            s.move_heads_with(|map, head, goal| {
11126                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11127            })
11128        })
11129    }
11130
11131    pub fn move_page_down(
11132        &mut self,
11133        action: &MovePageDown,
11134        window: &mut Window,
11135        cx: &mut Context<Self>,
11136    ) {
11137        if self.take_rename(true, window, cx).is_some() {
11138            return;
11139        }
11140
11141        if self
11142            .context_menu
11143            .borrow_mut()
11144            .as_mut()
11145            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11146            .unwrap_or(false)
11147        {
11148            return;
11149        }
11150
11151        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11152            cx.propagate();
11153            return;
11154        }
11155
11156        let Some(row_count) = self.visible_row_count() else {
11157            return;
11158        };
11159
11160        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11161
11162        let autoscroll = if action.center_cursor {
11163            Autoscroll::center()
11164        } else {
11165            Autoscroll::fit()
11166        };
11167
11168        let text_layout_details = &self.text_layout_details(window);
11169        self.change_selections(Some(autoscroll), window, cx, |s| {
11170            s.move_with(|map, selection| {
11171                if !selection.is_empty() {
11172                    selection.goal = SelectionGoal::None;
11173                }
11174                let (cursor, goal) = movement::down_by_rows(
11175                    map,
11176                    selection.end,
11177                    row_count,
11178                    selection.goal,
11179                    false,
11180                    text_layout_details,
11181                );
11182                selection.collapse_to(cursor, goal);
11183            });
11184        });
11185    }
11186
11187    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11188        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11189        let text_layout_details = &self.text_layout_details(window);
11190        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11191            s.move_heads_with(|map, head, goal| {
11192                movement::down(map, head, goal, false, text_layout_details)
11193            })
11194        });
11195    }
11196
11197    pub fn context_menu_first(
11198        &mut self,
11199        _: &ContextMenuFirst,
11200        _window: &mut Window,
11201        cx: &mut Context<Self>,
11202    ) {
11203        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11204            context_menu.select_first(self.completion_provider.as_deref(), cx);
11205        }
11206    }
11207
11208    pub fn context_menu_prev(
11209        &mut self,
11210        _: &ContextMenuPrevious,
11211        _window: &mut Window,
11212        cx: &mut Context<Self>,
11213    ) {
11214        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11215            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11216        }
11217    }
11218
11219    pub fn context_menu_next(
11220        &mut self,
11221        _: &ContextMenuNext,
11222        _window: &mut Window,
11223        cx: &mut Context<Self>,
11224    ) {
11225        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11226            context_menu.select_next(self.completion_provider.as_deref(), cx);
11227        }
11228    }
11229
11230    pub fn context_menu_last(
11231        &mut self,
11232        _: &ContextMenuLast,
11233        _window: &mut Window,
11234        cx: &mut Context<Self>,
11235    ) {
11236        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11237            context_menu.select_last(self.completion_provider.as_deref(), cx);
11238        }
11239    }
11240
11241    pub fn move_to_previous_word_start(
11242        &mut self,
11243        _: &MoveToPreviousWordStart,
11244        window: &mut Window,
11245        cx: &mut Context<Self>,
11246    ) {
11247        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11249            s.move_cursors_with(|map, head, _| {
11250                (
11251                    movement::previous_word_start(map, head),
11252                    SelectionGoal::None,
11253                )
11254            });
11255        })
11256    }
11257
11258    pub fn move_to_previous_subword_start(
11259        &mut self,
11260        _: &MoveToPreviousSubwordStart,
11261        window: &mut Window,
11262        cx: &mut Context<Self>,
11263    ) {
11264        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11265        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11266            s.move_cursors_with(|map, head, _| {
11267                (
11268                    movement::previous_subword_start(map, head),
11269                    SelectionGoal::None,
11270                )
11271            });
11272        })
11273    }
11274
11275    pub fn select_to_previous_word_start(
11276        &mut self,
11277        _: &SelectToPreviousWordStart,
11278        window: &mut Window,
11279        cx: &mut Context<Self>,
11280    ) {
11281        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11282        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11283            s.move_heads_with(|map, head, _| {
11284                (
11285                    movement::previous_word_start(map, head),
11286                    SelectionGoal::None,
11287                )
11288            });
11289        })
11290    }
11291
11292    pub fn select_to_previous_subword_start(
11293        &mut self,
11294        _: &SelectToPreviousSubwordStart,
11295        window: &mut Window,
11296        cx: &mut Context<Self>,
11297    ) {
11298        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11299        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11300            s.move_heads_with(|map, head, _| {
11301                (
11302                    movement::previous_subword_start(map, head),
11303                    SelectionGoal::None,
11304                )
11305            });
11306        })
11307    }
11308
11309    pub fn delete_to_previous_word_start(
11310        &mut self,
11311        action: &DeleteToPreviousWordStart,
11312        window: &mut Window,
11313        cx: &mut Context<Self>,
11314    ) {
11315        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11316        self.transact(window, cx, |this, window, cx| {
11317            this.select_autoclose_pair(window, cx);
11318            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11319                s.move_with(|map, selection| {
11320                    if selection.is_empty() {
11321                        let cursor = if action.ignore_newlines {
11322                            movement::previous_word_start(map, selection.head())
11323                        } else {
11324                            movement::previous_word_start_or_newline(map, selection.head())
11325                        };
11326                        selection.set_head(cursor, SelectionGoal::None);
11327                    }
11328                });
11329            });
11330            this.insert("", window, cx);
11331        });
11332    }
11333
11334    pub fn delete_to_previous_subword_start(
11335        &mut self,
11336        _: &DeleteToPreviousSubwordStart,
11337        window: &mut Window,
11338        cx: &mut Context<Self>,
11339    ) {
11340        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11341        self.transact(window, cx, |this, window, cx| {
11342            this.select_autoclose_pair(window, cx);
11343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11344                s.move_with(|map, selection| {
11345                    if selection.is_empty() {
11346                        let cursor = movement::previous_subword_start(map, selection.head());
11347                        selection.set_head(cursor, SelectionGoal::None);
11348                    }
11349                });
11350            });
11351            this.insert("", window, cx);
11352        });
11353    }
11354
11355    pub fn move_to_next_word_end(
11356        &mut self,
11357        _: &MoveToNextWordEnd,
11358        window: &mut Window,
11359        cx: &mut Context<Self>,
11360    ) {
11361        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11362        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11363            s.move_cursors_with(|map, head, _| {
11364                (movement::next_word_end(map, head), SelectionGoal::None)
11365            });
11366        })
11367    }
11368
11369    pub fn move_to_next_subword_end(
11370        &mut self,
11371        _: &MoveToNextSubwordEnd,
11372        window: &mut Window,
11373        cx: &mut Context<Self>,
11374    ) {
11375        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11376        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11377            s.move_cursors_with(|map, head, _| {
11378                (movement::next_subword_end(map, head), SelectionGoal::None)
11379            });
11380        })
11381    }
11382
11383    pub fn select_to_next_word_end(
11384        &mut self,
11385        _: &SelectToNextWordEnd,
11386        window: &mut Window,
11387        cx: &mut Context<Self>,
11388    ) {
11389        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11391            s.move_heads_with(|map, head, _| {
11392                (movement::next_word_end(map, head), SelectionGoal::None)
11393            });
11394        })
11395    }
11396
11397    pub fn select_to_next_subword_end(
11398        &mut self,
11399        _: &SelectToNextSubwordEnd,
11400        window: &mut Window,
11401        cx: &mut Context<Self>,
11402    ) {
11403        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11404        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11405            s.move_heads_with(|map, head, _| {
11406                (movement::next_subword_end(map, head), SelectionGoal::None)
11407            });
11408        })
11409    }
11410
11411    pub fn delete_to_next_word_end(
11412        &mut self,
11413        action: &DeleteToNextWordEnd,
11414        window: &mut Window,
11415        cx: &mut Context<Self>,
11416    ) {
11417        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11418        self.transact(window, cx, |this, window, cx| {
11419            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11420                s.move_with(|map, selection| {
11421                    if selection.is_empty() {
11422                        let cursor = if action.ignore_newlines {
11423                            movement::next_word_end(map, selection.head())
11424                        } else {
11425                            movement::next_word_end_or_newline(map, selection.head())
11426                        };
11427                        selection.set_head(cursor, SelectionGoal::None);
11428                    }
11429                });
11430            });
11431            this.insert("", window, cx);
11432        });
11433    }
11434
11435    pub fn delete_to_next_subword_end(
11436        &mut self,
11437        _: &DeleteToNextSubwordEnd,
11438        window: &mut Window,
11439        cx: &mut Context<Self>,
11440    ) {
11441        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11442        self.transact(window, cx, |this, window, cx| {
11443            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11444                s.move_with(|map, selection| {
11445                    if selection.is_empty() {
11446                        let cursor = movement::next_subword_end(map, selection.head());
11447                        selection.set_head(cursor, SelectionGoal::None);
11448                    }
11449                });
11450            });
11451            this.insert("", window, cx);
11452        });
11453    }
11454
11455    pub fn move_to_beginning_of_line(
11456        &mut self,
11457        action: &MoveToBeginningOfLine,
11458        window: &mut Window,
11459        cx: &mut Context<Self>,
11460    ) {
11461        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11462        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11463            s.move_cursors_with(|map, head, _| {
11464                (
11465                    movement::indented_line_beginning(
11466                        map,
11467                        head,
11468                        action.stop_at_soft_wraps,
11469                        action.stop_at_indent,
11470                    ),
11471                    SelectionGoal::None,
11472                )
11473            });
11474        })
11475    }
11476
11477    pub fn select_to_beginning_of_line(
11478        &mut self,
11479        action: &SelectToBeginningOfLine,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482    ) {
11483        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11484        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11485            s.move_heads_with(|map, head, _| {
11486                (
11487                    movement::indented_line_beginning(
11488                        map,
11489                        head,
11490                        action.stop_at_soft_wraps,
11491                        action.stop_at_indent,
11492                    ),
11493                    SelectionGoal::None,
11494                )
11495            });
11496        });
11497    }
11498
11499    pub fn delete_to_beginning_of_line(
11500        &mut self,
11501        action: &DeleteToBeginningOfLine,
11502        window: &mut Window,
11503        cx: &mut Context<Self>,
11504    ) {
11505        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11506        self.transact(window, cx, |this, window, cx| {
11507            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11508                s.move_with(|_, selection| {
11509                    selection.reversed = true;
11510                });
11511            });
11512
11513            this.select_to_beginning_of_line(
11514                &SelectToBeginningOfLine {
11515                    stop_at_soft_wraps: false,
11516                    stop_at_indent: action.stop_at_indent,
11517                },
11518                window,
11519                cx,
11520            );
11521            this.backspace(&Backspace, window, cx);
11522        });
11523    }
11524
11525    pub fn move_to_end_of_line(
11526        &mut self,
11527        action: &MoveToEndOfLine,
11528        window: &mut Window,
11529        cx: &mut Context<Self>,
11530    ) {
11531        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11532        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11533            s.move_cursors_with(|map, head, _| {
11534                (
11535                    movement::line_end(map, head, action.stop_at_soft_wraps),
11536                    SelectionGoal::None,
11537                )
11538            });
11539        })
11540    }
11541
11542    pub fn select_to_end_of_line(
11543        &mut self,
11544        action: &SelectToEndOfLine,
11545        window: &mut Window,
11546        cx: &mut Context<Self>,
11547    ) {
11548        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11549        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11550            s.move_heads_with(|map, head, _| {
11551                (
11552                    movement::line_end(map, head, action.stop_at_soft_wraps),
11553                    SelectionGoal::None,
11554                )
11555            });
11556        })
11557    }
11558
11559    pub fn delete_to_end_of_line(
11560        &mut self,
11561        _: &DeleteToEndOfLine,
11562        window: &mut Window,
11563        cx: &mut Context<Self>,
11564    ) {
11565        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11566        self.transact(window, cx, |this, window, cx| {
11567            this.select_to_end_of_line(
11568                &SelectToEndOfLine {
11569                    stop_at_soft_wraps: false,
11570                },
11571                window,
11572                cx,
11573            );
11574            this.delete(&Delete, window, cx);
11575        });
11576    }
11577
11578    pub fn cut_to_end_of_line(
11579        &mut self,
11580        _: &CutToEndOfLine,
11581        window: &mut Window,
11582        cx: &mut Context<Self>,
11583    ) {
11584        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11585        self.transact(window, cx, |this, window, cx| {
11586            this.select_to_end_of_line(
11587                &SelectToEndOfLine {
11588                    stop_at_soft_wraps: false,
11589                },
11590                window,
11591                cx,
11592            );
11593            this.cut(&Cut, window, cx);
11594        });
11595    }
11596
11597    pub fn move_to_start_of_paragraph(
11598        &mut self,
11599        _: &MoveToStartOfParagraph,
11600        window: &mut Window,
11601        cx: &mut Context<Self>,
11602    ) {
11603        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11604            cx.propagate();
11605            return;
11606        }
11607        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11608        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11609            s.move_with(|map, selection| {
11610                selection.collapse_to(
11611                    movement::start_of_paragraph(map, selection.head(), 1),
11612                    SelectionGoal::None,
11613                )
11614            });
11615        })
11616    }
11617
11618    pub fn move_to_end_of_paragraph(
11619        &mut self,
11620        _: &MoveToEndOfParagraph,
11621        window: &mut Window,
11622        cx: &mut Context<Self>,
11623    ) {
11624        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11625            cx.propagate();
11626            return;
11627        }
11628        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11629        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11630            s.move_with(|map, selection| {
11631                selection.collapse_to(
11632                    movement::end_of_paragraph(map, selection.head(), 1),
11633                    SelectionGoal::None,
11634                )
11635            });
11636        })
11637    }
11638
11639    pub fn select_to_start_of_paragraph(
11640        &mut self,
11641        _: &SelectToStartOfParagraph,
11642        window: &mut Window,
11643        cx: &mut Context<Self>,
11644    ) {
11645        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11646            cx.propagate();
11647            return;
11648        }
11649        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11650        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11651            s.move_heads_with(|map, head, _| {
11652                (
11653                    movement::start_of_paragraph(map, head, 1),
11654                    SelectionGoal::None,
11655                )
11656            });
11657        })
11658    }
11659
11660    pub fn select_to_end_of_paragraph(
11661        &mut self,
11662        _: &SelectToEndOfParagraph,
11663        window: &mut Window,
11664        cx: &mut Context<Self>,
11665    ) {
11666        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11667            cx.propagate();
11668            return;
11669        }
11670        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11671        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11672            s.move_heads_with(|map, head, _| {
11673                (
11674                    movement::end_of_paragraph(map, head, 1),
11675                    SelectionGoal::None,
11676                )
11677            });
11678        })
11679    }
11680
11681    pub fn move_to_start_of_excerpt(
11682        &mut self,
11683        _: &MoveToStartOfExcerpt,
11684        window: &mut Window,
11685        cx: &mut Context<Self>,
11686    ) {
11687        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11688            cx.propagate();
11689            return;
11690        }
11691        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11692        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11693            s.move_with(|map, selection| {
11694                selection.collapse_to(
11695                    movement::start_of_excerpt(
11696                        map,
11697                        selection.head(),
11698                        workspace::searchable::Direction::Prev,
11699                    ),
11700                    SelectionGoal::None,
11701                )
11702            });
11703        })
11704    }
11705
11706    pub fn move_to_start_of_next_excerpt(
11707        &mut self,
11708        _: &MoveToStartOfNextExcerpt,
11709        window: &mut Window,
11710        cx: &mut Context<Self>,
11711    ) {
11712        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11713            cx.propagate();
11714            return;
11715        }
11716
11717        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11718            s.move_with(|map, selection| {
11719                selection.collapse_to(
11720                    movement::start_of_excerpt(
11721                        map,
11722                        selection.head(),
11723                        workspace::searchable::Direction::Next,
11724                    ),
11725                    SelectionGoal::None,
11726                )
11727            });
11728        })
11729    }
11730
11731    pub fn move_to_end_of_excerpt(
11732        &mut self,
11733        _: &MoveToEndOfExcerpt,
11734        window: &mut Window,
11735        cx: &mut Context<Self>,
11736    ) {
11737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11738            cx.propagate();
11739            return;
11740        }
11741        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11742        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11743            s.move_with(|map, selection| {
11744                selection.collapse_to(
11745                    movement::end_of_excerpt(
11746                        map,
11747                        selection.head(),
11748                        workspace::searchable::Direction::Next,
11749                    ),
11750                    SelectionGoal::None,
11751                )
11752            });
11753        })
11754    }
11755
11756    pub fn move_to_end_of_previous_excerpt(
11757        &mut self,
11758        _: &MoveToEndOfPreviousExcerpt,
11759        window: &mut Window,
11760        cx: &mut Context<Self>,
11761    ) {
11762        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11763            cx.propagate();
11764            return;
11765        }
11766        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11767        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11768            s.move_with(|map, selection| {
11769                selection.collapse_to(
11770                    movement::end_of_excerpt(
11771                        map,
11772                        selection.head(),
11773                        workspace::searchable::Direction::Prev,
11774                    ),
11775                    SelectionGoal::None,
11776                )
11777            });
11778        })
11779    }
11780
11781    pub fn select_to_start_of_excerpt(
11782        &mut self,
11783        _: &SelectToStartOfExcerpt,
11784        window: &mut Window,
11785        cx: &mut Context<Self>,
11786    ) {
11787        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11788            cx.propagate();
11789            return;
11790        }
11791        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11793            s.move_heads_with(|map, head, _| {
11794                (
11795                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11796                    SelectionGoal::None,
11797                )
11798            });
11799        })
11800    }
11801
11802    pub fn select_to_start_of_next_excerpt(
11803        &mut self,
11804        _: &SelectToStartOfNextExcerpt,
11805        window: &mut Window,
11806        cx: &mut Context<Self>,
11807    ) {
11808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11809            cx.propagate();
11810            return;
11811        }
11812        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11813        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11814            s.move_heads_with(|map, head, _| {
11815                (
11816                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11817                    SelectionGoal::None,
11818                )
11819            });
11820        })
11821    }
11822
11823    pub fn select_to_end_of_excerpt(
11824        &mut self,
11825        _: &SelectToEndOfExcerpt,
11826        window: &mut Window,
11827        cx: &mut Context<Self>,
11828    ) {
11829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11830            cx.propagate();
11831            return;
11832        }
11833        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11835            s.move_heads_with(|map, head, _| {
11836                (
11837                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11838                    SelectionGoal::None,
11839                )
11840            });
11841        })
11842    }
11843
11844    pub fn select_to_end_of_previous_excerpt(
11845        &mut self,
11846        _: &SelectToEndOfPreviousExcerpt,
11847        window: &mut Window,
11848        cx: &mut Context<Self>,
11849    ) {
11850        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11851            cx.propagate();
11852            return;
11853        }
11854        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11856            s.move_heads_with(|map, head, _| {
11857                (
11858                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11859                    SelectionGoal::None,
11860                )
11861            });
11862        })
11863    }
11864
11865    pub fn move_to_beginning(
11866        &mut self,
11867        _: &MoveToBeginning,
11868        window: &mut Window,
11869        cx: &mut Context<Self>,
11870    ) {
11871        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11872            cx.propagate();
11873            return;
11874        }
11875        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11876        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11877            s.select_ranges(vec![0..0]);
11878        });
11879    }
11880
11881    pub fn select_to_beginning(
11882        &mut self,
11883        _: &SelectToBeginning,
11884        window: &mut Window,
11885        cx: &mut Context<Self>,
11886    ) {
11887        let mut selection = self.selections.last::<Point>(cx);
11888        selection.set_head(Point::zero(), SelectionGoal::None);
11889        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11890        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11891            s.select(vec![selection]);
11892        });
11893    }
11894
11895    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11896        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11897            cx.propagate();
11898            return;
11899        }
11900        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11901        let cursor = self.buffer.read(cx).read(cx).len();
11902        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11903            s.select_ranges(vec![cursor..cursor])
11904        });
11905    }
11906
11907    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11908        self.nav_history = nav_history;
11909    }
11910
11911    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11912        self.nav_history.as_ref()
11913    }
11914
11915    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11916        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11917    }
11918
11919    fn push_to_nav_history(
11920        &mut self,
11921        cursor_anchor: Anchor,
11922        new_position: Option<Point>,
11923        is_deactivate: bool,
11924        cx: &mut Context<Self>,
11925    ) {
11926        if let Some(nav_history) = self.nav_history.as_mut() {
11927            let buffer = self.buffer.read(cx).read(cx);
11928            let cursor_position = cursor_anchor.to_point(&buffer);
11929            let scroll_state = self.scroll_manager.anchor();
11930            let scroll_top_row = scroll_state.top_row(&buffer);
11931            drop(buffer);
11932
11933            if let Some(new_position) = new_position {
11934                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11935                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11936                    return;
11937                }
11938            }
11939
11940            nav_history.push(
11941                Some(NavigationData {
11942                    cursor_anchor,
11943                    cursor_position,
11944                    scroll_anchor: scroll_state,
11945                    scroll_top_row,
11946                }),
11947                cx,
11948            );
11949            cx.emit(EditorEvent::PushedToNavHistory {
11950                anchor: cursor_anchor,
11951                is_deactivate,
11952            })
11953        }
11954    }
11955
11956    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11957        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11958        let buffer = self.buffer.read(cx).snapshot(cx);
11959        let mut selection = self.selections.first::<usize>(cx);
11960        selection.set_head(buffer.len(), SelectionGoal::None);
11961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11962            s.select(vec![selection]);
11963        });
11964    }
11965
11966    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11967        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11968        let end = self.buffer.read(cx).read(cx).len();
11969        self.change_selections(None, window, cx, |s| {
11970            s.select_ranges(vec![0..end]);
11971        });
11972    }
11973
11974    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11975        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11977        let mut selections = self.selections.all::<Point>(cx);
11978        let max_point = display_map.buffer_snapshot.max_point();
11979        for selection in &mut selections {
11980            let rows = selection.spanned_rows(true, &display_map);
11981            selection.start = Point::new(rows.start.0, 0);
11982            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11983            selection.reversed = false;
11984        }
11985        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11986            s.select(selections);
11987        });
11988    }
11989
11990    pub fn split_selection_into_lines(
11991        &mut self,
11992        _: &SplitSelectionIntoLines,
11993        window: &mut Window,
11994        cx: &mut Context<Self>,
11995    ) {
11996        let selections = self
11997            .selections
11998            .all::<Point>(cx)
11999            .into_iter()
12000            .map(|selection| selection.start..selection.end)
12001            .collect::<Vec<_>>();
12002        self.unfold_ranges(&selections, true, true, cx);
12003
12004        let mut new_selection_ranges = Vec::new();
12005        {
12006            let buffer = self.buffer.read(cx).read(cx);
12007            for selection in selections {
12008                for row in selection.start.row..selection.end.row {
12009                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12010                    new_selection_ranges.push(cursor..cursor);
12011                }
12012
12013                let is_multiline_selection = selection.start.row != selection.end.row;
12014                // Don't insert last one if it's a multi-line selection ending at the start of a line,
12015                // so this action feels more ergonomic when paired with other selection operations
12016                let should_skip_last = is_multiline_selection && selection.end.column == 0;
12017                if !should_skip_last {
12018                    new_selection_ranges.push(selection.end..selection.end);
12019                }
12020            }
12021        }
12022        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12023            s.select_ranges(new_selection_ranges);
12024        });
12025    }
12026
12027    pub fn add_selection_above(
12028        &mut self,
12029        _: &AddSelectionAbove,
12030        window: &mut Window,
12031        cx: &mut Context<Self>,
12032    ) {
12033        self.add_selection(true, window, cx);
12034    }
12035
12036    pub fn add_selection_below(
12037        &mut self,
12038        _: &AddSelectionBelow,
12039        window: &mut Window,
12040        cx: &mut Context<Self>,
12041    ) {
12042        self.add_selection(false, window, cx);
12043    }
12044
12045    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12046        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12047
12048        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12049        let mut selections = self.selections.all::<Point>(cx);
12050        let text_layout_details = self.text_layout_details(window);
12051        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12052            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12053            let range = oldest_selection.display_range(&display_map).sorted();
12054
12055            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12056            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12057            let positions = start_x.min(end_x)..start_x.max(end_x);
12058
12059            selections.clear();
12060            let mut stack = Vec::new();
12061            for row in range.start.row().0..=range.end.row().0 {
12062                if let Some(selection) = self.selections.build_columnar_selection(
12063                    &display_map,
12064                    DisplayRow(row),
12065                    &positions,
12066                    oldest_selection.reversed,
12067                    &text_layout_details,
12068                ) {
12069                    stack.push(selection.id);
12070                    selections.push(selection);
12071                }
12072            }
12073
12074            if above {
12075                stack.reverse();
12076            }
12077
12078            AddSelectionsState { above, stack }
12079        });
12080
12081        let last_added_selection = *state.stack.last().unwrap();
12082        let mut new_selections = Vec::new();
12083        if above == state.above {
12084            let end_row = if above {
12085                DisplayRow(0)
12086            } else {
12087                display_map.max_point().row()
12088            };
12089
12090            'outer: for selection in selections {
12091                if selection.id == last_added_selection {
12092                    let range = selection.display_range(&display_map).sorted();
12093                    debug_assert_eq!(range.start.row(), range.end.row());
12094                    let mut row = range.start.row();
12095                    let positions =
12096                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12097                            px(start)..px(end)
12098                        } else {
12099                            let start_x =
12100                                display_map.x_for_display_point(range.start, &text_layout_details);
12101                            let end_x =
12102                                display_map.x_for_display_point(range.end, &text_layout_details);
12103                            start_x.min(end_x)..start_x.max(end_x)
12104                        };
12105
12106                    while row != end_row {
12107                        if above {
12108                            row.0 -= 1;
12109                        } else {
12110                            row.0 += 1;
12111                        }
12112
12113                        if let Some(new_selection) = self.selections.build_columnar_selection(
12114                            &display_map,
12115                            row,
12116                            &positions,
12117                            selection.reversed,
12118                            &text_layout_details,
12119                        ) {
12120                            state.stack.push(new_selection.id);
12121                            if above {
12122                                new_selections.push(new_selection);
12123                                new_selections.push(selection);
12124                            } else {
12125                                new_selections.push(selection);
12126                                new_selections.push(new_selection);
12127                            }
12128
12129                            continue 'outer;
12130                        }
12131                    }
12132                }
12133
12134                new_selections.push(selection);
12135            }
12136        } else {
12137            new_selections = selections;
12138            new_selections.retain(|s| s.id != last_added_selection);
12139            state.stack.pop();
12140        }
12141
12142        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12143            s.select(new_selections);
12144        });
12145        if state.stack.len() > 1 {
12146            self.add_selections_state = Some(state);
12147        }
12148    }
12149
12150    fn select_match_ranges(
12151        &mut self,
12152        range: Range<usize>,
12153        reversed: bool,
12154        replace_newest: bool,
12155        auto_scroll: Option<Autoscroll>,
12156        window: &mut Window,
12157        cx: &mut Context<Editor>,
12158    ) {
12159        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12160        self.change_selections(auto_scroll, window, cx, |s| {
12161            if replace_newest {
12162                s.delete(s.newest_anchor().id);
12163            }
12164            if reversed {
12165                s.insert_range(range.end..range.start);
12166            } else {
12167                s.insert_range(range);
12168            }
12169        });
12170    }
12171
12172    pub fn select_next_match_internal(
12173        &mut self,
12174        display_map: &DisplaySnapshot,
12175        replace_newest: bool,
12176        autoscroll: Option<Autoscroll>,
12177        window: &mut Window,
12178        cx: &mut Context<Self>,
12179    ) -> Result<()> {
12180        let buffer = &display_map.buffer_snapshot;
12181        let mut selections = self.selections.all::<usize>(cx);
12182        if let Some(mut select_next_state) = self.select_next_state.take() {
12183            let query = &select_next_state.query;
12184            if !select_next_state.done {
12185                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12186                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12187                let mut next_selected_range = None;
12188
12189                let bytes_after_last_selection =
12190                    buffer.bytes_in_range(last_selection.end..buffer.len());
12191                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12192                let query_matches = query
12193                    .stream_find_iter(bytes_after_last_selection)
12194                    .map(|result| (last_selection.end, result))
12195                    .chain(
12196                        query
12197                            .stream_find_iter(bytes_before_first_selection)
12198                            .map(|result| (0, result)),
12199                    );
12200
12201                for (start_offset, query_match) in query_matches {
12202                    let query_match = query_match.unwrap(); // can only fail due to I/O
12203                    let offset_range =
12204                        start_offset + query_match.start()..start_offset + query_match.end();
12205                    let display_range = offset_range.start.to_display_point(display_map)
12206                        ..offset_range.end.to_display_point(display_map);
12207
12208                    if !select_next_state.wordwise
12209                        || (!movement::is_inside_word(display_map, display_range.start)
12210                            && !movement::is_inside_word(display_map, display_range.end))
12211                    {
12212                        // TODO: This is n^2, because we might check all the selections
12213                        if !selections
12214                            .iter()
12215                            .any(|selection| selection.range().overlaps(&offset_range))
12216                        {
12217                            next_selected_range = Some(offset_range);
12218                            break;
12219                        }
12220                    }
12221                }
12222
12223                if let Some(next_selected_range) = next_selected_range {
12224                    self.select_match_ranges(
12225                        next_selected_range,
12226                        last_selection.reversed,
12227                        replace_newest,
12228                        autoscroll,
12229                        window,
12230                        cx,
12231                    );
12232                } else {
12233                    select_next_state.done = true;
12234                }
12235            }
12236
12237            self.select_next_state = Some(select_next_state);
12238        } else {
12239            let mut only_carets = true;
12240            let mut same_text_selected = true;
12241            let mut selected_text = None;
12242
12243            let mut selections_iter = selections.iter().peekable();
12244            while let Some(selection) = selections_iter.next() {
12245                if selection.start != selection.end {
12246                    only_carets = false;
12247                }
12248
12249                if same_text_selected {
12250                    if selected_text.is_none() {
12251                        selected_text =
12252                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12253                    }
12254
12255                    if let Some(next_selection) = selections_iter.peek() {
12256                        if next_selection.range().len() == selection.range().len() {
12257                            let next_selected_text = buffer
12258                                .text_for_range(next_selection.range())
12259                                .collect::<String>();
12260                            if Some(next_selected_text) != selected_text {
12261                                same_text_selected = false;
12262                                selected_text = None;
12263                            }
12264                        } else {
12265                            same_text_selected = false;
12266                            selected_text = None;
12267                        }
12268                    }
12269                }
12270            }
12271
12272            if only_carets {
12273                for selection in &mut selections {
12274                    let word_range = movement::surrounding_word(
12275                        display_map,
12276                        selection.start.to_display_point(display_map),
12277                    );
12278                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12279                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12280                    selection.goal = SelectionGoal::None;
12281                    selection.reversed = false;
12282                    self.select_match_ranges(
12283                        selection.start..selection.end,
12284                        selection.reversed,
12285                        replace_newest,
12286                        autoscroll,
12287                        window,
12288                        cx,
12289                    );
12290                }
12291
12292                if selections.len() == 1 {
12293                    let selection = selections
12294                        .last()
12295                        .expect("ensured that there's only one selection");
12296                    let query = buffer
12297                        .text_for_range(selection.start..selection.end)
12298                        .collect::<String>();
12299                    let is_empty = query.is_empty();
12300                    let select_state = SelectNextState {
12301                        query: AhoCorasick::new(&[query])?,
12302                        wordwise: true,
12303                        done: is_empty,
12304                    };
12305                    self.select_next_state = Some(select_state);
12306                } else {
12307                    self.select_next_state = None;
12308                }
12309            } else if let Some(selected_text) = selected_text {
12310                self.select_next_state = Some(SelectNextState {
12311                    query: AhoCorasick::new(&[selected_text])?,
12312                    wordwise: false,
12313                    done: false,
12314                });
12315                self.select_next_match_internal(
12316                    display_map,
12317                    replace_newest,
12318                    autoscroll,
12319                    window,
12320                    cx,
12321                )?;
12322            }
12323        }
12324        Ok(())
12325    }
12326
12327    pub fn select_all_matches(
12328        &mut self,
12329        _action: &SelectAllMatches,
12330        window: &mut Window,
12331        cx: &mut Context<Self>,
12332    ) -> Result<()> {
12333        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12334
12335        self.push_to_selection_history();
12336        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12337
12338        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12339        let Some(select_next_state) = self.select_next_state.as_mut() else {
12340            return Ok(());
12341        };
12342        if select_next_state.done {
12343            return Ok(());
12344        }
12345
12346        let mut new_selections = Vec::new();
12347
12348        let reversed = self.selections.oldest::<usize>(cx).reversed;
12349        let buffer = &display_map.buffer_snapshot;
12350        let query_matches = select_next_state
12351            .query
12352            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12353
12354        for query_match in query_matches.into_iter() {
12355            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12356            let offset_range = if reversed {
12357                query_match.end()..query_match.start()
12358            } else {
12359                query_match.start()..query_match.end()
12360            };
12361            let display_range = offset_range.start.to_display_point(&display_map)
12362                ..offset_range.end.to_display_point(&display_map);
12363
12364            if !select_next_state.wordwise
12365                || (!movement::is_inside_word(&display_map, display_range.start)
12366                    && !movement::is_inside_word(&display_map, display_range.end))
12367            {
12368                new_selections.push(offset_range.start..offset_range.end);
12369            }
12370        }
12371
12372        select_next_state.done = true;
12373        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12374        self.change_selections(None, window, cx, |selections| {
12375            selections.select_ranges(new_selections)
12376        });
12377
12378        Ok(())
12379    }
12380
12381    pub fn select_next(
12382        &mut self,
12383        action: &SelectNext,
12384        window: &mut Window,
12385        cx: &mut Context<Self>,
12386    ) -> Result<()> {
12387        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12388        self.push_to_selection_history();
12389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12390        self.select_next_match_internal(
12391            &display_map,
12392            action.replace_newest,
12393            Some(Autoscroll::newest()),
12394            window,
12395            cx,
12396        )?;
12397        Ok(())
12398    }
12399
12400    pub fn select_previous(
12401        &mut self,
12402        action: &SelectPrevious,
12403        window: &mut Window,
12404        cx: &mut Context<Self>,
12405    ) -> Result<()> {
12406        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12407        self.push_to_selection_history();
12408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12409        let buffer = &display_map.buffer_snapshot;
12410        let mut selections = self.selections.all::<usize>(cx);
12411        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12412            let query = &select_prev_state.query;
12413            if !select_prev_state.done {
12414                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12415                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12416                let mut next_selected_range = None;
12417                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12418                let bytes_before_last_selection =
12419                    buffer.reversed_bytes_in_range(0..last_selection.start);
12420                let bytes_after_first_selection =
12421                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12422                let query_matches = query
12423                    .stream_find_iter(bytes_before_last_selection)
12424                    .map(|result| (last_selection.start, result))
12425                    .chain(
12426                        query
12427                            .stream_find_iter(bytes_after_first_selection)
12428                            .map(|result| (buffer.len(), result)),
12429                    );
12430                for (end_offset, query_match) in query_matches {
12431                    let query_match = query_match.unwrap(); // can only fail due to I/O
12432                    let offset_range =
12433                        end_offset - query_match.end()..end_offset - query_match.start();
12434                    let display_range = offset_range.start.to_display_point(&display_map)
12435                        ..offset_range.end.to_display_point(&display_map);
12436
12437                    if !select_prev_state.wordwise
12438                        || (!movement::is_inside_word(&display_map, display_range.start)
12439                            && !movement::is_inside_word(&display_map, display_range.end))
12440                    {
12441                        next_selected_range = Some(offset_range);
12442                        break;
12443                    }
12444                }
12445
12446                if let Some(next_selected_range) = next_selected_range {
12447                    self.select_match_ranges(
12448                        next_selected_range,
12449                        last_selection.reversed,
12450                        action.replace_newest,
12451                        Some(Autoscroll::newest()),
12452                        window,
12453                        cx,
12454                    );
12455                } else {
12456                    select_prev_state.done = true;
12457                }
12458            }
12459
12460            self.select_prev_state = Some(select_prev_state);
12461        } else {
12462            let mut only_carets = true;
12463            let mut same_text_selected = true;
12464            let mut selected_text = None;
12465
12466            let mut selections_iter = selections.iter().peekable();
12467            while let Some(selection) = selections_iter.next() {
12468                if selection.start != selection.end {
12469                    only_carets = false;
12470                }
12471
12472                if same_text_selected {
12473                    if selected_text.is_none() {
12474                        selected_text =
12475                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12476                    }
12477
12478                    if let Some(next_selection) = selections_iter.peek() {
12479                        if next_selection.range().len() == selection.range().len() {
12480                            let next_selected_text = buffer
12481                                .text_for_range(next_selection.range())
12482                                .collect::<String>();
12483                            if Some(next_selected_text) != selected_text {
12484                                same_text_selected = false;
12485                                selected_text = None;
12486                            }
12487                        } else {
12488                            same_text_selected = false;
12489                            selected_text = None;
12490                        }
12491                    }
12492                }
12493            }
12494
12495            if only_carets {
12496                for selection in &mut selections {
12497                    let word_range = movement::surrounding_word(
12498                        &display_map,
12499                        selection.start.to_display_point(&display_map),
12500                    );
12501                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12502                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12503                    selection.goal = SelectionGoal::None;
12504                    selection.reversed = false;
12505                    self.select_match_ranges(
12506                        selection.start..selection.end,
12507                        selection.reversed,
12508                        action.replace_newest,
12509                        Some(Autoscroll::newest()),
12510                        window,
12511                        cx,
12512                    );
12513                }
12514                if selections.len() == 1 {
12515                    let selection = selections
12516                        .last()
12517                        .expect("ensured that there's only one selection");
12518                    let query = buffer
12519                        .text_for_range(selection.start..selection.end)
12520                        .collect::<String>();
12521                    let is_empty = query.is_empty();
12522                    let select_state = SelectNextState {
12523                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12524                        wordwise: true,
12525                        done: is_empty,
12526                    };
12527                    self.select_prev_state = Some(select_state);
12528                } else {
12529                    self.select_prev_state = None;
12530                }
12531            } else if let Some(selected_text) = selected_text {
12532                self.select_prev_state = Some(SelectNextState {
12533                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12534                    wordwise: false,
12535                    done: false,
12536                });
12537                self.select_previous(action, window, cx)?;
12538            }
12539        }
12540        Ok(())
12541    }
12542
12543    pub fn find_next_match(
12544        &mut self,
12545        _: &FindNextMatch,
12546        window: &mut Window,
12547        cx: &mut Context<Self>,
12548    ) -> Result<()> {
12549        let selections = self.selections.disjoint_anchors();
12550        match selections.first() {
12551            Some(first) if selections.len() >= 2 => {
12552                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12553                    s.select_ranges([first.range()]);
12554                });
12555            }
12556            _ => self.select_next(
12557                &SelectNext {
12558                    replace_newest: true,
12559                },
12560                window,
12561                cx,
12562            )?,
12563        }
12564        Ok(())
12565    }
12566
12567    pub fn find_previous_match(
12568        &mut self,
12569        _: &FindPreviousMatch,
12570        window: &mut Window,
12571        cx: &mut Context<Self>,
12572    ) -> Result<()> {
12573        let selections = self.selections.disjoint_anchors();
12574        match selections.last() {
12575            Some(last) if selections.len() >= 2 => {
12576                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12577                    s.select_ranges([last.range()]);
12578                });
12579            }
12580            _ => self.select_previous(
12581                &SelectPrevious {
12582                    replace_newest: true,
12583                },
12584                window,
12585                cx,
12586            )?,
12587        }
12588        Ok(())
12589    }
12590
12591    pub fn toggle_comments(
12592        &mut self,
12593        action: &ToggleComments,
12594        window: &mut Window,
12595        cx: &mut Context<Self>,
12596    ) {
12597        if self.read_only(cx) {
12598            return;
12599        }
12600        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12601        let text_layout_details = &self.text_layout_details(window);
12602        self.transact(window, cx, |this, window, cx| {
12603            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12604            let mut edits = Vec::new();
12605            let mut selection_edit_ranges = Vec::new();
12606            let mut last_toggled_row = None;
12607            let snapshot = this.buffer.read(cx).read(cx);
12608            let empty_str: Arc<str> = Arc::default();
12609            let mut suffixes_inserted = Vec::new();
12610            let ignore_indent = action.ignore_indent;
12611
12612            fn comment_prefix_range(
12613                snapshot: &MultiBufferSnapshot,
12614                row: MultiBufferRow,
12615                comment_prefix: &str,
12616                comment_prefix_whitespace: &str,
12617                ignore_indent: bool,
12618            ) -> Range<Point> {
12619                let indent_size = if ignore_indent {
12620                    0
12621                } else {
12622                    snapshot.indent_size_for_line(row).len
12623                };
12624
12625                let start = Point::new(row.0, indent_size);
12626
12627                let mut line_bytes = snapshot
12628                    .bytes_in_range(start..snapshot.max_point())
12629                    .flatten()
12630                    .copied();
12631
12632                // If this line currently begins with the line comment prefix, then record
12633                // the range containing the prefix.
12634                if line_bytes
12635                    .by_ref()
12636                    .take(comment_prefix.len())
12637                    .eq(comment_prefix.bytes())
12638                {
12639                    // Include any whitespace that matches the comment prefix.
12640                    let matching_whitespace_len = line_bytes
12641                        .zip(comment_prefix_whitespace.bytes())
12642                        .take_while(|(a, b)| a == b)
12643                        .count() as u32;
12644                    let end = Point::new(
12645                        start.row,
12646                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12647                    );
12648                    start..end
12649                } else {
12650                    start..start
12651                }
12652            }
12653
12654            fn comment_suffix_range(
12655                snapshot: &MultiBufferSnapshot,
12656                row: MultiBufferRow,
12657                comment_suffix: &str,
12658                comment_suffix_has_leading_space: bool,
12659            ) -> Range<Point> {
12660                let end = Point::new(row.0, snapshot.line_len(row));
12661                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12662
12663                let mut line_end_bytes = snapshot
12664                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12665                    .flatten()
12666                    .copied();
12667
12668                let leading_space_len = if suffix_start_column > 0
12669                    && line_end_bytes.next() == Some(b' ')
12670                    && comment_suffix_has_leading_space
12671                {
12672                    1
12673                } else {
12674                    0
12675                };
12676
12677                // If this line currently begins with the line comment prefix, then record
12678                // the range containing the prefix.
12679                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12680                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12681                    start..end
12682                } else {
12683                    end..end
12684                }
12685            }
12686
12687            // TODO: Handle selections that cross excerpts
12688            for selection in &mut selections {
12689                let start_column = snapshot
12690                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12691                    .len;
12692                let language = if let Some(language) =
12693                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12694                {
12695                    language
12696                } else {
12697                    continue;
12698                };
12699
12700                selection_edit_ranges.clear();
12701
12702                // If multiple selections contain a given row, avoid processing that
12703                // row more than once.
12704                let mut start_row = MultiBufferRow(selection.start.row);
12705                if last_toggled_row == Some(start_row) {
12706                    start_row = start_row.next_row();
12707                }
12708                let end_row =
12709                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12710                        MultiBufferRow(selection.end.row - 1)
12711                    } else {
12712                        MultiBufferRow(selection.end.row)
12713                    };
12714                last_toggled_row = Some(end_row);
12715
12716                if start_row > end_row {
12717                    continue;
12718                }
12719
12720                // If the language has line comments, toggle those.
12721                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12722
12723                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12724                if ignore_indent {
12725                    full_comment_prefixes = full_comment_prefixes
12726                        .into_iter()
12727                        .map(|s| Arc::from(s.trim_end()))
12728                        .collect();
12729                }
12730
12731                if !full_comment_prefixes.is_empty() {
12732                    let first_prefix = full_comment_prefixes
12733                        .first()
12734                        .expect("prefixes is non-empty");
12735                    let prefix_trimmed_lengths = full_comment_prefixes
12736                        .iter()
12737                        .map(|p| p.trim_end_matches(' ').len())
12738                        .collect::<SmallVec<[usize; 4]>>();
12739
12740                    let mut all_selection_lines_are_comments = true;
12741
12742                    for row in start_row.0..=end_row.0 {
12743                        let row = MultiBufferRow(row);
12744                        if start_row < end_row && snapshot.is_line_blank(row) {
12745                            continue;
12746                        }
12747
12748                        let prefix_range = full_comment_prefixes
12749                            .iter()
12750                            .zip(prefix_trimmed_lengths.iter().copied())
12751                            .map(|(prefix, trimmed_prefix_len)| {
12752                                comment_prefix_range(
12753                                    snapshot.deref(),
12754                                    row,
12755                                    &prefix[..trimmed_prefix_len],
12756                                    &prefix[trimmed_prefix_len..],
12757                                    ignore_indent,
12758                                )
12759                            })
12760                            .max_by_key(|range| range.end.column - range.start.column)
12761                            .expect("prefixes is non-empty");
12762
12763                        if prefix_range.is_empty() {
12764                            all_selection_lines_are_comments = false;
12765                        }
12766
12767                        selection_edit_ranges.push(prefix_range);
12768                    }
12769
12770                    if all_selection_lines_are_comments {
12771                        edits.extend(
12772                            selection_edit_ranges
12773                                .iter()
12774                                .cloned()
12775                                .map(|range| (range, empty_str.clone())),
12776                        );
12777                    } else {
12778                        let min_column = selection_edit_ranges
12779                            .iter()
12780                            .map(|range| range.start.column)
12781                            .min()
12782                            .unwrap_or(0);
12783                        edits.extend(selection_edit_ranges.iter().map(|range| {
12784                            let position = Point::new(range.start.row, min_column);
12785                            (position..position, first_prefix.clone())
12786                        }));
12787                    }
12788                } else if let Some((full_comment_prefix, comment_suffix)) =
12789                    language.block_comment_delimiters()
12790                {
12791                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12792                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12793                    let prefix_range = comment_prefix_range(
12794                        snapshot.deref(),
12795                        start_row,
12796                        comment_prefix,
12797                        comment_prefix_whitespace,
12798                        ignore_indent,
12799                    );
12800                    let suffix_range = comment_suffix_range(
12801                        snapshot.deref(),
12802                        end_row,
12803                        comment_suffix.trim_start_matches(' '),
12804                        comment_suffix.starts_with(' '),
12805                    );
12806
12807                    if prefix_range.is_empty() || suffix_range.is_empty() {
12808                        edits.push((
12809                            prefix_range.start..prefix_range.start,
12810                            full_comment_prefix.clone(),
12811                        ));
12812                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12813                        suffixes_inserted.push((end_row, comment_suffix.len()));
12814                    } else {
12815                        edits.push((prefix_range, empty_str.clone()));
12816                        edits.push((suffix_range, empty_str.clone()));
12817                    }
12818                } else {
12819                    continue;
12820                }
12821            }
12822
12823            drop(snapshot);
12824            this.buffer.update(cx, |buffer, cx| {
12825                buffer.edit(edits, None, cx);
12826            });
12827
12828            // Adjust selections so that they end before any comment suffixes that
12829            // were inserted.
12830            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12831            let mut selections = this.selections.all::<Point>(cx);
12832            let snapshot = this.buffer.read(cx).read(cx);
12833            for selection in &mut selections {
12834                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12835                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12836                        Ordering::Less => {
12837                            suffixes_inserted.next();
12838                            continue;
12839                        }
12840                        Ordering::Greater => break,
12841                        Ordering::Equal => {
12842                            if selection.end.column == snapshot.line_len(row) {
12843                                if selection.is_empty() {
12844                                    selection.start.column -= suffix_len as u32;
12845                                }
12846                                selection.end.column -= suffix_len as u32;
12847                            }
12848                            break;
12849                        }
12850                    }
12851                }
12852            }
12853
12854            drop(snapshot);
12855            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12856                s.select(selections)
12857            });
12858
12859            let selections = this.selections.all::<Point>(cx);
12860            let selections_on_single_row = selections.windows(2).all(|selections| {
12861                selections[0].start.row == selections[1].start.row
12862                    && selections[0].end.row == selections[1].end.row
12863                    && selections[0].start.row == selections[0].end.row
12864            });
12865            let selections_selecting = selections
12866                .iter()
12867                .any(|selection| selection.start != selection.end);
12868            let advance_downwards = action.advance_downwards
12869                && selections_on_single_row
12870                && !selections_selecting
12871                && !matches!(this.mode, EditorMode::SingleLine { .. });
12872
12873            if advance_downwards {
12874                let snapshot = this.buffer.read(cx).snapshot(cx);
12875
12876                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12877                    s.move_cursors_with(|display_snapshot, display_point, _| {
12878                        let mut point = display_point.to_point(display_snapshot);
12879                        point.row += 1;
12880                        point = snapshot.clip_point(point, Bias::Left);
12881                        let display_point = point.to_display_point(display_snapshot);
12882                        let goal = SelectionGoal::HorizontalPosition(
12883                            display_snapshot
12884                                .x_for_display_point(display_point, text_layout_details)
12885                                .into(),
12886                        );
12887                        (display_point, goal)
12888                    })
12889                });
12890            }
12891        });
12892    }
12893
12894    pub fn select_enclosing_symbol(
12895        &mut self,
12896        _: &SelectEnclosingSymbol,
12897        window: &mut Window,
12898        cx: &mut Context<Self>,
12899    ) {
12900        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12901
12902        let buffer = self.buffer.read(cx).snapshot(cx);
12903        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12904
12905        fn update_selection(
12906            selection: &Selection<usize>,
12907            buffer_snap: &MultiBufferSnapshot,
12908        ) -> Option<Selection<usize>> {
12909            let cursor = selection.head();
12910            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12911            for symbol in symbols.iter().rev() {
12912                let start = symbol.range.start.to_offset(buffer_snap);
12913                let end = symbol.range.end.to_offset(buffer_snap);
12914                let new_range = start..end;
12915                if start < selection.start || end > selection.end {
12916                    return Some(Selection {
12917                        id: selection.id,
12918                        start: new_range.start,
12919                        end: new_range.end,
12920                        goal: SelectionGoal::None,
12921                        reversed: selection.reversed,
12922                    });
12923                }
12924            }
12925            None
12926        }
12927
12928        let mut selected_larger_symbol = false;
12929        let new_selections = old_selections
12930            .iter()
12931            .map(|selection| match update_selection(selection, &buffer) {
12932                Some(new_selection) => {
12933                    if new_selection.range() != selection.range() {
12934                        selected_larger_symbol = true;
12935                    }
12936                    new_selection
12937                }
12938                None => selection.clone(),
12939            })
12940            .collect::<Vec<_>>();
12941
12942        if selected_larger_symbol {
12943            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12944                s.select(new_selections);
12945            });
12946        }
12947    }
12948
12949    pub fn select_larger_syntax_node(
12950        &mut self,
12951        _: &SelectLargerSyntaxNode,
12952        window: &mut Window,
12953        cx: &mut Context<Self>,
12954    ) {
12955        let Some(visible_row_count) = self.visible_row_count() else {
12956            return;
12957        };
12958        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12959        if old_selections.is_empty() {
12960            return;
12961        }
12962
12963        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12964
12965        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12966        let buffer = self.buffer.read(cx).snapshot(cx);
12967
12968        let mut selected_larger_node = false;
12969        let mut new_selections = old_selections
12970            .iter()
12971            .map(|selection| {
12972                let old_range = selection.start..selection.end;
12973
12974                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12975                    // manually select word at selection
12976                    if ["string_content", "inline"].contains(&node.kind()) {
12977                        let word_range = {
12978                            let display_point = buffer
12979                                .offset_to_point(old_range.start)
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                        // ignore if word is already selected
12987                        if !word_range.is_empty() && old_range != word_range {
12988                            let last_word_range = {
12989                                let display_point = buffer
12990                                    .offset_to_point(old_range.end)
12991                                    .to_display_point(&display_map);
12992                                let Range { start, end } =
12993                                    movement::surrounding_word(&display_map, display_point);
12994                                start.to_point(&display_map).to_offset(&buffer)
12995                                    ..end.to_point(&display_map).to_offset(&buffer)
12996                            };
12997                            // only select word if start and end point belongs to same word
12998                            if word_range == last_word_range {
12999                                selected_larger_node = true;
13000                                return Selection {
13001                                    id: selection.id,
13002                                    start: word_range.start,
13003                                    end: word_range.end,
13004                                    goal: SelectionGoal::None,
13005                                    reversed: selection.reversed,
13006                                };
13007                            }
13008                        }
13009                    }
13010                }
13011
13012                let mut new_range = old_range.clone();
13013                while let Some((_node, containing_range)) =
13014                    buffer.syntax_ancestor(new_range.clone())
13015                {
13016                    new_range = match containing_range {
13017                        MultiOrSingleBufferOffsetRange::Single(_) => break,
13018                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
13019                    };
13020                    if !display_map.intersects_fold(new_range.start)
13021                        && !display_map.intersects_fold(new_range.end)
13022                    {
13023                        break;
13024                    }
13025                }
13026
13027                selected_larger_node |= new_range != old_range;
13028                Selection {
13029                    id: selection.id,
13030                    start: new_range.start,
13031                    end: new_range.end,
13032                    goal: SelectionGoal::None,
13033                    reversed: selection.reversed,
13034                }
13035            })
13036            .collect::<Vec<_>>();
13037
13038        if !selected_larger_node {
13039            return; // don't put this call in the history
13040        }
13041
13042        // scroll based on transformation done to the last selection created by the user
13043        let (last_old, last_new) = old_selections
13044            .last()
13045            .zip(new_selections.last().cloned())
13046            .expect("old_selections isn't empty");
13047
13048        // revert selection
13049        let is_selection_reversed = {
13050            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13051            new_selections.last_mut().expect("checked above").reversed =
13052                should_newest_selection_be_reversed;
13053            should_newest_selection_be_reversed
13054        };
13055
13056        if selected_larger_node {
13057            self.select_syntax_node_history.disable_clearing = true;
13058            self.change_selections(None, window, cx, |s| {
13059                s.select(new_selections.clone());
13060            });
13061            self.select_syntax_node_history.disable_clearing = false;
13062        }
13063
13064        let start_row = last_new.start.to_display_point(&display_map).row().0;
13065        let end_row = last_new.end.to_display_point(&display_map).row().0;
13066        let selection_height = end_row - start_row + 1;
13067        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13068
13069        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13070        let scroll_behavior = if fits_on_the_screen {
13071            self.request_autoscroll(Autoscroll::fit(), cx);
13072            SelectSyntaxNodeScrollBehavior::FitSelection
13073        } else if is_selection_reversed {
13074            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13075            SelectSyntaxNodeScrollBehavior::CursorTop
13076        } else {
13077            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13078            SelectSyntaxNodeScrollBehavior::CursorBottom
13079        };
13080
13081        self.select_syntax_node_history.push((
13082            old_selections,
13083            scroll_behavior,
13084            is_selection_reversed,
13085        ));
13086    }
13087
13088    pub fn select_smaller_syntax_node(
13089        &mut self,
13090        _: &SelectSmallerSyntaxNode,
13091        window: &mut Window,
13092        cx: &mut Context<Self>,
13093    ) {
13094        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13095
13096        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13097            self.select_syntax_node_history.pop()
13098        {
13099            if let Some(selection) = selections.last_mut() {
13100                selection.reversed = is_selection_reversed;
13101            }
13102
13103            self.select_syntax_node_history.disable_clearing = true;
13104            self.change_selections(None, window, cx, |s| {
13105                s.select(selections.to_vec());
13106            });
13107            self.select_syntax_node_history.disable_clearing = false;
13108
13109            match scroll_behavior {
13110                SelectSyntaxNodeScrollBehavior::CursorTop => {
13111                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13112                }
13113                SelectSyntaxNodeScrollBehavior::FitSelection => {
13114                    self.request_autoscroll(Autoscroll::fit(), cx);
13115                }
13116                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13117                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13118                }
13119            }
13120        }
13121    }
13122
13123    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13124        if !EditorSettings::get_global(cx).gutter.runnables {
13125            self.clear_tasks();
13126            return Task::ready(());
13127        }
13128        let project = self.project.as_ref().map(Entity::downgrade);
13129        let task_sources = self.lsp_task_sources(cx);
13130        cx.spawn_in(window, async move |editor, cx| {
13131            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13132            let Some(project) = project.and_then(|p| p.upgrade()) else {
13133                return;
13134            };
13135            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13136                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13137            }) else {
13138                return;
13139            };
13140
13141            let hide_runnables = project
13142                .update(cx, |project, cx| {
13143                    // Do not display any test indicators in non-dev server remote projects.
13144                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13145                })
13146                .unwrap_or(true);
13147            if hide_runnables {
13148                return;
13149            }
13150            let new_rows =
13151                cx.background_spawn({
13152                    let snapshot = display_snapshot.clone();
13153                    async move {
13154                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13155                    }
13156                })
13157                    .await;
13158            let Ok(lsp_tasks) =
13159                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13160            else {
13161                return;
13162            };
13163            let lsp_tasks = lsp_tasks.await;
13164
13165            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13166                lsp_tasks
13167                    .into_iter()
13168                    .flat_map(|(kind, tasks)| {
13169                        tasks.into_iter().filter_map(move |(location, task)| {
13170                            Some((kind.clone(), location?, task))
13171                        })
13172                    })
13173                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13174                        let buffer = location.target.buffer;
13175                        let buffer_snapshot = buffer.read(cx).snapshot();
13176                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13177                            |(excerpt_id, snapshot, _)| {
13178                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13179                                    display_snapshot
13180                                        .buffer_snapshot
13181                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13182                                } else {
13183                                    None
13184                                }
13185                            },
13186                        );
13187                        if let Some(offset) = offset {
13188                            let task_buffer_range =
13189                                location.target.range.to_point(&buffer_snapshot);
13190                            let context_buffer_range =
13191                                task_buffer_range.to_offset(&buffer_snapshot);
13192                            let context_range = BufferOffset(context_buffer_range.start)
13193                                ..BufferOffset(context_buffer_range.end);
13194
13195                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13196                                .or_insert_with(|| RunnableTasks {
13197                                    templates: Vec::new(),
13198                                    offset,
13199                                    column: task_buffer_range.start.column,
13200                                    extra_variables: HashMap::default(),
13201                                    context_range,
13202                                })
13203                                .templates
13204                                .push((kind, task.original_task().clone()));
13205                        }
13206
13207                        acc
13208                    })
13209            }) else {
13210                return;
13211            };
13212
13213            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13214            editor
13215                .update(cx, |editor, _| {
13216                    editor.clear_tasks();
13217                    for (key, mut value) in rows {
13218                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13219                            value.templates.extend(lsp_tasks.templates);
13220                        }
13221
13222                        editor.insert_tasks(key, value);
13223                    }
13224                    for (key, value) in lsp_tasks_by_rows {
13225                        editor.insert_tasks(key, value);
13226                    }
13227                })
13228                .ok();
13229        })
13230    }
13231    fn fetch_runnable_ranges(
13232        snapshot: &DisplaySnapshot,
13233        range: Range<Anchor>,
13234    ) -> Vec<language::RunnableRange> {
13235        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13236    }
13237
13238    fn runnable_rows(
13239        project: Entity<Project>,
13240        snapshot: DisplaySnapshot,
13241        runnable_ranges: Vec<RunnableRange>,
13242        mut cx: AsyncWindowContext,
13243    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13244        runnable_ranges
13245            .into_iter()
13246            .filter_map(|mut runnable| {
13247                let tasks = cx
13248                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13249                    .ok()?;
13250                if tasks.is_empty() {
13251                    return None;
13252                }
13253
13254                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13255
13256                let row = snapshot
13257                    .buffer_snapshot
13258                    .buffer_line_for_row(MultiBufferRow(point.row))?
13259                    .1
13260                    .start
13261                    .row;
13262
13263                let context_range =
13264                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13265                Some((
13266                    (runnable.buffer_id, row),
13267                    RunnableTasks {
13268                        templates: tasks,
13269                        offset: snapshot
13270                            .buffer_snapshot
13271                            .anchor_before(runnable.run_range.start),
13272                        context_range,
13273                        column: point.column,
13274                        extra_variables: runnable.extra_captures,
13275                    },
13276                ))
13277            })
13278            .collect()
13279    }
13280
13281    fn templates_with_tags(
13282        project: &Entity<Project>,
13283        runnable: &mut Runnable,
13284        cx: &mut App,
13285    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13286        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13287            let (worktree_id, file) = project
13288                .buffer_for_id(runnable.buffer, cx)
13289                .and_then(|buffer| buffer.read(cx).file())
13290                .map(|file| (file.worktree_id(cx), file.clone()))
13291                .unzip();
13292
13293            (
13294                project.task_store().read(cx).task_inventory().cloned(),
13295                worktree_id,
13296                file,
13297            )
13298        });
13299
13300        let mut templates_with_tags = mem::take(&mut runnable.tags)
13301            .into_iter()
13302            .flat_map(|RunnableTag(tag)| {
13303                inventory
13304                    .as_ref()
13305                    .into_iter()
13306                    .flat_map(|inventory| {
13307                        inventory.read(cx).list_tasks(
13308                            file.clone(),
13309                            Some(runnable.language.clone()),
13310                            worktree_id,
13311                            cx,
13312                        )
13313                    })
13314                    .filter(move |(_, template)| {
13315                        template.tags.iter().any(|source_tag| source_tag == &tag)
13316                    })
13317            })
13318            .sorted_by_key(|(kind, _)| kind.to_owned())
13319            .collect::<Vec<_>>();
13320        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13321            // Strongest source wins; if we have worktree tag binding, prefer that to
13322            // global and language bindings;
13323            // if we have a global binding, prefer that to language binding.
13324            let first_mismatch = templates_with_tags
13325                .iter()
13326                .position(|(tag_source, _)| tag_source != leading_tag_source);
13327            if let Some(index) = first_mismatch {
13328                templates_with_tags.truncate(index);
13329            }
13330        }
13331
13332        templates_with_tags
13333    }
13334
13335    pub fn move_to_enclosing_bracket(
13336        &mut self,
13337        _: &MoveToEnclosingBracket,
13338        window: &mut Window,
13339        cx: &mut Context<Self>,
13340    ) {
13341        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13342        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13343            s.move_offsets_with(|snapshot, selection| {
13344                let Some(enclosing_bracket_ranges) =
13345                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13346                else {
13347                    return;
13348                };
13349
13350                let mut best_length = usize::MAX;
13351                let mut best_inside = false;
13352                let mut best_in_bracket_range = false;
13353                let mut best_destination = None;
13354                for (open, close) in enclosing_bracket_ranges {
13355                    let close = close.to_inclusive();
13356                    let length = close.end() - open.start;
13357                    let inside = selection.start >= open.end && selection.end <= *close.start();
13358                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13359                        || close.contains(&selection.head());
13360
13361                    // If best is next to a bracket and current isn't, skip
13362                    if !in_bracket_range && best_in_bracket_range {
13363                        continue;
13364                    }
13365
13366                    // Prefer smaller lengths unless best is inside and current isn't
13367                    if length > best_length && (best_inside || !inside) {
13368                        continue;
13369                    }
13370
13371                    best_length = length;
13372                    best_inside = inside;
13373                    best_in_bracket_range = in_bracket_range;
13374                    best_destination = Some(
13375                        if close.contains(&selection.start) && close.contains(&selection.end) {
13376                            if inside { open.end } else { open.start }
13377                        } else if inside {
13378                            *close.start()
13379                        } else {
13380                            *close.end()
13381                        },
13382                    );
13383                }
13384
13385                if let Some(destination) = best_destination {
13386                    selection.collapse_to(destination, SelectionGoal::None);
13387                }
13388            })
13389        });
13390    }
13391
13392    pub fn undo_selection(
13393        &mut self,
13394        _: &UndoSelection,
13395        window: &mut Window,
13396        cx: &mut Context<Self>,
13397    ) {
13398        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13399        self.end_selection(window, cx);
13400        self.selection_history.mode = SelectionHistoryMode::Undoing;
13401        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13402            self.change_selections(None, window, cx, |s| {
13403                s.select_anchors(entry.selections.to_vec())
13404            });
13405            self.select_next_state = entry.select_next_state;
13406            self.select_prev_state = entry.select_prev_state;
13407            self.add_selections_state = entry.add_selections_state;
13408            self.request_autoscroll(Autoscroll::newest(), cx);
13409        }
13410        self.selection_history.mode = SelectionHistoryMode::Normal;
13411    }
13412
13413    pub fn redo_selection(
13414        &mut self,
13415        _: &RedoSelection,
13416        window: &mut Window,
13417        cx: &mut Context<Self>,
13418    ) {
13419        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13420        self.end_selection(window, cx);
13421        self.selection_history.mode = SelectionHistoryMode::Redoing;
13422        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13423            self.change_selections(None, window, cx, |s| {
13424                s.select_anchors(entry.selections.to_vec())
13425            });
13426            self.select_next_state = entry.select_next_state;
13427            self.select_prev_state = entry.select_prev_state;
13428            self.add_selections_state = entry.add_selections_state;
13429            self.request_autoscroll(Autoscroll::newest(), cx);
13430        }
13431        self.selection_history.mode = SelectionHistoryMode::Normal;
13432    }
13433
13434    pub fn expand_excerpts(
13435        &mut self,
13436        action: &ExpandExcerpts,
13437        _: &mut Window,
13438        cx: &mut Context<Self>,
13439    ) {
13440        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13441    }
13442
13443    pub fn expand_excerpts_down(
13444        &mut self,
13445        action: &ExpandExcerptsDown,
13446        _: &mut Window,
13447        cx: &mut Context<Self>,
13448    ) {
13449        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13450    }
13451
13452    pub fn expand_excerpts_up(
13453        &mut self,
13454        action: &ExpandExcerptsUp,
13455        _: &mut Window,
13456        cx: &mut Context<Self>,
13457    ) {
13458        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13459    }
13460
13461    pub fn expand_excerpts_for_direction(
13462        &mut self,
13463        lines: u32,
13464        direction: ExpandExcerptDirection,
13465
13466        cx: &mut Context<Self>,
13467    ) {
13468        let selections = self.selections.disjoint_anchors();
13469
13470        let lines = if lines == 0 {
13471            EditorSettings::get_global(cx).expand_excerpt_lines
13472        } else {
13473            lines
13474        };
13475
13476        self.buffer.update(cx, |buffer, cx| {
13477            let snapshot = buffer.snapshot(cx);
13478            let mut excerpt_ids = selections
13479                .iter()
13480                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13481                .collect::<Vec<_>>();
13482            excerpt_ids.sort();
13483            excerpt_ids.dedup();
13484            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13485        })
13486    }
13487
13488    pub fn expand_excerpt(
13489        &mut self,
13490        excerpt: ExcerptId,
13491        direction: ExpandExcerptDirection,
13492        window: &mut Window,
13493        cx: &mut Context<Self>,
13494    ) {
13495        let current_scroll_position = self.scroll_position(cx);
13496        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13497        let mut should_scroll_up = false;
13498
13499        if direction == ExpandExcerptDirection::Down {
13500            let multi_buffer = self.buffer.read(cx);
13501            let snapshot = multi_buffer.snapshot(cx);
13502            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13503                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13504                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13505                        let buffer_snapshot = buffer.read(cx).snapshot();
13506                        let excerpt_end_row =
13507                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13508                        let last_row = buffer_snapshot.max_point().row;
13509                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13510                        should_scroll_up = lines_below >= lines_to_expand;
13511                    }
13512                }
13513            }
13514        }
13515
13516        self.buffer.update(cx, |buffer, cx| {
13517            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13518        });
13519
13520        if should_scroll_up {
13521            let new_scroll_position =
13522                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13523            self.set_scroll_position(new_scroll_position, window, cx);
13524        }
13525    }
13526
13527    pub fn go_to_singleton_buffer_point(
13528        &mut self,
13529        point: Point,
13530        window: &mut Window,
13531        cx: &mut Context<Self>,
13532    ) {
13533        self.go_to_singleton_buffer_range(point..point, window, cx);
13534    }
13535
13536    pub fn go_to_singleton_buffer_range(
13537        &mut self,
13538        range: Range<Point>,
13539        window: &mut Window,
13540        cx: &mut Context<Self>,
13541    ) {
13542        let multibuffer = self.buffer().read(cx);
13543        let Some(buffer) = multibuffer.as_singleton() else {
13544            return;
13545        };
13546        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13547            return;
13548        };
13549        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13550            return;
13551        };
13552        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13553            s.select_anchor_ranges([start..end])
13554        });
13555    }
13556
13557    pub fn go_to_diagnostic(
13558        &mut self,
13559        _: &GoToDiagnostic,
13560        window: &mut Window,
13561        cx: &mut Context<Self>,
13562    ) {
13563        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13564        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13565    }
13566
13567    pub fn go_to_prev_diagnostic(
13568        &mut self,
13569        _: &GoToPreviousDiagnostic,
13570        window: &mut Window,
13571        cx: &mut Context<Self>,
13572    ) {
13573        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13574        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13575    }
13576
13577    pub fn go_to_diagnostic_impl(
13578        &mut self,
13579        direction: Direction,
13580        window: &mut Window,
13581        cx: &mut Context<Self>,
13582    ) {
13583        let buffer = self.buffer.read(cx).snapshot(cx);
13584        let selection = self.selections.newest::<usize>(cx);
13585
13586        let mut active_group_id = None;
13587        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13588            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13589                active_group_id = Some(active_group.group_id);
13590            }
13591        }
13592
13593        fn filtered(
13594            snapshot: EditorSnapshot,
13595            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13596        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13597            diagnostics
13598                .filter(|entry| entry.range.start != entry.range.end)
13599                .filter(|entry| !entry.diagnostic.is_unnecessary)
13600                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13601        }
13602
13603        let snapshot = self.snapshot(window, cx);
13604        let before = filtered(
13605            snapshot.clone(),
13606            buffer
13607                .diagnostics_in_range(0..selection.start)
13608                .filter(|entry| entry.range.start <= selection.start),
13609        );
13610        let after = filtered(
13611            snapshot,
13612            buffer
13613                .diagnostics_in_range(selection.start..buffer.len())
13614                .filter(|entry| entry.range.start >= selection.start),
13615        );
13616
13617        let mut found: Option<DiagnosticEntry<usize>> = None;
13618        if direction == Direction::Prev {
13619            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13620            {
13621                for diagnostic in prev_diagnostics.into_iter().rev() {
13622                    if diagnostic.range.start != selection.start
13623                        || active_group_id
13624                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13625                    {
13626                        found = Some(diagnostic);
13627                        break 'outer;
13628                    }
13629                }
13630            }
13631        } else {
13632            for diagnostic in after.chain(before) {
13633                if diagnostic.range.start != selection.start
13634                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13635                {
13636                    found = Some(diagnostic);
13637                    break;
13638                }
13639            }
13640        }
13641        let Some(next_diagnostic) = found else {
13642            return;
13643        };
13644
13645        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13646            return;
13647        };
13648        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13649            s.select_ranges(vec![
13650                next_diagnostic.range.start..next_diagnostic.range.start,
13651            ])
13652        });
13653        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13654        self.refresh_inline_completion(false, true, window, cx);
13655    }
13656
13657    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13658        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13659        let snapshot = self.snapshot(window, cx);
13660        let selection = self.selections.newest::<Point>(cx);
13661        self.go_to_hunk_before_or_after_position(
13662            &snapshot,
13663            selection.head(),
13664            Direction::Next,
13665            window,
13666            cx,
13667        );
13668    }
13669
13670    pub fn go_to_hunk_before_or_after_position(
13671        &mut self,
13672        snapshot: &EditorSnapshot,
13673        position: Point,
13674        direction: Direction,
13675        window: &mut Window,
13676        cx: &mut Context<Editor>,
13677    ) {
13678        let row = if direction == Direction::Next {
13679            self.hunk_after_position(snapshot, position)
13680                .map(|hunk| hunk.row_range.start)
13681        } else {
13682            self.hunk_before_position(snapshot, position)
13683        };
13684
13685        if let Some(row) = row {
13686            let destination = Point::new(row.0, 0);
13687            let autoscroll = Autoscroll::center();
13688
13689            self.unfold_ranges(&[destination..destination], false, false, cx);
13690            self.change_selections(Some(autoscroll), window, cx, |s| {
13691                s.select_ranges([destination..destination]);
13692            });
13693        }
13694    }
13695
13696    fn hunk_after_position(
13697        &mut self,
13698        snapshot: &EditorSnapshot,
13699        position: Point,
13700    ) -> Option<MultiBufferDiffHunk> {
13701        snapshot
13702            .buffer_snapshot
13703            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13704            .find(|hunk| hunk.row_range.start.0 > position.row)
13705            .or_else(|| {
13706                snapshot
13707                    .buffer_snapshot
13708                    .diff_hunks_in_range(Point::zero()..position)
13709                    .find(|hunk| hunk.row_range.end.0 < position.row)
13710            })
13711    }
13712
13713    fn go_to_prev_hunk(
13714        &mut self,
13715        _: &GoToPreviousHunk,
13716        window: &mut Window,
13717        cx: &mut Context<Self>,
13718    ) {
13719        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13720        let snapshot = self.snapshot(window, cx);
13721        let selection = self.selections.newest::<Point>(cx);
13722        self.go_to_hunk_before_or_after_position(
13723            &snapshot,
13724            selection.head(),
13725            Direction::Prev,
13726            window,
13727            cx,
13728        );
13729    }
13730
13731    fn hunk_before_position(
13732        &mut self,
13733        snapshot: &EditorSnapshot,
13734        position: Point,
13735    ) -> Option<MultiBufferRow> {
13736        snapshot
13737            .buffer_snapshot
13738            .diff_hunk_before(position)
13739            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13740    }
13741
13742    fn go_to_next_change(
13743        &mut self,
13744        _: &GoToNextChange,
13745        window: &mut Window,
13746        cx: &mut Context<Self>,
13747    ) {
13748        if let Some(selections) = self
13749            .change_list
13750            .next_change(1, Direction::Next)
13751            .map(|s| s.to_vec())
13752        {
13753            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13754                let map = s.display_map();
13755                s.select_display_ranges(selections.iter().map(|a| {
13756                    let point = a.to_display_point(&map);
13757                    point..point
13758                }))
13759            })
13760        }
13761    }
13762
13763    fn go_to_previous_change(
13764        &mut self,
13765        _: &GoToPreviousChange,
13766        window: &mut Window,
13767        cx: &mut Context<Self>,
13768    ) {
13769        if let Some(selections) = self
13770            .change_list
13771            .next_change(1, Direction::Prev)
13772            .map(|s| s.to_vec())
13773        {
13774            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13775                let map = s.display_map();
13776                s.select_display_ranges(selections.iter().map(|a| {
13777                    let point = a.to_display_point(&map);
13778                    point..point
13779                }))
13780            })
13781        }
13782    }
13783
13784    fn go_to_line<T: 'static>(
13785        &mut self,
13786        position: Anchor,
13787        highlight_color: Option<Hsla>,
13788        window: &mut Window,
13789        cx: &mut Context<Self>,
13790    ) {
13791        let snapshot = self.snapshot(window, cx).display_snapshot;
13792        let position = position.to_point(&snapshot.buffer_snapshot);
13793        let start = snapshot
13794            .buffer_snapshot
13795            .clip_point(Point::new(position.row, 0), Bias::Left);
13796        let end = start + Point::new(1, 0);
13797        let start = snapshot.buffer_snapshot.anchor_before(start);
13798        let end = snapshot.buffer_snapshot.anchor_before(end);
13799
13800        self.highlight_rows::<T>(
13801            start..end,
13802            highlight_color
13803                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13804            Default::default(),
13805            cx,
13806        );
13807        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13808    }
13809
13810    pub fn go_to_definition(
13811        &mut self,
13812        _: &GoToDefinition,
13813        window: &mut Window,
13814        cx: &mut Context<Self>,
13815    ) -> Task<Result<Navigated>> {
13816        let definition =
13817            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13818        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13819        cx.spawn_in(window, async move |editor, cx| {
13820            if definition.await? == Navigated::Yes {
13821                return Ok(Navigated::Yes);
13822            }
13823            match fallback_strategy {
13824                GoToDefinitionFallback::None => Ok(Navigated::No),
13825                GoToDefinitionFallback::FindAllReferences => {
13826                    match editor.update_in(cx, |editor, window, cx| {
13827                        editor.find_all_references(&FindAllReferences, window, cx)
13828                    })? {
13829                        Some(references) => references.await,
13830                        None => Ok(Navigated::No),
13831                    }
13832                }
13833            }
13834        })
13835    }
13836
13837    pub fn go_to_declaration(
13838        &mut self,
13839        _: &GoToDeclaration,
13840        window: &mut Window,
13841        cx: &mut Context<Self>,
13842    ) -> Task<Result<Navigated>> {
13843        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13844    }
13845
13846    pub fn go_to_declaration_split(
13847        &mut self,
13848        _: &GoToDeclaration,
13849        window: &mut Window,
13850        cx: &mut Context<Self>,
13851    ) -> Task<Result<Navigated>> {
13852        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13853    }
13854
13855    pub fn go_to_implementation(
13856        &mut self,
13857        _: &GoToImplementation,
13858        window: &mut Window,
13859        cx: &mut Context<Self>,
13860    ) -> Task<Result<Navigated>> {
13861        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13862    }
13863
13864    pub fn go_to_implementation_split(
13865        &mut self,
13866        _: &GoToImplementationSplit,
13867        window: &mut Window,
13868        cx: &mut Context<Self>,
13869    ) -> Task<Result<Navigated>> {
13870        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13871    }
13872
13873    pub fn go_to_type_definition(
13874        &mut self,
13875        _: &GoToTypeDefinition,
13876        window: &mut Window,
13877        cx: &mut Context<Self>,
13878    ) -> Task<Result<Navigated>> {
13879        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13880    }
13881
13882    pub fn go_to_definition_split(
13883        &mut self,
13884        _: &GoToDefinitionSplit,
13885        window: &mut Window,
13886        cx: &mut Context<Self>,
13887    ) -> Task<Result<Navigated>> {
13888        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13889    }
13890
13891    pub fn go_to_type_definition_split(
13892        &mut self,
13893        _: &GoToTypeDefinitionSplit,
13894        window: &mut Window,
13895        cx: &mut Context<Self>,
13896    ) -> Task<Result<Navigated>> {
13897        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13898    }
13899
13900    fn go_to_definition_of_kind(
13901        &mut self,
13902        kind: GotoDefinitionKind,
13903        split: bool,
13904        window: &mut Window,
13905        cx: &mut Context<Self>,
13906    ) -> Task<Result<Navigated>> {
13907        let Some(provider) = self.semantics_provider.clone() else {
13908            return Task::ready(Ok(Navigated::No));
13909        };
13910        let head = self.selections.newest::<usize>(cx).head();
13911        let buffer = self.buffer.read(cx);
13912        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13913            text_anchor
13914        } else {
13915            return Task::ready(Ok(Navigated::No));
13916        };
13917
13918        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13919            return Task::ready(Ok(Navigated::No));
13920        };
13921
13922        cx.spawn_in(window, async move |editor, cx| {
13923            let definitions = definitions.await?;
13924            let navigated = editor
13925                .update_in(cx, |editor, window, cx| {
13926                    editor.navigate_to_hover_links(
13927                        Some(kind),
13928                        definitions
13929                            .into_iter()
13930                            .filter(|location| {
13931                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13932                            })
13933                            .map(HoverLink::Text)
13934                            .collect::<Vec<_>>(),
13935                        split,
13936                        window,
13937                        cx,
13938                    )
13939                })?
13940                .await?;
13941            anyhow::Ok(navigated)
13942        })
13943    }
13944
13945    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13946        let selection = self.selections.newest_anchor();
13947        let head = selection.head();
13948        let tail = selection.tail();
13949
13950        let Some((buffer, start_position)) =
13951            self.buffer.read(cx).text_anchor_for_position(head, cx)
13952        else {
13953            return;
13954        };
13955
13956        let end_position = if head != tail {
13957            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13958                return;
13959            };
13960            Some(pos)
13961        } else {
13962            None
13963        };
13964
13965        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13966            let url = if let Some(end_pos) = end_position {
13967                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13968            } else {
13969                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13970            };
13971
13972            if let Some(url) = url {
13973                editor.update(cx, |_, cx| {
13974                    cx.open_url(&url);
13975                })
13976            } else {
13977                Ok(())
13978            }
13979        });
13980
13981        url_finder.detach();
13982    }
13983
13984    pub fn open_selected_filename(
13985        &mut self,
13986        _: &OpenSelectedFilename,
13987        window: &mut Window,
13988        cx: &mut Context<Self>,
13989    ) {
13990        let Some(workspace) = self.workspace() else {
13991            return;
13992        };
13993
13994        let position = self.selections.newest_anchor().head();
13995
13996        let Some((buffer, buffer_position)) =
13997            self.buffer.read(cx).text_anchor_for_position(position, cx)
13998        else {
13999            return;
14000        };
14001
14002        let project = self.project.clone();
14003
14004        cx.spawn_in(window, async move |_, cx| {
14005            let result = find_file(&buffer, project, buffer_position, cx).await;
14006
14007            if let Some((_, path)) = result {
14008                workspace
14009                    .update_in(cx, |workspace, window, cx| {
14010                        workspace.open_resolved_path(path, window, cx)
14011                    })?
14012                    .await?;
14013            }
14014            anyhow::Ok(())
14015        })
14016        .detach();
14017    }
14018
14019    pub(crate) fn navigate_to_hover_links(
14020        &mut self,
14021        kind: Option<GotoDefinitionKind>,
14022        mut definitions: Vec<HoverLink>,
14023        split: bool,
14024        window: &mut Window,
14025        cx: &mut Context<Editor>,
14026    ) -> Task<Result<Navigated>> {
14027        // If there is one definition, just open it directly
14028        if definitions.len() == 1 {
14029            let definition = definitions.pop().unwrap();
14030
14031            enum TargetTaskResult {
14032                Location(Option<Location>),
14033                AlreadyNavigated,
14034            }
14035
14036            let target_task = match definition {
14037                HoverLink::Text(link) => {
14038                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14039                }
14040                HoverLink::InlayHint(lsp_location, server_id) => {
14041                    let computation =
14042                        self.compute_target_location(lsp_location, server_id, window, cx);
14043                    cx.background_spawn(async move {
14044                        let location = computation.await?;
14045                        Ok(TargetTaskResult::Location(location))
14046                    })
14047                }
14048                HoverLink::Url(url) => {
14049                    cx.open_url(&url);
14050                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14051                }
14052                HoverLink::File(path) => {
14053                    if let Some(workspace) = self.workspace() {
14054                        cx.spawn_in(window, async move |_, cx| {
14055                            workspace
14056                                .update_in(cx, |workspace, window, cx| {
14057                                    workspace.open_resolved_path(path, window, cx)
14058                                })?
14059                                .await
14060                                .map(|_| TargetTaskResult::AlreadyNavigated)
14061                        })
14062                    } else {
14063                        Task::ready(Ok(TargetTaskResult::Location(None)))
14064                    }
14065                }
14066            };
14067            cx.spawn_in(window, async move |editor, cx| {
14068                let target = match target_task.await.context("target resolution task")? {
14069                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14070                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14071                    TargetTaskResult::Location(Some(target)) => target,
14072                };
14073
14074                editor.update_in(cx, |editor, window, cx| {
14075                    let Some(workspace) = editor.workspace() else {
14076                        return Navigated::No;
14077                    };
14078                    let pane = workspace.read(cx).active_pane().clone();
14079
14080                    let range = target.range.to_point(target.buffer.read(cx));
14081                    let range = editor.range_for_match(&range);
14082                    let range = collapse_multiline_range(range);
14083
14084                    if !split
14085                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14086                    {
14087                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14088                    } else {
14089                        window.defer(cx, move |window, cx| {
14090                            let target_editor: Entity<Self> =
14091                                workspace.update(cx, |workspace, cx| {
14092                                    let pane = if split {
14093                                        workspace.adjacent_pane(window, cx)
14094                                    } else {
14095                                        workspace.active_pane().clone()
14096                                    };
14097
14098                                    workspace.open_project_item(
14099                                        pane,
14100                                        target.buffer.clone(),
14101                                        true,
14102                                        true,
14103                                        window,
14104                                        cx,
14105                                    )
14106                                });
14107                            target_editor.update(cx, |target_editor, cx| {
14108                                // When selecting a definition in a different buffer, disable the nav history
14109                                // to avoid creating a history entry at the previous cursor location.
14110                                pane.update(cx, |pane, _| pane.disable_history());
14111                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14112                                pane.update(cx, |pane, _| pane.enable_history());
14113                            });
14114                        });
14115                    }
14116                    Navigated::Yes
14117                })
14118            })
14119        } else if !definitions.is_empty() {
14120            cx.spawn_in(window, async move |editor, cx| {
14121                let (title, location_tasks, workspace) = editor
14122                    .update_in(cx, |editor, window, cx| {
14123                        let tab_kind = match kind {
14124                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14125                            _ => "Definitions",
14126                        };
14127                        let title = definitions
14128                            .iter()
14129                            .find_map(|definition| match definition {
14130                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14131                                    let buffer = origin.buffer.read(cx);
14132                                    format!(
14133                                        "{} for {}",
14134                                        tab_kind,
14135                                        buffer
14136                                            .text_for_range(origin.range.clone())
14137                                            .collect::<String>()
14138                                    )
14139                                }),
14140                                HoverLink::InlayHint(_, _) => None,
14141                                HoverLink::Url(_) => None,
14142                                HoverLink::File(_) => None,
14143                            })
14144                            .unwrap_or(tab_kind.to_string());
14145                        let location_tasks = definitions
14146                            .into_iter()
14147                            .map(|definition| match definition {
14148                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14149                                HoverLink::InlayHint(lsp_location, server_id) => editor
14150                                    .compute_target_location(lsp_location, server_id, window, cx),
14151                                HoverLink::Url(_) => Task::ready(Ok(None)),
14152                                HoverLink::File(_) => Task::ready(Ok(None)),
14153                            })
14154                            .collect::<Vec<_>>();
14155                        (title, location_tasks, editor.workspace().clone())
14156                    })
14157                    .context("location tasks preparation")?;
14158
14159                let locations = future::join_all(location_tasks)
14160                    .await
14161                    .into_iter()
14162                    .filter_map(|location| location.transpose())
14163                    .collect::<Result<_>>()
14164                    .context("location tasks")?;
14165
14166                let Some(workspace) = workspace else {
14167                    return Ok(Navigated::No);
14168                };
14169                let opened = workspace
14170                    .update_in(cx, |workspace, window, cx| {
14171                        Self::open_locations_in_multibuffer(
14172                            workspace,
14173                            locations,
14174                            title,
14175                            split,
14176                            MultibufferSelectionMode::First,
14177                            window,
14178                            cx,
14179                        )
14180                    })
14181                    .ok();
14182
14183                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14184            })
14185        } else {
14186            Task::ready(Ok(Navigated::No))
14187        }
14188    }
14189
14190    fn compute_target_location(
14191        &self,
14192        lsp_location: lsp::Location,
14193        server_id: LanguageServerId,
14194        window: &mut Window,
14195        cx: &mut Context<Self>,
14196    ) -> Task<anyhow::Result<Option<Location>>> {
14197        let Some(project) = self.project.clone() else {
14198            return Task::ready(Ok(None));
14199        };
14200
14201        cx.spawn_in(window, async move |editor, cx| {
14202            let location_task = editor.update(cx, |_, cx| {
14203                project.update(cx, |project, cx| {
14204                    let language_server_name = project
14205                        .language_server_statuses(cx)
14206                        .find(|(id, _)| server_id == *id)
14207                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14208                    language_server_name.map(|language_server_name| {
14209                        project.open_local_buffer_via_lsp(
14210                            lsp_location.uri.clone(),
14211                            server_id,
14212                            language_server_name,
14213                            cx,
14214                        )
14215                    })
14216                })
14217            })?;
14218            let location = match location_task {
14219                Some(task) => Some({
14220                    let target_buffer_handle = task.await.context("open local buffer")?;
14221                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14222                        let target_start = target_buffer
14223                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14224                        let target_end = target_buffer
14225                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14226                        target_buffer.anchor_after(target_start)
14227                            ..target_buffer.anchor_before(target_end)
14228                    })?;
14229                    Location {
14230                        buffer: target_buffer_handle,
14231                        range,
14232                    }
14233                }),
14234                None => None,
14235            };
14236            Ok(location)
14237        })
14238    }
14239
14240    pub fn find_all_references(
14241        &mut self,
14242        _: &FindAllReferences,
14243        window: &mut Window,
14244        cx: &mut Context<Self>,
14245    ) -> Option<Task<Result<Navigated>>> {
14246        let selection = self.selections.newest::<usize>(cx);
14247        let multi_buffer = self.buffer.read(cx);
14248        let head = selection.head();
14249
14250        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14251        let head_anchor = multi_buffer_snapshot.anchor_at(
14252            head,
14253            if head < selection.tail() {
14254                Bias::Right
14255            } else {
14256                Bias::Left
14257            },
14258        );
14259
14260        match self
14261            .find_all_references_task_sources
14262            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14263        {
14264            Ok(_) => {
14265                log::info!(
14266                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14267                );
14268                return None;
14269            }
14270            Err(i) => {
14271                self.find_all_references_task_sources.insert(i, head_anchor);
14272            }
14273        }
14274
14275        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14276        let workspace = self.workspace()?;
14277        let project = workspace.read(cx).project().clone();
14278        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14279        Some(cx.spawn_in(window, async move |editor, cx| {
14280            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14281                if let Ok(i) = editor
14282                    .find_all_references_task_sources
14283                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14284                {
14285                    editor.find_all_references_task_sources.remove(i);
14286                }
14287            });
14288
14289            let locations = references.await?;
14290            if locations.is_empty() {
14291                return anyhow::Ok(Navigated::No);
14292            }
14293
14294            workspace.update_in(cx, |workspace, window, cx| {
14295                let title = locations
14296                    .first()
14297                    .as_ref()
14298                    .map(|location| {
14299                        let buffer = location.buffer.read(cx);
14300                        format!(
14301                            "References to `{}`",
14302                            buffer
14303                                .text_for_range(location.range.clone())
14304                                .collect::<String>()
14305                        )
14306                    })
14307                    .unwrap();
14308                Self::open_locations_in_multibuffer(
14309                    workspace,
14310                    locations,
14311                    title,
14312                    false,
14313                    MultibufferSelectionMode::First,
14314                    window,
14315                    cx,
14316                );
14317                Navigated::Yes
14318            })
14319        }))
14320    }
14321
14322    /// Opens a multibuffer with the given project locations in it
14323    pub fn open_locations_in_multibuffer(
14324        workspace: &mut Workspace,
14325        mut locations: Vec<Location>,
14326        title: String,
14327        split: bool,
14328        multibuffer_selection_mode: MultibufferSelectionMode,
14329        window: &mut Window,
14330        cx: &mut Context<Workspace>,
14331    ) {
14332        // If there are multiple definitions, open them in a multibuffer
14333        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14334        let mut locations = locations.into_iter().peekable();
14335        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14336        let capability = workspace.project().read(cx).capability();
14337
14338        let excerpt_buffer = cx.new(|cx| {
14339            let mut multibuffer = MultiBuffer::new(capability);
14340            while let Some(location) = locations.next() {
14341                let buffer = location.buffer.read(cx);
14342                let mut ranges_for_buffer = Vec::new();
14343                let range = location.range.to_point(buffer);
14344                ranges_for_buffer.push(range.clone());
14345
14346                while let Some(next_location) = locations.peek() {
14347                    if next_location.buffer == location.buffer {
14348                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14349                        locations.next();
14350                    } else {
14351                        break;
14352                    }
14353                }
14354
14355                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14356                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14357                    PathKey::for_buffer(&location.buffer, cx),
14358                    location.buffer.clone(),
14359                    ranges_for_buffer,
14360                    DEFAULT_MULTIBUFFER_CONTEXT,
14361                    cx,
14362                );
14363                ranges.extend(new_ranges)
14364            }
14365
14366            multibuffer.with_title(title)
14367        });
14368
14369        let editor = cx.new(|cx| {
14370            Editor::for_multibuffer(
14371                excerpt_buffer,
14372                Some(workspace.project().clone()),
14373                window,
14374                cx,
14375            )
14376        });
14377        editor.update(cx, |editor, cx| {
14378            match multibuffer_selection_mode {
14379                MultibufferSelectionMode::First => {
14380                    if let Some(first_range) = ranges.first() {
14381                        editor.change_selections(None, window, cx, |selections| {
14382                            selections.clear_disjoint();
14383                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14384                        });
14385                    }
14386                    editor.highlight_background::<Self>(
14387                        &ranges,
14388                        |theme| theme.editor_highlighted_line_background,
14389                        cx,
14390                    );
14391                }
14392                MultibufferSelectionMode::All => {
14393                    editor.change_selections(None, window, cx, |selections| {
14394                        selections.clear_disjoint();
14395                        selections.select_anchor_ranges(ranges);
14396                    });
14397                }
14398            }
14399            editor.register_buffers_with_language_servers(cx);
14400        });
14401
14402        let item = Box::new(editor);
14403        let item_id = item.item_id();
14404
14405        if split {
14406            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14407        } else {
14408            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14409                let (preview_item_id, preview_item_idx) =
14410                    workspace.active_pane().update(cx, |pane, _| {
14411                        (pane.preview_item_id(), pane.preview_item_idx())
14412                    });
14413
14414                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14415
14416                if let Some(preview_item_id) = preview_item_id {
14417                    workspace.active_pane().update(cx, |pane, cx| {
14418                        pane.remove_item(preview_item_id, false, false, window, cx);
14419                    });
14420                }
14421            } else {
14422                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14423            }
14424        }
14425        workspace.active_pane().update(cx, |pane, cx| {
14426            pane.set_preview_item_id(Some(item_id), cx);
14427        });
14428    }
14429
14430    pub fn rename(
14431        &mut self,
14432        _: &Rename,
14433        window: &mut Window,
14434        cx: &mut Context<Self>,
14435    ) -> Option<Task<Result<()>>> {
14436        use language::ToOffset as _;
14437
14438        let provider = self.semantics_provider.clone()?;
14439        let selection = self.selections.newest_anchor().clone();
14440        let (cursor_buffer, cursor_buffer_position) = self
14441            .buffer
14442            .read(cx)
14443            .text_anchor_for_position(selection.head(), cx)?;
14444        let (tail_buffer, cursor_buffer_position_end) = self
14445            .buffer
14446            .read(cx)
14447            .text_anchor_for_position(selection.tail(), cx)?;
14448        if tail_buffer != cursor_buffer {
14449            return None;
14450        }
14451
14452        let snapshot = cursor_buffer.read(cx).snapshot();
14453        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14454        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14455        let prepare_rename = provider
14456            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14457            .unwrap_or_else(|| Task::ready(Ok(None)));
14458        drop(snapshot);
14459
14460        Some(cx.spawn_in(window, async move |this, cx| {
14461            let rename_range = if let Some(range) = prepare_rename.await? {
14462                Some(range)
14463            } else {
14464                this.update(cx, |this, cx| {
14465                    let buffer = this.buffer.read(cx).snapshot(cx);
14466                    let mut buffer_highlights = this
14467                        .document_highlights_for_position(selection.head(), &buffer)
14468                        .filter(|highlight| {
14469                            highlight.start.excerpt_id == selection.head().excerpt_id
14470                                && highlight.end.excerpt_id == selection.head().excerpt_id
14471                        });
14472                    buffer_highlights
14473                        .next()
14474                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14475                })?
14476            };
14477            if let Some(rename_range) = rename_range {
14478                this.update_in(cx, |this, window, cx| {
14479                    let snapshot = cursor_buffer.read(cx).snapshot();
14480                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14481                    let cursor_offset_in_rename_range =
14482                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14483                    let cursor_offset_in_rename_range_end =
14484                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14485
14486                    this.take_rename(false, window, cx);
14487                    let buffer = this.buffer.read(cx).read(cx);
14488                    let cursor_offset = selection.head().to_offset(&buffer);
14489                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14490                    let rename_end = rename_start + rename_buffer_range.len();
14491                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14492                    let mut old_highlight_id = None;
14493                    let old_name: Arc<str> = buffer
14494                        .chunks(rename_start..rename_end, true)
14495                        .map(|chunk| {
14496                            if old_highlight_id.is_none() {
14497                                old_highlight_id = chunk.syntax_highlight_id;
14498                            }
14499                            chunk.text
14500                        })
14501                        .collect::<String>()
14502                        .into();
14503
14504                    drop(buffer);
14505
14506                    // Position the selection in the rename editor so that it matches the current selection.
14507                    this.show_local_selections = false;
14508                    let rename_editor = cx.new(|cx| {
14509                        let mut editor = Editor::single_line(window, cx);
14510                        editor.buffer.update(cx, |buffer, cx| {
14511                            buffer.edit([(0..0, old_name.clone())], None, cx)
14512                        });
14513                        let rename_selection_range = match cursor_offset_in_rename_range
14514                            .cmp(&cursor_offset_in_rename_range_end)
14515                        {
14516                            Ordering::Equal => {
14517                                editor.select_all(&SelectAll, window, cx);
14518                                return editor;
14519                            }
14520                            Ordering::Less => {
14521                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14522                            }
14523                            Ordering::Greater => {
14524                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14525                            }
14526                        };
14527                        if rename_selection_range.end > old_name.len() {
14528                            editor.select_all(&SelectAll, window, cx);
14529                        } else {
14530                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14531                                s.select_ranges([rename_selection_range]);
14532                            });
14533                        }
14534                        editor
14535                    });
14536                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14537                        if e == &EditorEvent::Focused {
14538                            cx.emit(EditorEvent::FocusedIn)
14539                        }
14540                    })
14541                    .detach();
14542
14543                    let write_highlights =
14544                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14545                    let read_highlights =
14546                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14547                    let ranges = write_highlights
14548                        .iter()
14549                        .flat_map(|(_, ranges)| ranges.iter())
14550                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14551                        .cloned()
14552                        .collect();
14553
14554                    this.highlight_text::<Rename>(
14555                        ranges,
14556                        HighlightStyle {
14557                            fade_out: Some(0.6),
14558                            ..Default::default()
14559                        },
14560                        cx,
14561                    );
14562                    let rename_focus_handle = rename_editor.focus_handle(cx);
14563                    window.focus(&rename_focus_handle);
14564                    let block_id = this.insert_blocks(
14565                        [BlockProperties {
14566                            style: BlockStyle::Flex,
14567                            placement: BlockPlacement::Below(range.start),
14568                            height: Some(1),
14569                            render: Arc::new({
14570                                let rename_editor = rename_editor.clone();
14571                                move |cx: &mut BlockContext| {
14572                                    let mut text_style = cx.editor_style.text.clone();
14573                                    if let Some(highlight_style) = old_highlight_id
14574                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14575                                    {
14576                                        text_style = text_style.highlight(highlight_style);
14577                                    }
14578                                    div()
14579                                        .block_mouse_down()
14580                                        .pl(cx.anchor_x)
14581                                        .child(EditorElement::new(
14582                                            &rename_editor,
14583                                            EditorStyle {
14584                                                background: cx.theme().system().transparent,
14585                                                local_player: cx.editor_style.local_player,
14586                                                text: text_style,
14587                                                scrollbar_width: cx.editor_style.scrollbar_width,
14588                                                syntax: cx.editor_style.syntax.clone(),
14589                                                status: cx.editor_style.status.clone(),
14590                                                inlay_hints_style: HighlightStyle {
14591                                                    font_weight: Some(FontWeight::BOLD),
14592                                                    ..make_inlay_hints_style(cx.app)
14593                                                },
14594                                                inline_completion_styles: make_suggestion_styles(
14595                                                    cx.app,
14596                                                ),
14597                                                ..EditorStyle::default()
14598                                            },
14599                                        ))
14600                                        .into_any_element()
14601                                }
14602                            }),
14603                            priority: 0,
14604                        }],
14605                        Some(Autoscroll::fit()),
14606                        cx,
14607                    )[0];
14608                    this.pending_rename = Some(RenameState {
14609                        range,
14610                        old_name,
14611                        editor: rename_editor,
14612                        block_id,
14613                    });
14614                })?;
14615            }
14616
14617            Ok(())
14618        }))
14619    }
14620
14621    pub fn confirm_rename(
14622        &mut self,
14623        _: &ConfirmRename,
14624        window: &mut Window,
14625        cx: &mut Context<Self>,
14626    ) -> Option<Task<Result<()>>> {
14627        let rename = self.take_rename(false, window, cx)?;
14628        let workspace = self.workspace()?.downgrade();
14629        let (buffer, start) = self
14630            .buffer
14631            .read(cx)
14632            .text_anchor_for_position(rename.range.start, cx)?;
14633        let (end_buffer, _) = self
14634            .buffer
14635            .read(cx)
14636            .text_anchor_for_position(rename.range.end, cx)?;
14637        if buffer != end_buffer {
14638            return None;
14639        }
14640
14641        let old_name = rename.old_name;
14642        let new_name = rename.editor.read(cx).text(cx);
14643
14644        let rename = self.semantics_provider.as_ref()?.perform_rename(
14645            &buffer,
14646            start,
14647            new_name.clone(),
14648            cx,
14649        )?;
14650
14651        Some(cx.spawn_in(window, async move |editor, cx| {
14652            let project_transaction = rename.await?;
14653            Self::open_project_transaction(
14654                &editor,
14655                workspace,
14656                project_transaction,
14657                format!("Rename: {}{}", old_name, new_name),
14658                cx,
14659            )
14660            .await?;
14661
14662            editor.update(cx, |editor, cx| {
14663                editor.refresh_document_highlights(cx);
14664            })?;
14665            Ok(())
14666        }))
14667    }
14668
14669    fn take_rename(
14670        &mut self,
14671        moving_cursor: bool,
14672        window: &mut Window,
14673        cx: &mut Context<Self>,
14674    ) -> Option<RenameState> {
14675        let rename = self.pending_rename.take()?;
14676        if rename.editor.focus_handle(cx).is_focused(window) {
14677            window.focus(&self.focus_handle);
14678        }
14679
14680        self.remove_blocks(
14681            [rename.block_id].into_iter().collect(),
14682            Some(Autoscroll::fit()),
14683            cx,
14684        );
14685        self.clear_highlights::<Rename>(cx);
14686        self.show_local_selections = true;
14687
14688        if moving_cursor {
14689            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14690                editor.selections.newest::<usize>(cx).head()
14691            });
14692
14693            // Update the selection to match the position of the selection inside
14694            // the rename editor.
14695            let snapshot = self.buffer.read(cx).read(cx);
14696            let rename_range = rename.range.to_offset(&snapshot);
14697            let cursor_in_editor = snapshot
14698                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14699                .min(rename_range.end);
14700            drop(snapshot);
14701
14702            self.change_selections(None, window, cx, |s| {
14703                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14704            });
14705        } else {
14706            self.refresh_document_highlights(cx);
14707        }
14708
14709        Some(rename)
14710    }
14711
14712    pub fn pending_rename(&self) -> Option<&RenameState> {
14713        self.pending_rename.as_ref()
14714    }
14715
14716    fn format(
14717        &mut self,
14718        _: &Format,
14719        window: &mut Window,
14720        cx: &mut Context<Self>,
14721    ) -> Option<Task<Result<()>>> {
14722        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14723
14724        let project = match &self.project {
14725            Some(project) => project.clone(),
14726            None => return None,
14727        };
14728
14729        Some(self.perform_format(
14730            project,
14731            FormatTrigger::Manual,
14732            FormatTarget::Buffers,
14733            window,
14734            cx,
14735        ))
14736    }
14737
14738    fn format_selections(
14739        &mut self,
14740        _: &FormatSelections,
14741        window: &mut Window,
14742        cx: &mut Context<Self>,
14743    ) -> Option<Task<Result<()>>> {
14744        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14745
14746        let project = match &self.project {
14747            Some(project) => project.clone(),
14748            None => return None,
14749        };
14750
14751        let ranges = self
14752            .selections
14753            .all_adjusted(cx)
14754            .into_iter()
14755            .map(|selection| selection.range())
14756            .collect_vec();
14757
14758        Some(self.perform_format(
14759            project,
14760            FormatTrigger::Manual,
14761            FormatTarget::Ranges(ranges),
14762            window,
14763            cx,
14764        ))
14765    }
14766
14767    fn perform_format(
14768        &mut self,
14769        project: Entity<Project>,
14770        trigger: FormatTrigger,
14771        target: FormatTarget,
14772        window: &mut Window,
14773        cx: &mut Context<Self>,
14774    ) -> Task<Result<()>> {
14775        let buffer = self.buffer.clone();
14776        let (buffers, target) = match target {
14777            FormatTarget::Buffers => {
14778                let mut buffers = buffer.read(cx).all_buffers();
14779                if trigger == FormatTrigger::Save {
14780                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14781                }
14782                (buffers, LspFormatTarget::Buffers)
14783            }
14784            FormatTarget::Ranges(selection_ranges) => {
14785                let multi_buffer = buffer.read(cx);
14786                let snapshot = multi_buffer.read(cx);
14787                let mut buffers = HashSet::default();
14788                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14789                    BTreeMap::new();
14790                for selection_range in selection_ranges {
14791                    for (buffer, buffer_range, _) in
14792                        snapshot.range_to_buffer_ranges(selection_range)
14793                    {
14794                        let buffer_id = buffer.remote_id();
14795                        let start = buffer.anchor_before(buffer_range.start);
14796                        let end = buffer.anchor_after(buffer_range.end);
14797                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14798                        buffer_id_to_ranges
14799                            .entry(buffer_id)
14800                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14801                            .or_insert_with(|| vec![start..end]);
14802                    }
14803                }
14804                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14805            }
14806        };
14807
14808        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14809        let selections_prev = transaction_id_prev
14810            .and_then(|transaction_id_prev| {
14811                // default to selections as they were after the last edit, if we have them,
14812                // instead of how they are now.
14813                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14814                // will take you back to where you made the last edit, instead of staying where you scrolled
14815                self.selection_history
14816                    .transaction(transaction_id_prev)
14817                    .map(|t| t.0.clone())
14818            })
14819            .unwrap_or_else(|| {
14820                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14821                self.selections.disjoint_anchors()
14822            });
14823
14824        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14825        let format = project.update(cx, |project, cx| {
14826            project.format(buffers, target, true, trigger, cx)
14827        });
14828
14829        cx.spawn_in(window, async move |editor, cx| {
14830            let transaction = futures::select_biased! {
14831                transaction = format.log_err().fuse() => transaction,
14832                () = timeout => {
14833                    log::warn!("timed out waiting for formatting");
14834                    None
14835                }
14836            };
14837
14838            buffer
14839                .update(cx, |buffer, cx| {
14840                    if let Some(transaction) = transaction {
14841                        if !buffer.is_singleton() {
14842                            buffer.push_transaction(&transaction.0, cx);
14843                        }
14844                    }
14845                    cx.notify();
14846                })
14847                .ok();
14848
14849            if let Some(transaction_id_now) =
14850                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14851            {
14852                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14853                if has_new_transaction {
14854                    _ = editor.update(cx, |editor, _| {
14855                        editor
14856                            .selection_history
14857                            .insert_transaction(transaction_id_now, selections_prev);
14858                    });
14859                }
14860            }
14861
14862            Ok(())
14863        })
14864    }
14865
14866    fn organize_imports(
14867        &mut self,
14868        _: &OrganizeImports,
14869        window: &mut Window,
14870        cx: &mut Context<Self>,
14871    ) -> Option<Task<Result<()>>> {
14872        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14873        let project = match &self.project {
14874            Some(project) => project.clone(),
14875            None => return None,
14876        };
14877        Some(self.perform_code_action_kind(
14878            project,
14879            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14880            window,
14881            cx,
14882        ))
14883    }
14884
14885    fn perform_code_action_kind(
14886        &mut self,
14887        project: Entity<Project>,
14888        kind: CodeActionKind,
14889        window: &mut Window,
14890        cx: &mut Context<Self>,
14891    ) -> Task<Result<()>> {
14892        let buffer = self.buffer.clone();
14893        let buffers = buffer.read(cx).all_buffers();
14894        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14895        let apply_action = project.update(cx, |project, cx| {
14896            project.apply_code_action_kind(buffers, kind, true, cx)
14897        });
14898        cx.spawn_in(window, async move |_, cx| {
14899            let transaction = futures::select_biased! {
14900                () = timeout => {
14901                    log::warn!("timed out waiting for executing code action");
14902                    None
14903                }
14904                transaction = apply_action.log_err().fuse() => transaction,
14905            };
14906            buffer
14907                .update(cx, |buffer, cx| {
14908                    // check if we need this
14909                    if let Some(transaction) = transaction {
14910                        if !buffer.is_singleton() {
14911                            buffer.push_transaction(&transaction.0, cx);
14912                        }
14913                    }
14914                    cx.notify();
14915                })
14916                .ok();
14917            Ok(())
14918        })
14919    }
14920
14921    fn restart_language_server(
14922        &mut self,
14923        _: &RestartLanguageServer,
14924        _: &mut Window,
14925        cx: &mut Context<Self>,
14926    ) {
14927        if let Some(project) = self.project.clone() {
14928            self.buffer.update(cx, |multi_buffer, cx| {
14929                project.update(cx, |project, cx| {
14930                    project.restart_language_servers_for_buffers(
14931                        multi_buffer.all_buffers().into_iter().collect(),
14932                        cx,
14933                    );
14934                });
14935            })
14936        }
14937    }
14938
14939    fn stop_language_server(
14940        &mut self,
14941        _: &StopLanguageServer,
14942        _: &mut Window,
14943        cx: &mut Context<Self>,
14944    ) {
14945        if let Some(project) = self.project.clone() {
14946            self.buffer.update(cx, |multi_buffer, cx| {
14947                project.update(cx, |project, cx| {
14948                    project.stop_language_servers_for_buffers(
14949                        multi_buffer.all_buffers().into_iter().collect(),
14950                        cx,
14951                    );
14952                    cx.emit(project::Event::RefreshInlayHints);
14953                });
14954            });
14955        }
14956    }
14957
14958    fn cancel_language_server_work(
14959        workspace: &mut Workspace,
14960        _: &actions::CancelLanguageServerWork,
14961        _: &mut Window,
14962        cx: &mut Context<Workspace>,
14963    ) {
14964        let project = workspace.project();
14965        let buffers = workspace
14966            .active_item(cx)
14967            .and_then(|item| item.act_as::<Editor>(cx))
14968            .map_or(HashSet::default(), |editor| {
14969                editor.read(cx).buffer.read(cx).all_buffers()
14970            });
14971        project.update(cx, |project, cx| {
14972            project.cancel_language_server_work_for_buffers(buffers, cx);
14973        });
14974    }
14975
14976    fn show_character_palette(
14977        &mut self,
14978        _: &ShowCharacterPalette,
14979        window: &mut Window,
14980        _: &mut Context<Self>,
14981    ) {
14982        window.show_character_palette();
14983    }
14984
14985    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14986        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14987            let buffer = self.buffer.read(cx).snapshot(cx);
14988            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14989            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14990            let is_valid = buffer
14991                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14992                .any(|entry| {
14993                    entry.diagnostic.is_primary
14994                        && !entry.range.is_empty()
14995                        && entry.range.start == primary_range_start
14996                        && entry.diagnostic.message == active_diagnostics.active_message
14997                });
14998
14999            if !is_valid {
15000                self.dismiss_diagnostics(cx);
15001            }
15002        }
15003    }
15004
15005    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15006        match &self.active_diagnostics {
15007            ActiveDiagnostic::Group(group) => Some(group),
15008            _ => None,
15009        }
15010    }
15011
15012    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15013        self.dismiss_diagnostics(cx);
15014        self.active_diagnostics = ActiveDiagnostic::All;
15015    }
15016
15017    fn activate_diagnostics(
15018        &mut self,
15019        buffer_id: BufferId,
15020        diagnostic: DiagnosticEntry<usize>,
15021        window: &mut Window,
15022        cx: &mut Context<Self>,
15023    ) {
15024        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15025            return;
15026        }
15027        self.dismiss_diagnostics(cx);
15028        let snapshot = self.snapshot(window, cx);
15029        let buffer = self.buffer.read(cx).snapshot(cx);
15030        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15031            return;
15032        };
15033
15034        let diagnostic_group = buffer
15035            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15036            .collect::<Vec<_>>();
15037
15038        let blocks =
15039            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15040
15041        let blocks = self.display_map.update(cx, |display_map, cx| {
15042            display_map.insert_blocks(blocks, cx).into_iter().collect()
15043        });
15044        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15045            active_range: buffer.anchor_before(diagnostic.range.start)
15046                ..buffer.anchor_after(diagnostic.range.end),
15047            active_message: diagnostic.diagnostic.message.clone(),
15048            group_id: diagnostic.diagnostic.group_id,
15049            blocks,
15050        });
15051        cx.notify();
15052    }
15053
15054    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15055        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15056            return;
15057        };
15058
15059        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15060        if let ActiveDiagnostic::Group(group) = prev {
15061            self.display_map.update(cx, |display_map, cx| {
15062                display_map.remove_blocks(group.blocks, cx);
15063            });
15064            cx.notify();
15065        }
15066    }
15067
15068    /// Disable inline diagnostics rendering for this editor.
15069    pub fn disable_inline_diagnostics(&mut self) {
15070        self.inline_diagnostics_enabled = false;
15071        self.inline_diagnostics_update = Task::ready(());
15072        self.inline_diagnostics.clear();
15073    }
15074
15075    pub fn inline_diagnostics_enabled(&self) -> bool {
15076        self.inline_diagnostics_enabled
15077    }
15078
15079    pub fn show_inline_diagnostics(&self) -> bool {
15080        self.show_inline_diagnostics
15081    }
15082
15083    pub fn toggle_inline_diagnostics(
15084        &mut self,
15085        _: &ToggleInlineDiagnostics,
15086        window: &mut Window,
15087        cx: &mut Context<Editor>,
15088    ) {
15089        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15090        self.refresh_inline_diagnostics(false, window, cx);
15091    }
15092
15093    fn refresh_inline_diagnostics(
15094        &mut self,
15095        debounce: bool,
15096        window: &mut Window,
15097        cx: &mut Context<Self>,
15098    ) {
15099        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15100            self.inline_diagnostics_update = Task::ready(());
15101            self.inline_diagnostics.clear();
15102            return;
15103        }
15104
15105        let debounce_ms = ProjectSettings::get_global(cx)
15106            .diagnostics
15107            .inline
15108            .update_debounce_ms;
15109        let debounce = if debounce && debounce_ms > 0 {
15110            Some(Duration::from_millis(debounce_ms))
15111        } else {
15112            None
15113        };
15114        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15115            let editor = editor.upgrade().unwrap();
15116
15117            if let Some(debounce) = debounce {
15118                cx.background_executor().timer(debounce).await;
15119            }
15120            let Some(snapshot) = editor
15121                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15122                .ok()
15123            else {
15124                return;
15125            };
15126
15127            let new_inline_diagnostics = cx
15128                .background_spawn(async move {
15129                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15130                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15131                        let message = diagnostic_entry
15132                            .diagnostic
15133                            .message
15134                            .split_once('\n')
15135                            .map(|(line, _)| line)
15136                            .map(SharedString::new)
15137                            .unwrap_or_else(|| {
15138                                SharedString::from(diagnostic_entry.diagnostic.message)
15139                            });
15140                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15141                        let (Ok(i) | Err(i)) = inline_diagnostics
15142                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15143                        inline_diagnostics.insert(
15144                            i,
15145                            (
15146                                start_anchor,
15147                                InlineDiagnostic {
15148                                    message,
15149                                    group_id: diagnostic_entry.diagnostic.group_id,
15150                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15151                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15152                                    severity: diagnostic_entry.diagnostic.severity,
15153                                },
15154                            ),
15155                        );
15156                    }
15157                    inline_diagnostics
15158                })
15159                .await;
15160
15161            editor
15162                .update(cx, |editor, cx| {
15163                    editor.inline_diagnostics = new_inline_diagnostics;
15164                    cx.notify();
15165                })
15166                .ok();
15167        });
15168    }
15169
15170    pub fn set_selections_from_remote(
15171        &mut self,
15172        selections: Vec<Selection<Anchor>>,
15173        pending_selection: Option<Selection<Anchor>>,
15174        window: &mut Window,
15175        cx: &mut Context<Self>,
15176    ) {
15177        let old_cursor_position = self.selections.newest_anchor().head();
15178        self.selections.change_with(cx, |s| {
15179            s.select_anchors(selections);
15180            if let Some(pending_selection) = pending_selection {
15181                s.set_pending(pending_selection, SelectMode::Character);
15182            } else {
15183                s.clear_pending();
15184            }
15185        });
15186        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15187    }
15188
15189    fn push_to_selection_history(&mut self) {
15190        self.selection_history.push(SelectionHistoryEntry {
15191            selections: self.selections.disjoint_anchors(),
15192            select_next_state: self.select_next_state.clone(),
15193            select_prev_state: self.select_prev_state.clone(),
15194            add_selections_state: self.add_selections_state.clone(),
15195        });
15196    }
15197
15198    pub fn transact(
15199        &mut self,
15200        window: &mut Window,
15201        cx: &mut Context<Self>,
15202        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15203    ) -> Option<TransactionId> {
15204        self.start_transaction_at(Instant::now(), window, cx);
15205        update(self, window, cx);
15206        self.end_transaction_at(Instant::now(), cx)
15207    }
15208
15209    pub fn start_transaction_at(
15210        &mut self,
15211        now: Instant,
15212        window: &mut Window,
15213        cx: &mut Context<Self>,
15214    ) {
15215        self.end_selection(window, cx);
15216        if let Some(tx_id) = self
15217            .buffer
15218            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15219        {
15220            self.selection_history
15221                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15222            cx.emit(EditorEvent::TransactionBegun {
15223                transaction_id: tx_id,
15224            })
15225        }
15226    }
15227
15228    pub fn end_transaction_at(
15229        &mut self,
15230        now: Instant,
15231        cx: &mut Context<Self>,
15232    ) -> Option<TransactionId> {
15233        if let Some(transaction_id) = self
15234            .buffer
15235            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15236        {
15237            if let Some((_, end_selections)) =
15238                self.selection_history.transaction_mut(transaction_id)
15239            {
15240                *end_selections = Some(self.selections.disjoint_anchors());
15241            } else {
15242                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15243            }
15244
15245            cx.emit(EditorEvent::Edited { transaction_id });
15246            Some(transaction_id)
15247        } else {
15248            None
15249        }
15250    }
15251
15252    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15253        if self.selection_mark_mode {
15254            self.change_selections(None, window, cx, |s| {
15255                s.move_with(|_, sel| {
15256                    sel.collapse_to(sel.head(), SelectionGoal::None);
15257                });
15258            })
15259        }
15260        self.selection_mark_mode = true;
15261        cx.notify();
15262    }
15263
15264    pub fn swap_selection_ends(
15265        &mut self,
15266        _: &actions::SwapSelectionEnds,
15267        window: &mut Window,
15268        cx: &mut Context<Self>,
15269    ) {
15270        self.change_selections(None, window, cx, |s| {
15271            s.move_with(|_, sel| {
15272                if sel.start != sel.end {
15273                    sel.reversed = !sel.reversed
15274                }
15275            });
15276        });
15277        self.request_autoscroll(Autoscroll::newest(), cx);
15278        cx.notify();
15279    }
15280
15281    pub fn toggle_fold(
15282        &mut self,
15283        _: &actions::ToggleFold,
15284        window: &mut Window,
15285        cx: &mut Context<Self>,
15286    ) {
15287        if self.is_singleton(cx) {
15288            let selection = self.selections.newest::<Point>(cx);
15289
15290            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15291            let range = if selection.is_empty() {
15292                let point = selection.head().to_display_point(&display_map);
15293                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15294                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15295                    .to_point(&display_map);
15296                start..end
15297            } else {
15298                selection.range()
15299            };
15300            if display_map.folds_in_range(range).next().is_some() {
15301                self.unfold_lines(&Default::default(), window, cx)
15302            } else {
15303                self.fold(&Default::default(), window, cx)
15304            }
15305        } else {
15306            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15307            let buffer_ids: HashSet<_> = self
15308                .selections
15309                .disjoint_anchor_ranges()
15310                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15311                .collect();
15312
15313            let should_unfold = buffer_ids
15314                .iter()
15315                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15316
15317            for buffer_id in buffer_ids {
15318                if should_unfold {
15319                    self.unfold_buffer(buffer_id, cx);
15320                } else {
15321                    self.fold_buffer(buffer_id, cx);
15322                }
15323            }
15324        }
15325    }
15326
15327    pub fn toggle_fold_recursive(
15328        &mut self,
15329        _: &actions::ToggleFoldRecursive,
15330        window: &mut Window,
15331        cx: &mut Context<Self>,
15332    ) {
15333        let selection = self.selections.newest::<Point>(cx);
15334
15335        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15336        let range = if selection.is_empty() {
15337            let point = selection.head().to_display_point(&display_map);
15338            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15339            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15340                .to_point(&display_map);
15341            start..end
15342        } else {
15343            selection.range()
15344        };
15345        if display_map.folds_in_range(range).next().is_some() {
15346            self.unfold_recursive(&Default::default(), window, cx)
15347        } else {
15348            self.fold_recursive(&Default::default(), window, cx)
15349        }
15350    }
15351
15352    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15353        if self.is_singleton(cx) {
15354            let mut to_fold = Vec::new();
15355            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15356            let selections = self.selections.all_adjusted(cx);
15357
15358            for selection in selections {
15359                let range = selection.range().sorted();
15360                let buffer_start_row = range.start.row;
15361
15362                if range.start.row != range.end.row {
15363                    let mut found = false;
15364                    let mut row = range.start.row;
15365                    while row <= range.end.row {
15366                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15367                        {
15368                            found = true;
15369                            row = crease.range().end.row + 1;
15370                            to_fold.push(crease);
15371                        } else {
15372                            row += 1
15373                        }
15374                    }
15375                    if found {
15376                        continue;
15377                    }
15378                }
15379
15380                for row in (0..=range.start.row).rev() {
15381                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15382                        if crease.range().end.row >= buffer_start_row {
15383                            to_fold.push(crease);
15384                            if row <= range.start.row {
15385                                break;
15386                            }
15387                        }
15388                    }
15389                }
15390            }
15391
15392            self.fold_creases(to_fold, true, window, cx);
15393        } else {
15394            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15395            let buffer_ids = self
15396                .selections
15397                .disjoint_anchor_ranges()
15398                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15399                .collect::<HashSet<_>>();
15400            for buffer_id in buffer_ids {
15401                self.fold_buffer(buffer_id, cx);
15402            }
15403        }
15404    }
15405
15406    fn fold_at_level(
15407        &mut self,
15408        fold_at: &FoldAtLevel,
15409        window: &mut Window,
15410        cx: &mut Context<Self>,
15411    ) {
15412        if !self.buffer.read(cx).is_singleton() {
15413            return;
15414        }
15415
15416        let fold_at_level = fold_at.0;
15417        let snapshot = self.buffer.read(cx).snapshot(cx);
15418        let mut to_fold = Vec::new();
15419        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15420
15421        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15422            while start_row < end_row {
15423                match self
15424                    .snapshot(window, cx)
15425                    .crease_for_buffer_row(MultiBufferRow(start_row))
15426                {
15427                    Some(crease) => {
15428                        let nested_start_row = crease.range().start.row + 1;
15429                        let nested_end_row = crease.range().end.row;
15430
15431                        if current_level < fold_at_level {
15432                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15433                        } else if current_level == fold_at_level {
15434                            to_fold.push(crease);
15435                        }
15436
15437                        start_row = nested_end_row + 1;
15438                    }
15439                    None => start_row += 1,
15440                }
15441            }
15442        }
15443
15444        self.fold_creases(to_fold, true, window, cx);
15445    }
15446
15447    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15448        if self.buffer.read(cx).is_singleton() {
15449            let mut fold_ranges = Vec::new();
15450            let snapshot = self.buffer.read(cx).snapshot(cx);
15451
15452            for row in 0..snapshot.max_row().0 {
15453                if let Some(foldable_range) = self
15454                    .snapshot(window, cx)
15455                    .crease_for_buffer_row(MultiBufferRow(row))
15456                {
15457                    fold_ranges.push(foldable_range);
15458                }
15459            }
15460
15461            self.fold_creases(fold_ranges, true, window, cx);
15462        } else {
15463            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15464                editor
15465                    .update_in(cx, |editor, _, cx| {
15466                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15467                            editor.fold_buffer(buffer_id, cx);
15468                        }
15469                    })
15470                    .ok();
15471            });
15472        }
15473    }
15474
15475    pub fn fold_function_bodies(
15476        &mut self,
15477        _: &actions::FoldFunctionBodies,
15478        window: &mut Window,
15479        cx: &mut Context<Self>,
15480    ) {
15481        let snapshot = self.buffer.read(cx).snapshot(cx);
15482
15483        let ranges = snapshot
15484            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15485            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15486            .collect::<Vec<_>>();
15487
15488        let creases = ranges
15489            .into_iter()
15490            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15491            .collect();
15492
15493        self.fold_creases(creases, true, window, cx);
15494    }
15495
15496    pub fn fold_recursive(
15497        &mut self,
15498        _: &actions::FoldRecursive,
15499        window: &mut Window,
15500        cx: &mut Context<Self>,
15501    ) {
15502        let mut to_fold = Vec::new();
15503        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15504        let selections = self.selections.all_adjusted(cx);
15505
15506        for selection in selections {
15507            let range = selection.range().sorted();
15508            let buffer_start_row = range.start.row;
15509
15510            if range.start.row != range.end.row {
15511                let mut found = false;
15512                for row in range.start.row..=range.end.row {
15513                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15514                        found = true;
15515                        to_fold.push(crease);
15516                    }
15517                }
15518                if found {
15519                    continue;
15520                }
15521            }
15522
15523            for row in (0..=range.start.row).rev() {
15524                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15525                    if crease.range().end.row >= buffer_start_row {
15526                        to_fold.push(crease);
15527                    } else {
15528                        break;
15529                    }
15530                }
15531            }
15532        }
15533
15534        self.fold_creases(to_fold, true, window, cx);
15535    }
15536
15537    pub fn fold_at(
15538        &mut self,
15539        buffer_row: MultiBufferRow,
15540        window: &mut Window,
15541        cx: &mut Context<Self>,
15542    ) {
15543        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15544
15545        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15546            let autoscroll = self
15547                .selections
15548                .all::<Point>(cx)
15549                .iter()
15550                .any(|selection| crease.range().overlaps(&selection.range()));
15551
15552            self.fold_creases(vec![crease], autoscroll, window, cx);
15553        }
15554    }
15555
15556    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15557        if self.is_singleton(cx) {
15558            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15559            let buffer = &display_map.buffer_snapshot;
15560            let selections = self.selections.all::<Point>(cx);
15561            let ranges = selections
15562                .iter()
15563                .map(|s| {
15564                    let range = s.display_range(&display_map).sorted();
15565                    let mut start = range.start.to_point(&display_map);
15566                    let mut end = range.end.to_point(&display_map);
15567                    start.column = 0;
15568                    end.column = buffer.line_len(MultiBufferRow(end.row));
15569                    start..end
15570                })
15571                .collect::<Vec<_>>();
15572
15573            self.unfold_ranges(&ranges, true, true, cx);
15574        } else {
15575            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15576            let buffer_ids = self
15577                .selections
15578                .disjoint_anchor_ranges()
15579                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15580                .collect::<HashSet<_>>();
15581            for buffer_id in buffer_ids {
15582                self.unfold_buffer(buffer_id, cx);
15583            }
15584        }
15585    }
15586
15587    pub fn unfold_recursive(
15588        &mut self,
15589        _: &UnfoldRecursive,
15590        _window: &mut Window,
15591        cx: &mut Context<Self>,
15592    ) {
15593        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15594        let selections = self.selections.all::<Point>(cx);
15595        let ranges = selections
15596            .iter()
15597            .map(|s| {
15598                let mut range = s.display_range(&display_map).sorted();
15599                *range.start.column_mut() = 0;
15600                *range.end.column_mut() = display_map.line_len(range.end.row());
15601                let start = range.start.to_point(&display_map);
15602                let end = range.end.to_point(&display_map);
15603                start..end
15604            })
15605            .collect::<Vec<_>>();
15606
15607        self.unfold_ranges(&ranges, true, true, cx);
15608    }
15609
15610    pub fn unfold_at(
15611        &mut self,
15612        buffer_row: MultiBufferRow,
15613        _window: &mut Window,
15614        cx: &mut Context<Self>,
15615    ) {
15616        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15617
15618        let intersection_range = Point::new(buffer_row.0, 0)
15619            ..Point::new(
15620                buffer_row.0,
15621                display_map.buffer_snapshot.line_len(buffer_row),
15622            );
15623
15624        let autoscroll = self
15625            .selections
15626            .all::<Point>(cx)
15627            .iter()
15628            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15629
15630        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15631    }
15632
15633    pub fn unfold_all(
15634        &mut self,
15635        _: &actions::UnfoldAll,
15636        _window: &mut Window,
15637        cx: &mut Context<Self>,
15638    ) {
15639        if self.buffer.read(cx).is_singleton() {
15640            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15641            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15642        } else {
15643            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15644                editor
15645                    .update(cx, |editor, cx| {
15646                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15647                            editor.unfold_buffer(buffer_id, cx);
15648                        }
15649                    })
15650                    .ok();
15651            });
15652        }
15653    }
15654
15655    pub fn fold_selected_ranges(
15656        &mut self,
15657        _: &FoldSelectedRanges,
15658        window: &mut Window,
15659        cx: &mut Context<Self>,
15660    ) {
15661        let selections = self.selections.all_adjusted(cx);
15662        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15663        let ranges = selections
15664            .into_iter()
15665            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15666            .collect::<Vec<_>>();
15667        self.fold_creases(ranges, true, window, cx);
15668    }
15669
15670    pub fn fold_ranges<T: ToOffset + Clone>(
15671        &mut self,
15672        ranges: Vec<Range<T>>,
15673        auto_scroll: bool,
15674        window: &mut Window,
15675        cx: &mut Context<Self>,
15676    ) {
15677        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15678        let ranges = ranges
15679            .into_iter()
15680            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15681            .collect::<Vec<_>>();
15682        self.fold_creases(ranges, auto_scroll, window, cx);
15683    }
15684
15685    pub fn fold_creases<T: ToOffset + Clone>(
15686        &mut self,
15687        creases: Vec<Crease<T>>,
15688        auto_scroll: bool,
15689        _window: &mut Window,
15690        cx: &mut Context<Self>,
15691    ) {
15692        if creases.is_empty() {
15693            return;
15694        }
15695
15696        let mut buffers_affected = HashSet::default();
15697        let multi_buffer = self.buffer().read(cx);
15698        for crease in &creases {
15699            if let Some((_, buffer, _)) =
15700                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15701            {
15702                buffers_affected.insert(buffer.read(cx).remote_id());
15703            };
15704        }
15705
15706        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15707
15708        if auto_scroll {
15709            self.request_autoscroll(Autoscroll::fit(), cx);
15710        }
15711
15712        cx.notify();
15713
15714        self.scrollbar_marker_state.dirty = true;
15715        self.folds_did_change(cx);
15716    }
15717
15718    /// Removes any folds whose ranges intersect any of the given ranges.
15719    pub fn unfold_ranges<T: ToOffset + Clone>(
15720        &mut self,
15721        ranges: &[Range<T>],
15722        inclusive: bool,
15723        auto_scroll: bool,
15724        cx: &mut Context<Self>,
15725    ) {
15726        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15727            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15728        });
15729        self.folds_did_change(cx);
15730    }
15731
15732    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15733        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15734            return;
15735        }
15736        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15737        self.display_map.update(cx, |display_map, cx| {
15738            display_map.fold_buffers([buffer_id], cx)
15739        });
15740        cx.emit(EditorEvent::BufferFoldToggled {
15741            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15742            folded: true,
15743        });
15744        cx.notify();
15745    }
15746
15747    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15748        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15749            return;
15750        }
15751        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15752        self.display_map.update(cx, |display_map, cx| {
15753            display_map.unfold_buffers([buffer_id], cx);
15754        });
15755        cx.emit(EditorEvent::BufferFoldToggled {
15756            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15757            folded: false,
15758        });
15759        cx.notify();
15760    }
15761
15762    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15763        self.display_map.read(cx).is_buffer_folded(buffer)
15764    }
15765
15766    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15767        self.display_map.read(cx).folded_buffers()
15768    }
15769
15770    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15771        self.display_map.update(cx, |display_map, cx| {
15772            display_map.disable_header_for_buffer(buffer_id, cx);
15773        });
15774        cx.notify();
15775    }
15776
15777    /// Removes any folds with the given ranges.
15778    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15779        &mut self,
15780        ranges: &[Range<T>],
15781        type_id: TypeId,
15782        auto_scroll: bool,
15783        cx: &mut Context<Self>,
15784    ) {
15785        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15786            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15787        });
15788        self.folds_did_change(cx);
15789    }
15790
15791    fn remove_folds_with<T: ToOffset + Clone>(
15792        &mut self,
15793        ranges: &[Range<T>],
15794        auto_scroll: bool,
15795        cx: &mut Context<Self>,
15796        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15797    ) {
15798        if ranges.is_empty() {
15799            return;
15800        }
15801
15802        let mut buffers_affected = HashSet::default();
15803        let multi_buffer = self.buffer().read(cx);
15804        for range in ranges {
15805            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15806                buffers_affected.insert(buffer.read(cx).remote_id());
15807            };
15808        }
15809
15810        self.display_map.update(cx, update);
15811
15812        if auto_scroll {
15813            self.request_autoscroll(Autoscroll::fit(), cx);
15814        }
15815
15816        cx.notify();
15817        self.scrollbar_marker_state.dirty = true;
15818        self.active_indent_guides_state.dirty = true;
15819    }
15820
15821    pub fn update_fold_widths(
15822        &mut self,
15823        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15824        cx: &mut Context<Self>,
15825    ) -> bool {
15826        self.display_map
15827            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15828    }
15829
15830    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15831        self.display_map.read(cx).fold_placeholder.clone()
15832    }
15833
15834    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15835        self.buffer.update(cx, |buffer, cx| {
15836            buffer.set_all_diff_hunks_expanded(cx);
15837        });
15838    }
15839
15840    pub fn expand_all_diff_hunks(
15841        &mut self,
15842        _: &ExpandAllDiffHunks,
15843        _window: &mut Window,
15844        cx: &mut Context<Self>,
15845    ) {
15846        self.buffer.update(cx, |buffer, cx| {
15847            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15848        });
15849    }
15850
15851    pub fn toggle_selected_diff_hunks(
15852        &mut self,
15853        _: &ToggleSelectedDiffHunks,
15854        _window: &mut Window,
15855        cx: &mut Context<Self>,
15856    ) {
15857        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15858        self.toggle_diff_hunks_in_ranges(ranges, cx);
15859    }
15860
15861    pub fn diff_hunks_in_ranges<'a>(
15862        &'a self,
15863        ranges: &'a [Range<Anchor>],
15864        buffer: &'a MultiBufferSnapshot,
15865    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15866        ranges.iter().flat_map(move |range| {
15867            let end_excerpt_id = range.end.excerpt_id;
15868            let range = range.to_point(buffer);
15869            let mut peek_end = range.end;
15870            if range.end.row < buffer.max_row().0 {
15871                peek_end = Point::new(range.end.row + 1, 0);
15872            }
15873            buffer
15874                .diff_hunks_in_range(range.start..peek_end)
15875                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15876        })
15877    }
15878
15879    pub fn has_stageable_diff_hunks_in_ranges(
15880        &self,
15881        ranges: &[Range<Anchor>],
15882        snapshot: &MultiBufferSnapshot,
15883    ) -> bool {
15884        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15885        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15886    }
15887
15888    pub fn toggle_staged_selected_diff_hunks(
15889        &mut self,
15890        _: &::git::ToggleStaged,
15891        _: &mut Window,
15892        cx: &mut Context<Self>,
15893    ) {
15894        let snapshot = self.buffer.read(cx).snapshot(cx);
15895        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15896        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15897        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15898    }
15899
15900    pub fn set_render_diff_hunk_controls(
15901        &mut self,
15902        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15903        cx: &mut Context<Self>,
15904    ) {
15905        self.render_diff_hunk_controls = render_diff_hunk_controls;
15906        cx.notify();
15907    }
15908
15909    pub fn stage_and_next(
15910        &mut self,
15911        _: &::git::StageAndNext,
15912        window: &mut Window,
15913        cx: &mut Context<Self>,
15914    ) {
15915        self.do_stage_or_unstage_and_next(true, window, cx);
15916    }
15917
15918    pub fn unstage_and_next(
15919        &mut self,
15920        _: &::git::UnstageAndNext,
15921        window: &mut Window,
15922        cx: &mut Context<Self>,
15923    ) {
15924        self.do_stage_or_unstage_and_next(false, window, cx);
15925    }
15926
15927    pub fn stage_or_unstage_diff_hunks(
15928        &mut self,
15929        stage: bool,
15930        ranges: Vec<Range<Anchor>>,
15931        cx: &mut Context<Self>,
15932    ) {
15933        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15934        cx.spawn(async move |this, cx| {
15935            task.await?;
15936            this.update(cx, |this, cx| {
15937                let snapshot = this.buffer.read(cx).snapshot(cx);
15938                let chunk_by = this
15939                    .diff_hunks_in_ranges(&ranges, &snapshot)
15940                    .chunk_by(|hunk| hunk.buffer_id);
15941                for (buffer_id, hunks) in &chunk_by {
15942                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15943                }
15944            })
15945        })
15946        .detach_and_log_err(cx);
15947    }
15948
15949    fn save_buffers_for_ranges_if_needed(
15950        &mut self,
15951        ranges: &[Range<Anchor>],
15952        cx: &mut Context<Editor>,
15953    ) -> Task<Result<()>> {
15954        let multibuffer = self.buffer.read(cx);
15955        let snapshot = multibuffer.read(cx);
15956        let buffer_ids: HashSet<_> = ranges
15957            .iter()
15958            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15959            .collect();
15960        drop(snapshot);
15961
15962        let mut buffers = HashSet::default();
15963        for buffer_id in buffer_ids {
15964            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15965                let buffer = buffer_entity.read(cx);
15966                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15967                {
15968                    buffers.insert(buffer_entity);
15969                }
15970            }
15971        }
15972
15973        if let Some(project) = &self.project {
15974            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15975        } else {
15976            Task::ready(Ok(()))
15977        }
15978    }
15979
15980    fn do_stage_or_unstage_and_next(
15981        &mut self,
15982        stage: bool,
15983        window: &mut Window,
15984        cx: &mut Context<Self>,
15985    ) {
15986        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15987
15988        if ranges.iter().any(|range| range.start != range.end) {
15989            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15990            return;
15991        }
15992
15993        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15994        let snapshot = self.snapshot(window, cx);
15995        let position = self.selections.newest::<Point>(cx).head();
15996        let mut row = snapshot
15997            .buffer_snapshot
15998            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15999            .find(|hunk| hunk.row_range.start.0 > position.row)
16000            .map(|hunk| hunk.row_range.start);
16001
16002        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16003        // Outside of the project diff editor, wrap around to the beginning.
16004        if !all_diff_hunks_expanded {
16005            row = row.or_else(|| {
16006                snapshot
16007                    .buffer_snapshot
16008                    .diff_hunks_in_range(Point::zero()..position)
16009                    .find(|hunk| hunk.row_range.end.0 < position.row)
16010                    .map(|hunk| hunk.row_range.start)
16011            });
16012        }
16013
16014        if let Some(row) = row {
16015            let destination = Point::new(row.0, 0);
16016            let autoscroll = Autoscroll::center();
16017
16018            self.unfold_ranges(&[destination..destination], false, false, cx);
16019            self.change_selections(Some(autoscroll), window, cx, |s| {
16020                s.select_ranges([destination..destination]);
16021            });
16022        }
16023    }
16024
16025    fn do_stage_or_unstage(
16026        &self,
16027        stage: bool,
16028        buffer_id: BufferId,
16029        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16030        cx: &mut App,
16031    ) -> Option<()> {
16032        let project = self.project.as_ref()?;
16033        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16034        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16035        let buffer_snapshot = buffer.read(cx).snapshot();
16036        let file_exists = buffer_snapshot
16037            .file()
16038            .is_some_and(|file| file.disk_state().exists());
16039        diff.update(cx, |diff, cx| {
16040            diff.stage_or_unstage_hunks(
16041                stage,
16042                &hunks
16043                    .map(|hunk| buffer_diff::DiffHunk {
16044                        buffer_range: hunk.buffer_range,
16045                        diff_base_byte_range: hunk.diff_base_byte_range,
16046                        secondary_status: hunk.secondary_status,
16047                        range: Point::zero()..Point::zero(), // unused
16048                    })
16049                    .collect::<Vec<_>>(),
16050                &buffer_snapshot,
16051                file_exists,
16052                cx,
16053            )
16054        });
16055        None
16056    }
16057
16058    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16059        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16060        self.buffer
16061            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16062    }
16063
16064    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16065        self.buffer.update(cx, |buffer, cx| {
16066            let ranges = vec![Anchor::min()..Anchor::max()];
16067            if !buffer.all_diff_hunks_expanded()
16068                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16069            {
16070                buffer.collapse_diff_hunks(ranges, cx);
16071                true
16072            } else {
16073                false
16074            }
16075        })
16076    }
16077
16078    fn toggle_diff_hunks_in_ranges(
16079        &mut self,
16080        ranges: Vec<Range<Anchor>>,
16081        cx: &mut Context<Editor>,
16082    ) {
16083        self.buffer.update(cx, |buffer, cx| {
16084            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16085            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16086        })
16087    }
16088
16089    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16090        self.buffer.update(cx, |buffer, cx| {
16091            let snapshot = buffer.snapshot(cx);
16092            let excerpt_id = range.end.excerpt_id;
16093            let point_range = range.to_point(&snapshot);
16094            let expand = !buffer.single_hunk_is_expanded(range, cx);
16095            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16096        })
16097    }
16098
16099    pub(crate) fn apply_all_diff_hunks(
16100        &mut self,
16101        _: &ApplyAllDiffHunks,
16102        window: &mut Window,
16103        cx: &mut Context<Self>,
16104    ) {
16105        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16106
16107        let buffers = self.buffer.read(cx).all_buffers();
16108        for branch_buffer in buffers {
16109            branch_buffer.update(cx, |branch_buffer, cx| {
16110                branch_buffer.merge_into_base(Vec::new(), cx);
16111            });
16112        }
16113
16114        if let Some(project) = self.project.clone() {
16115            self.save(true, project, window, cx).detach_and_log_err(cx);
16116        }
16117    }
16118
16119    pub(crate) fn apply_selected_diff_hunks(
16120        &mut self,
16121        _: &ApplyDiffHunk,
16122        window: &mut Window,
16123        cx: &mut Context<Self>,
16124    ) {
16125        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16126        let snapshot = self.snapshot(window, cx);
16127        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16128        let mut ranges_by_buffer = HashMap::default();
16129        self.transact(window, cx, |editor, _window, cx| {
16130            for hunk in hunks {
16131                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16132                    ranges_by_buffer
16133                        .entry(buffer.clone())
16134                        .or_insert_with(Vec::new)
16135                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16136                }
16137            }
16138
16139            for (buffer, ranges) in ranges_by_buffer {
16140                buffer.update(cx, |buffer, cx| {
16141                    buffer.merge_into_base(ranges, cx);
16142                });
16143            }
16144        });
16145
16146        if let Some(project) = self.project.clone() {
16147            self.save(true, project, window, cx).detach_and_log_err(cx);
16148        }
16149    }
16150
16151    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16152        if hovered != self.gutter_hovered {
16153            self.gutter_hovered = hovered;
16154            cx.notify();
16155        }
16156    }
16157
16158    pub fn insert_blocks(
16159        &mut self,
16160        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16161        autoscroll: Option<Autoscroll>,
16162        cx: &mut Context<Self>,
16163    ) -> Vec<CustomBlockId> {
16164        let blocks = self
16165            .display_map
16166            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16167        if let Some(autoscroll) = autoscroll {
16168            self.request_autoscroll(autoscroll, cx);
16169        }
16170        cx.notify();
16171        blocks
16172    }
16173
16174    pub fn resize_blocks(
16175        &mut self,
16176        heights: HashMap<CustomBlockId, u32>,
16177        autoscroll: Option<Autoscroll>,
16178        cx: &mut Context<Self>,
16179    ) {
16180        self.display_map
16181            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16182        if let Some(autoscroll) = autoscroll {
16183            self.request_autoscroll(autoscroll, cx);
16184        }
16185        cx.notify();
16186    }
16187
16188    pub fn replace_blocks(
16189        &mut self,
16190        renderers: HashMap<CustomBlockId, RenderBlock>,
16191        autoscroll: Option<Autoscroll>,
16192        cx: &mut Context<Self>,
16193    ) {
16194        self.display_map
16195            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16196        if let Some(autoscroll) = autoscroll {
16197            self.request_autoscroll(autoscroll, cx);
16198        }
16199        cx.notify();
16200    }
16201
16202    pub fn remove_blocks(
16203        &mut self,
16204        block_ids: HashSet<CustomBlockId>,
16205        autoscroll: Option<Autoscroll>,
16206        cx: &mut Context<Self>,
16207    ) {
16208        self.display_map.update(cx, |display_map, cx| {
16209            display_map.remove_blocks(block_ids, cx)
16210        });
16211        if let Some(autoscroll) = autoscroll {
16212            self.request_autoscroll(autoscroll, cx);
16213        }
16214        cx.notify();
16215    }
16216
16217    pub fn row_for_block(
16218        &self,
16219        block_id: CustomBlockId,
16220        cx: &mut Context<Self>,
16221    ) -> Option<DisplayRow> {
16222        self.display_map
16223            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16224    }
16225
16226    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16227        self.focused_block = Some(focused_block);
16228    }
16229
16230    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16231        self.focused_block.take()
16232    }
16233
16234    pub fn insert_creases(
16235        &mut self,
16236        creases: impl IntoIterator<Item = Crease<Anchor>>,
16237        cx: &mut Context<Self>,
16238    ) -> Vec<CreaseId> {
16239        self.display_map
16240            .update(cx, |map, cx| map.insert_creases(creases, cx))
16241    }
16242
16243    pub fn remove_creases(
16244        &mut self,
16245        ids: impl IntoIterator<Item = CreaseId>,
16246        cx: &mut Context<Self>,
16247    ) -> Vec<(CreaseId, Range<Anchor>)> {
16248        self.display_map
16249            .update(cx, |map, cx| map.remove_creases(ids, cx))
16250    }
16251
16252    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16253        self.display_map
16254            .update(cx, |map, cx| map.snapshot(cx))
16255            .longest_row()
16256    }
16257
16258    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16259        self.display_map
16260            .update(cx, |map, cx| map.snapshot(cx))
16261            .max_point()
16262    }
16263
16264    pub fn text(&self, cx: &App) -> String {
16265        self.buffer.read(cx).read(cx).text()
16266    }
16267
16268    pub fn is_empty(&self, cx: &App) -> bool {
16269        self.buffer.read(cx).read(cx).is_empty()
16270    }
16271
16272    pub fn text_option(&self, cx: &App) -> Option<String> {
16273        let text = self.text(cx);
16274        let text = text.trim();
16275
16276        if text.is_empty() {
16277            return None;
16278        }
16279
16280        Some(text.to_string())
16281    }
16282
16283    pub fn set_text(
16284        &mut self,
16285        text: impl Into<Arc<str>>,
16286        window: &mut Window,
16287        cx: &mut Context<Self>,
16288    ) {
16289        self.transact(window, cx, |this, _, cx| {
16290            this.buffer
16291                .read(cx)
16292                .as_singleton()
16293                .expect("you can only call set_text on editors for singleton buffers")
16294                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16295        });
16296    }
16297
16298    pub fn display_text(&self, cx: &mut App) -> String {
16299        self.display_map
16300            .update(cx, |map, cx| map.snapshot(cx))
16301            .text()
16302    }
16303
16304    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16305        let mut wrap_guides = smallvec::smallvec![];
16306
16307        if self.show_wrap_guides == Some(false) {
16308            return wrap_guides;
16309        }
16310
16311        let settings = self.buffer.read(cx).language_settings(cx);
16312        if settings.show_wrap_guides {
16313            match self.soft_wrap_mode(cx) {
16314                SoftWrap::Column(soft_wrap) => {
16315                    wrap_guides.push((soft_wrap as usize, true));
16316                }
16317                SoftWrap::Bounded(soft_wrap) => {
16318                    wrap_guides.push((soft_wrap as usize, true));
16319                }
16320                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16321            }
16322            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16323        }
16324
16325        wrap_guides
16326    }
16327
16328    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16329        let settings = self.buffer.read(cx).language_settings(cx);
16330        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16331        match mode {
16332            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16333                SoftWrap::None
16334            }
16335            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16336            language_settings::SoftWrap::PreferredLineLength => {
16337                SoftWrap::Column(settings.preferred_line_length)
16338            }
16339            language_settings::SoftWrap::Bounded => {
16340                SoftWrap::Bounded(settings.preferred_line_length)
16341            }
16342        }
16343    }
16344
16345    pub fn set_soft_wrap_mode(
16346        &mut self,
16347        mode: language_settings::SoftWrap,
16348
16349        cx: &mut Context<Self>,
16350    ) {
16351        self.soft_wrap_mode_override = Some(mode);
16352        cx.notify();
16353    }
16354
16355    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16356        self.hard_wrap = hard_wrap;
16357        cx.notify();
16358    }
16359
16360    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16361        self.text_style_refinement = Some(style);
16362    }
16363
16364    /// called by the Element so we know what style we were most recently rendered with.
16365    pub(crate) fn set_style(
16366        &mut self,
16367        style: EditorStyle,
16368        window: &mut Window,
16369        cx: &mut Context<Self>,
16370    ) {
16371        let rem_size = window.rem_size();
16372        self.display_map.update(cx, |map, cx| {
16373            map.set_font(
16374                style.text.font(),
16375                style.text.font_size.to_pixels(rem_size),
16376                cx,
16377            )
16378        });
16379        self.style = Some(style);
16380    }
16381
16382    pub fn style(&self) -> Option<&EditorStyle> {
16383        self.style.as_ref()
16384    }
16385
16386    // Called by the element. This method is not designed to be called outside of the editor
16387    // element's layout code because it does not notify when rewrapping is computed synchronously.
16388    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16389        self.display_map
16390            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16391    }
16392
16393    pub fn set_soft_wrap(&mut self) {
16394        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16395    }
16396
16397    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16398        if self.soft_wrap_mode_override.is_some() {
16399            self.soft_wrap_mode_override.take();
16400        } else {
16401            let soft_wrap = match self.soft_wrap_mode(cx) {
16402                SoftWrap::GitDiff => return,
16403                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16404                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16405                    language_settings::SoftWrap::None
16406                }
16407            };
16408            self.soft_wrap_mode_override = Some(soft_wrap);
16409        }
16410        cx.notify();
16411    }
16412
16413    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16414        let Some(workspace) = self.workspace() else {
16415            return;
16416        };
16417        let fs = workspace.read(cx).app_state().fs.clone();
16418        let current_show = TabBarSettings::get_global(cx).show;
16419        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16420            setting.show = Some(!current_show);
16421        });
16422    }
16423
16424    pub fn toggle_indent_guides(
16425        &mut self,
16426        _: &ToggleIndentGuides,
16427        _: &mut Window,
16428        cx: &mut Context<Self>,
16429    ) {
16430        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16431            self.buffer
16432                .read(cx)
16433                .language_settings(cx)
16434                .indent_guides
16435                .enabled
16436        });
16437        self.show_indent_guides = Some(!currently_enabled);
16438        cx.notify();
16439    }
16440
16441    fn should_show_indent_guides(&self) -> Option<bool> {
16442        self.show_indent_guides
16443    }
16444
16445    pub fn toggle_line_numbers(
16446        &mut self,
16447        _: &ToggleLineNumbers,
16448        _: &mut Window,
16449        cx: &mut Context<Self>,
16450    ) {
16451        let mut editor_settings = EditorSettings::get_global(cx).clone();
16452        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16453        EditorSettings::override_global(editor_settings, cx);
16454    }
16455
16456    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16457        if let Some(show_line_numbers) = self.show_line_numbers {
16458            return show_line_numbers;
16459        }
16460        EditorSettings::get_global(cx).gutter.line_numbers
16461    }
16462
16463    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16464        self.use_relative_line_numbers
16465            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16466    }
16467
16468    pub fn toggle_relative_line_numbers(
16469        &mut self,
16470        _: &ToggleRelativeLineNumbers,
16471        _: &mut Window,
16472        cx: &mut Context<Self>,
16473    ) {
16474        let is_relative = self.should_use_relative_line_numbers(cx);
16475        self.set_relative_line_number(Some(!is_relative), cx)
16476    }
16477
16478    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16479        self.use_relative_line_numbers = is_relative;
16480        cx.notify();
16481    }
16482
16483    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16484        self.show_gutter = show_gutter;
16485        cx.notify();
16486    }
16487
16488    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16489        self.show_scrollbars = show_scrollbars;
16490        cx.notify();
16491    }
16492
16493    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16494        self.show_line_numbers = Some(show_line_numbers);
16495        cx.notify();
16496    }
16497
16498    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16499        self.disable_expand_excerpt_buttons = true;
16500        cx.notify();
16501    }
16502
16503    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16504        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16505        cx.notify();
16506    }
16507
16508    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16509        self.show_code_actions = Some(show_code_actions);
16510        cx.notify();
16511    }
16512
16513    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16514        self.show_runnables = Some(show_runnables);
16515        cx.notify();
16516    }
16517
16518    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16519        self.show_breakpoints = Some(show_breakpoints);
16520        cx.notify();
16521    }
16522
16523    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16524        if self.display_map.read(cx).masked != masked {
16525            self.display_map.update(cx, |map, _| map.masked = masked);
16526        }
16527        cx.notify()
16528    }
16529
16530    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16531        self.show_wrap_guides = Some(show_wrap_guides);
16532        cx.notify();
16533    }
16534
16535    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16536        self.show_indent_guides = Some(show_indent_guides);
16537        cx.notify();
16538    }
16539
16540    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16541        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16542            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16543                if let Some(dir) = file.abs_path(cx).parent() {
16544                    return Some(dir.to_owned());
16545                }
16546            }
16547
16548            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16549                return Some(project_path.path.to_path_buf());
16550            }
16551        }
16552
16553        None
16554    }
16555
16556    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16557        self.active_excerpt(cx)?
16558            .1
16559            .read(cx)
16560            .file()
16561            .and_then(|f| f.as_local())
16562    }
16563
16564    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16565        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16566            let buffer = buffer.read(cx);
16567            if let Some(project_path) = buffer.project_path(cx) {
16568                let project = self.project.as_ref()?.read(cx);
16569                project.absolute_path(&project_path, cx)
16570            } else {
16571                buffer
16572                    .file()
16573                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16574            }
16575        })
16576    }
16577
16578    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16579        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16580            let project_path = buffer.read(cx).project_path(cx)?;
16581            let project = self.project.as_ref()?.read(cx);
16582            let entry = project.entry_for_path(&project_path, cx)?;
16583            let path = entry.path.to_path_buf();
16584            Some(path)
16585        })
16586    }
16587
16588    pub fn reveal_in_finder(
16589        &mut self,
16590        _: &RevealInFileManager,
16591        _window: &mut Window,
16592        cx: &mut Context<Self>,
16593    ) {
16594        if let Some(target) = self.target_file(cx) {
16595            cx.reveal_path(&target.abs_path(cx));
16596        }
16597    }
16598
16599    pub fn copy_path(
16600        &mut self,
16601        _: &zed_actions::workspace::CopyPath,
16602        _window: &mut Window,
16603        cx: &mut Context<Self>,
16604    ) {
16605        if let Some(path) = self.target_file_abs_path(cx) {
16606            if let Some(path) = path.to_str() {
16607                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16608            }
16609        }
16610    }
16611
16612    pub fn copy_relative_path(
16613        &mut self,
16614        _: &zed_actions::workspace::CopyRelativePath,
16615        _window: &mut Window,
16616        cx: &mut Context<Self>,
16617    ) {
16618        if let Some(path) = self.target_file_path(cx) {
16619            if let Some(path) = path.to_str() {
16620                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16621            }
16622        }
16623    }
16624
16625    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16626        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16627            buffer.read(cx).project_path(cx)
16628        } else {
16629            None
16630        }
16631    }
16632
16633    // Returns true if the editor handled a go-to-line request
16634    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16635        maybe!({
16636            let breakpoint_store = self.breakpoint_store.as_ref()?;
16637
16638            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16639            else {
16640                self.clear_row_highlights::<ActiveDebugLine>();
16641                return None;
16642            };
16643
16644            let position = active_stack_frame.position;
16645            let buffer_id = position.buffer_id?;
16646            let snapshot = self
16647                .project
16648                .as_ref()?
16649                .read(cx)
16650                .buffer_for_id(buffer_id, cx)?
16651                .read(cx)
16652                .snapshot();
16653
16654            let mut handled = false;
16655            for (id, ExcerptRange { context, .. }) in
16656                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16657            {
16658                if context.start.cmp(&position, &snapshot).is_ge()
16659                    || context.end.cmp(&position, &snapshot).is_lt()
16660                {
16661                    continue;
16662                }
16663                let snapshot = self.buffer.read(cx).snapshot(cx);
16664                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16665
16666                handled = true;
16667                self.clear_row_highlights::<ActiveDebugLine>();
16668                self.go_to_line::<ActiveDebugLine>(
16669                    multibuffer_anchor,
16670                    Some(cx.theme().colors().editor_debugger_active_line_background),
16671                    window,
16672                    cx,
16673                );
16674
16675                cx.notify();
16676            }
16677
16678            handled.then_some(())
16679        })
16680        .is_some()
16681    }
16682
16683    pub fn copy_file_name_without_extension(
16684        &mut self,
16685        _: &CopyFileNameWithoutExtension,
16686        _: &mut Window,
16687        cx: &mut Context<Self>,
16688    ) {
16689        if let Some(file) = self.target_file(cx) {
16690            if let Some(file_stem) = file.path().file_stem() {
16691                if let Some(name) = file_stem.to_str() {
16692                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16693                }
16694            }
16695        }
16696    }
16697
16698    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16699        if let Some(file) = self.target_file(cx) {
16700            if let Some(file_name) = file.path().file_name() {
16701                if let Some(name) = file_name.to_str() {
16702                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16703                }
16704            }
16705        }
16706    }
16707
16708    pub fn toggle_git_blame(
16709        &mut self,
16710        _: &::git::Blame,
16711        window: &mut Window,
16712        cx: &mut Context<Self>,
16713    ) {
16714        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16715
16716        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16717            self.start_git_blame(true, window, cx);
16718        }
16719
16720        cx.notify();
16721    }
16722
16723    pub fn toggle_git_blame_inline(
16724        &mut self,
16725        _: &ToggleGitBlameInline,
16726        window: &mut Window,
16727        cx: &mut Context<Self>,
16728    ) {
16729        self.toggle_git_blame_inline_internal(true, window, cx);
16730        cx.notify();
16731    }
16732
16733    pub fn open_git_blame_commit(
16734        &mut self,
16735        _: &OpenGitBlameCommit,
16736        window: &mut Window,
16737        cx: &mut Context<Self>,
16738    ) {
16739        self.open_git_blame_commit_internal(window, cx);
16740    }
16741
16742    fn open_git_blame_commit_internal(
16743        &mut self,
16744        window: &mut Window,
16745        cx: &mut Context<Self>,
16746    ) -> Option<()> {
16747        let blame = self.blame.as_ref()?;
16748        let snapshot = self.snapshot(window, cx);
16749        let cursor = self.selections.newest::<Point>(cx).head();
16750        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16751        let blame_entry = blame
16752            .update(cx, |blame, cx| {
16753                blame
16754                    .blame_for_rows(
16755                        &[RowInfo {
16756                            buffer_id: Some(buffer.remote_id()),
16757                            buffer_row: Some(point.row),
16758                            ..Default::default()
16759                        }],
16760                        cx,
16761                    )
16762                    .next()
16763            })
16764            .flatten()?;
16765        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16766        let repo = blame.read(cx).repository(cx)?;
16767        let workspace = self.workspace()?.downgrade();
16768        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16769        None
16770    }
16771
16772    pub fn git_blame_inline_enabled(&self) -> bool {
16773        self.git_blame_inline_enabled
16774    }
16775
16776    pub fn toggle_selection_menu(
16777        &mut self,
16778        _: &ToggleSelectionMenu,
16779        _: &mut Window,
16780        cx: &mut Context<Self>,
16781    ) {
16782        self.show_selection_menu = self
16783            .show_selection_menu
16784            .map(|show_selections_menu| !show_selections_menu)
16785            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16786
16787        cx.notify();
16788    }
16789
16790    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16791        self.show_selection_menu
16792            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16793    }
16794
16795    fn start_git_blame(
16796        &mut self,
16797        user_triggered: bool,
16798        window: &mut Window,
16799        cx: &mut Context<Self>,
16800    ) {
16801        if let Some(project) = self.project.as_ref() {
16802            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16803                return;
16804            };
16805
16806            if buffer.read(cx).file().is_none() {
16807                return;
16808            }
16809
16810            let focused = self.focus_handle(cx).contains_focused(window, cx);
16811
16812            let project = project.clone();
16813            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16814            self.blame_subscription =
16815                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16816            self.blame = Some(blame);
16817        }
16818    }
16819
16820    fn toggle_git_blame_inline_internal(
16821        &mut self,
16822        user_triggered: bool,
16823        window: &mut Window,
16824        cx: &mut Context<Self>,
16825    ) {
16826        if self.git_blame_inline_enabled {
16827            self.git_blame_inline_enabled = false;
16828            self.show_git_blame_inline = false;
16829            self.show_git_blame_inline_delay_task.take();
16830        } else {
16831            self.git_blame_inline_enabled = true;
16832            self.start_git_blame_inline(user_triggered, window, cx);
16833        }
16834
16835        cx.notify();
16836    }
16837
16838    fn start_git_blame_inline(
16839        &mut self,
16840        user_triggered: bool,
16841        window: &mut Window,
16842        cx: &mut Context<Self>,
16843    ) {
16844        self.start_git_blame(user_triggered, window, cx);
16845
16846        if ProjectSettings::get_global(cx)
16847            .git
16848            .inline_blame_delay()
16849            .is_some()
16850        {
16851            self.start_inline_blame_timer(window, cx);
16852        } else {
16853            self.show_git_blame_inline = true
16854        }
16855    }
16856
16857    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16858        self.blame.as_ref()
16859    }
16860
16861    pub fn show_git_blame_gutter(&self) -> bool {
16862        self.show_git_blame_gutter
16863    }
16864
16865    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16866        self.show_git_blame_gutter && self.has_blame_entries(cx)
16867    }
16868
16869    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16870        self.show_git_blame_inline
16871            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16872            && !self.newest_selection_head_on_empty_line(cx)
16873            && self.has_blame_entries(cx)
16874    }
16875
16876    fn has_blame_entries(&self, cx: &App) -> bool {
16877        self.blame()
16878            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16879    }
16880
16881    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16882        let cursor_anchor = self.selections.newest_anchor().head();
16883
16884        let snapshot = self.buffer.read(cx).snapshot(cx);
16885        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16886
16887        snapshot.line_len(buffer_row) == 0
16888    }
16889
16890    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16891        let buffer_and_selection = maybe!({
16892            let selection = self.selections.newest::<Point>(cx);
16893            let selection_range = selection.range();
16894
16895            let multi_buffer = self.buffer().read(cx);
16896            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16897            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16898
16899            let (buffer, range, _) = if selection.reversed {
16900                buffer_ranges.first()
16901            } else {
16902                buffer_ranges.last()
16903            }?;
16904
16905            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16906                ..text::ToPoint::to_point(&range.end, &buffer).row;
16907            Some((
16908                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16909                selection,
16910            ))
16911        });
16912
16913        let Some((buffer, selection)) = buffer_and_selection else {
16914            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16915        };
16916
16917        let Some(project) = self.project.as_ref() else {
16918            return Task::ready(Err(anyhow!("editor does not have project")));
16919        };
16920
16921        project.update(cx, |project, cx| {
16922            project.get_permalink_to_line(&buffer, selection, cx)
16923        })
16924    }
16925
16926    pub fn copy_permalink_to_line(
16927        &mut self,
16928        _: &CopyPermalinkToLine,
16929        window: &mut Window,
16930        cx: &mut Context<Self>,
16931    ) {
16932        let permalink_task = self.get_permalink_to_line(cx);
16933        let workspace = self.workspace();
16934
16935        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16936            Ok(permalink) => {
16937                cx.update(|_, cx| {
16938                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16939                })
16940                .ok();
16941            }
16942            Err(err) => {
16943                let message = format!("Failed to copy permalink: {err}");
16944
16945                Err::<(), anyhow::Error>(err).log_err();
16946
16947                if let Some(workspace) = workspace {
16948                    workspace
16949                        .update_in(cx, |workspace, _, cx| {
16950                            struct CopyPermalinkToLine;
16951
16952                            workspace.show_toast(
16953                                Toast::new(
16954                                    NotificationId::unique::<CopyPermalinkToLine>(),
16955                                    message,
16956                                ),
16957                                cx,
16958                            )
16959                        })
16960                        .ok();
16961                }
16962            }
16963        })
16964        .detach();
16965    }
16966
16967    pub fn copy_file_location(
16968        &mut self,
16969        _: &CopyFileLocation,
16970        _: &mut Window,
16971        cx: &mut Context<Self>,
16972    ) {
16973        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16974        if let Some(file) = self.target_file(cx) {
16975            if let Some(path) = file.path().to_str() {
16976                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16977            }
16978        }
16979    }
16980
16981    pub fn open_permalink_to_line(
16982        &mut self,
16983        _: &OpenPermalinkToLine,
16984        window: &mut Window,
16985        cx: &mut Context<Self>,
16986    ) {
16987        let permalink_task = self.get_permalink_to_line(cx);
16988        let workspace = self.workspace();
16989
16990        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16991            Ok(permalink) => {
16992                cx.update(|_, cx| {
16993                    cx.open_url(permalink.as_ref());
16994                })
16995                .ok();
16996            }
16997            Err(err) => {
16998                let message = format!("Failed to open permalink: {err}");
16999
17000                Err::<(), anyhow::Error>(err).log_err();
17001
17002                if let Some(workspace) = workspace {
17003                    workspace
17004                        .update(cx, |workspace, cx| {
17005                            struct OpenPermalinkToLine;
17006
17007                            workspace.show_toast(
17008                                Toast::new(
17009                                    NotificationId::unique::<OpenPermalinkToLine>(),
17010                                    message,
17011                                ),
17012                                cx,
17013                            )
17014                        })
17015                        .ok();
17016                }
17017            }
17018        })
17019        .detach();
17020    }
17021
17022    pub fn insert_uuid_v4(
17023        &mut self,
17024        _: &InsertUuidV4,
17025        window: &mut Window,
17026        cx: &mut Context<Self>,
17027    ) {
17028        self.insert_uuid(UuidVersion::V4, window, cx);
17029    }
17030
17031    pub fn insert_uuid_v7(
17032        &mut self,
17033        _: &InsertUuidV7,
17034        window: &mut Window,
17035        cx: &mut Context<Self>,
17036    ) {
17037        self.insert_uuid(UuidVersion::V7, window, cx);
17038    }
17039
17040    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17041        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17042        self.transact(window, cx, |this, window, cx| {
17043            let edits = this
17044                .selections
17045                .all::<Point>(cx)
17046                .into_iter()
17047                .map(|selection| {
17048                    let uuid = match version {
17049                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17050                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17051                    };
17052
17053                    (selection.range(), uuid.to_string())
17054                });
17055            this.edit(edits, cx);
17056            this.refresh_inline_completion(true, false, window, cx);
17057        });
17058    }
17059
17060    pub fn open_selections_in_multibuffer(
17061        &mut self,
17062        _: &OpenSelectionsInMultibuffer,
17063        window: &mut Window,
17064        cx: &mut Context<Self>,
17065    ) {
17066        let multibuffer = self.buffer.read(cx);
17067
17068        let Some(buffer) = multibuffer.as_singleton() else {
17069            return;
17070        };
17071
17072        let Some(workspace) = self.workspace() else {
17073            return;
17074        };
17075
17076        let locations = self
17077            .selections
17078            .disjoint_anchors()
17079            .iter()
17080            .map(|range| Location {
17081                buffer: buffer.clone(),
17082                range: range.start.text_anchor..range.end.text_anchor,
17083            })
17084            .collect::<Vec<_>>();
17085
17086        let title = multibuffer.title(cx).to_string();
17087
17088        cx.spawn_in(window, async move |_, cx| {
17089            workspace.update_in(cx, |workspace, window, cx| {
17090                Self::open_locations_in_multibuffer(
17091                    workspace,
17092                    locations,
17093                    format!("Selections for '{title}'"),
17094                    false,
17095                    MultibufferSelectionMode::All,
17096                    window,
17097                    cx,
17098                );
17099            })
17100        })
17101        .detach();
17102    }
17103
17104    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17105    /// last highlight added will be used.
17106    ///
17107    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17108    pub fn highlight_rows<T: 'static>(
17109        &mut self,
17110        range: Range<Anchor>,
17111        color: Hsla,
17112        options: RowHighlightOptions,
17113        cx: &mut Context<Self>,
17114    ) {
17115        let snapshot = self.buffer().read(cx).snapshot(cx);
17116        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17117        let ix = row_highlights.binary_search_by(|highlight| {
17118            Ordering::Equal
17119                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17120                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17121        });
17122
17123        if let Err(mut ix) = ix {
17124            let index = post_inc(&mut self.highlight_order);
17125
17126            // If this range intersects with the preceding highlight, then merge it with
17127            // the preceding highlight. Otherwise insert a new highlight.
17128            let mut merged = false;
17129            if ix > 0 {
17130                let prev_highlight = &mut row_highlights[ix - 1];
17131                if prev_highlight
17132                    .range
17133                    .end
17134                    .cmp(&range.start, &snapshot)
17135                    .is_ge()
17136                {
17137                    ix -= 1;
17138                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17139                        prev_highlight.range.end = range.end;
17140                    }
17141                    merged = true;
17142                    prev_highlight.index = index;
17143                    prev_highlight.color = color;
17144                    prev_highlight.options = options;
17145                }
17146            }
17147
17148            if !merged {
17149                row_highlights.insert(
17150                    ix,
17151                    RowHighlight {
17152                        range: range.clone(),
17153                        index,
17154                        color,
17155                        options,
17156                        type_id: TypeId::of::<T>(),
17157                    },
17158                );
17159            }
17160
17161            // If any of the following highlights intersect with this one, merge them.
17162            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17163                let highlight = &row_highlights[ix];
17164                if next_highlight
17165                    .range
17166                    .start
17167                    .cmp(&highlight.range.end, &snapshot)
17168                    .is_le()
17169                {
17170                    if next_highlight
17171                        .range
17172                        .end
17173                        .cmp(&highlight.range.end, &snapshot)
17174                        .is_gt()
17175                    {
17176                        row_highlights[ix].range.end = next_highlight.range.end;
17177                    }
17178                    row_highlights.remove(ix + 1);
17179                } else {
17180                    break;
17181                }
17182            }
17183        }
17184    }
17185
17186    /// Remove any highlighted row ranges of the given type that intersect the
17187    /// given ranges.
17188    pub fn remove_highlighted_rows<T: 'static>(
17189        &mut self,
17190        ranges_to_remove: Vec<Range<Anchor>>,
17191        cx: &mut Context<Self>,
17192    ) {
17193        let snapshot = self.buffer().read(cx).snapshot(cx);
17194        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17195        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17196        row_highlights.retain(|highlight| {
17197            while let Some(range_to_remove) = ranges_to_remove.peek() {
17198                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17199                    Ordering::Less | Ordering::Equal => {
17200                        ranges_to_remove.next();
17201                    }
17202                    Ordering::Greater => {
17203                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17204                            Ordering::Less | Ordering::Equal => {
17205                                return false;
17206                            }
17207                            Ordering::Greater => break,
17208                        }
17209                    }
17210                }
17211            }
17212
17213            true
17214        })
17215    }
17216
17217    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17218    pub fn clear_row_highlights<T: 'static>(&mut self) {
17219        self.highlighted_rows.remove(&TypeId::of::<T>());
17220    }
17221
17222    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17223    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17224        self.highlighted_rows
17225            .get(&TypeId::of::<T>())
17226            .map_or(&[] as &[_], |vec| vec.as_slice())
17227            .iter()
17228            .map(|highlight| (highlight.range.clone(), highlight.color))
17229    }
17230
17231    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17232    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17233    /// Allows to ignore certain kinds of highlights.
17234    pub fn highlighted_display_rows(
17235        &self,
17236        window: &mut Window,
17237        cx: &mut App,
17238    ) -> BTreeMap<DisplayRow, LineHighlight> {
17239        let snapshot = self.snapshot(window, cx);
17240        let mut used_highlight_orders = HashMap::default();
17241        self.highlighted_rows
17242            .iter()
17243            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17244            .fold(
17245                BTreeMap::<DisplayRow, LineHighlight>::new(),
17246                |mut unique_rows, highlight| {
17247                    let start = highlight.range.start.to_display_point(&snapshot);
17248                    let end = highlight.range.end.to_display_point(&snapshot);
17249                    let start_row = start.row().0;
17250                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17251                        && end.column() == 0
17252                    {
17253                        end.row().0.saturating_sub(1)
17254                    } else {
17255                        end.row().0
17256                    };
17257                    for row in start_row..=end_row {
17258                        let used_index =
17259                            used_highlight_orders.entry(row).or_insert(highlight.index);
17260                        if highlight.index >= *used_index {
17261                            *used_index = highlight.index;
17262                            unique_rows.insert(
17263                                DisplayRow(row),
17264                                LineHighlight {
17265                                    include_gutter: highlight.options.include_gutter,
17266                                    border: None,
17267                                    background: highlight.color.into(),
17268                                    type_id: Some(highlight.type_id),
17269                                },
17270                            );
17271                        }
17272                    }
17273                    unique_rows
17274                },
17275            )
17276    }
17277
17278    pub fn highlighted_display_row_for_autoscroll(
17279        &self,
17280        snapshot: &DisplaySnapshot,
17281    ) -> Option<DisplayRow> {
17282        self.highlighted_rows
17283            .values()
17284            .flat_map(|highlighted_rows| highlighted_rows.iter())
17285            .filter_map(|highlight| {
17286                if highlight.options.autoscroll {
17287                    Some(highlight.range.start.to_display_point(snapshot).row())
17288                } else {
17289                    None
17290                }
17291            })
17292            .min()
17293    }
17294
17295    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17296        self.highlight_background::<SearchWithinRange>(
17297            ranges,
17298            |colors| colors.editor_document_highlight_read_background,
17299            cx,
17300        )
17301    }
17302
17303    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17304        self.breadcrumb_header = Some(new_header);
17305    }
17306
17307    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17308        self.clear_background_highlights::<SearchWithinRange>(cx);
17309    }
17310
17311    pub fn highlight_background<T: 'static>(
17312        &mut self,
17313        ranges: &[Range<Anchor>],
17314        color_fetcher: fn(&ThemeColors) -> Hsla,
17315        cx: &mut Context<Self>,
17316    ) {
17317        self.background_highlights
17318            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17319        self.scrollbar_marker_state.dirty = true;
17320        cx.notify();
17321    }
17322
17323    pub fn clear_background_highlights<T: 'static>(
17324        &mut self,
17325        cx: &mut Context<Self>,
17326    ) -> Option<BackgroundHighlight> {
17327        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17328        if !text_highlights.1.is_empty() {
17329            self.scrollbar_marker_state.dirty = true;
17330            cx.notify();
17331        }
17332        Some(text_highlights)
17333    }
17334
17335    pub fn highlight_gutter<T: 'static>(
17336        &mut self,
17337        ranges: &[Range<Anchor>],
17338        color_fetcher: fn(&App) -> Hsla,
17339        cx: &mut Context<Self>,
17340    ) {
17341        self.gutter_highlights
17342            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17343        cx.notify();
17344    }
17345
17346    pub fn clear_gutter_highlights<T: 'static>(
17347        &mut self,
17348        cx: &mut Context<Self>,
17349    ) -> Option<GutterHighlight> {
17350        cx.notify();
17351        self.gutter_highlights.remove(&TypeId::of::<T>())
17352    }
17353
17354    #[cfg(feature = "test-support")]
17355    pub fn all_text_background_highlights(
17356        &self,
17357        window: &mut Window,
17358        cx: &mut Context<Self>,
17359    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17360        let snapshot = self.snapshot(window, cx);
17361        let buffer = &snapshot.buffer_snapshot;
17362        let start = buffer.anchor_before(0);
17363        let end = buffer.anchor_after(buffer.len());
17364        let theme = cx.theme().colors();
17365        self.background_highlights_in_range(start..end, &snapshot, theme)
17366    }
17367
17368    #[cfg(feature = "test-support")]
17369    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17370        let snapshot = self.buffer().read(cx).snapshot(cx);
17371
17372        let highlights = self
17373            .background_highlights
17374            .get(&TypeId::of::<items::BufferSearchHighlights>());
17375
17376        if let Some((_color, ranges)) = highlights {
17377            ranges
17378                .iter()
17379                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17380                .collect_vec()
17381        } else {
17382            vec![]
17383        }
17384    }
17385
17386    fn document_highlights_for_position<'a>(
17387        &'a self,
17388        position: Anchor,
17389        buffer: &'a MultiBufferSnapshot,
17390    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17391        let read_highlights = self
17392            .background_highlights
17393            .get(&TypeId::of::<DocumentHighlightRead>())
17394            .map(|h| &h.1);
17395        let write_highlights = self
17396            .background_highlights
17397            .get(&TypeId::of::<DocumentHighlightWrite>())
17398            .map(|h| &h.1);
17399        let left_position = position.bias_left(buffer);
17400        let right_position = position.bias_right(buffer);
17401        read_highlights
17402            .into_iter()
17403            .chain(write_highlights)
17404            .flat_map(move |ranges| {
17405                let start_ix = match ranges.binary_search_by(|probe| {
17406                    let cmp = probe.end.cmp(&left_position, buffer);
17407                    if cmp.is_ge() {
17408                        Ordering::Greater
17409                    } else {
17410                        Ordering::Less
17411                    }
17412                }) {
17413                    Ok(i) | Err(i) => i,
17414                };
17415
17416                ranges[start_ix..]
17417                    .iter()
17418                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17419            })
17420    }
17421
17422    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17423        self.background_highlights
17424            .get(&TypeId::of::<T>())
17425            .map_or(false, |(_, highlights)| !highlights.is_empty())
17426    }
17427
17428    pub fn background_highlights_in_range(
17429        &self,
17430        search_range: Range<Anchor>,
17431        display_snapshot: &DisplaySnapshot,
17432        theme: &ThemeColors,
17433    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17434        let mut results = Vec::new();
17435        for (color_fetcher, ranges) in self.background_highlights.values() {
17436            let color = color_fetcher(theme);
17437            let start_ix = match ranges.binary_search_by(|probe| {
17438                let cmp = probe
17439                    .end
17440                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17441                if cmp.is_gt() {
17442                    Ordering::Greater
17443                } else {
17444                    Ordering::Less
17445                }
17446            }) {
17447                Ok(i) | Err(i) => i,
17448            };
17449            for range in &ranges[start_ix..] {
17450                if range
17451                    .start
17452                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17453                    .is_ge()
17454                {
17455                    break;
17456                }
17457
17458                let start = range.start.to_display_point(display_snapshot);
17459                let end = range.end.to_display_point(display_snapshot);
17460                results.push((start..end, color))
17461            }
17462        }
17463        results
17464    }
17465
17466    pub fn background_highlight_row_ranges<T: 'static>(
17467        &self,
17468        search_range: Range<Anchor>,
17469        display_snapshot: &DisplaySnapshot,
17470        count: usize,
17471    ) -> Vec<RangeInclusive<DisplayPoint>> {
17472        let mut results = Vec::new();
17473        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17474            return vec![];
17475        };
17476
17477        let start_ix = match ranges.binary_search_by(|probe| {
17478            let cmp = probe
17479                .end
17480                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17481            if cmp.is_gt() {
17482                Ordering::Greater
17483            } else {
17484                Ordering::Less
17485            }
17486        }) {
17487            Ok(i) | Err(i) => i,
17488        };
17489        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17490            if let (Some(start_display), Some(end_display)) = (start, end) {
17491                results.push(
17492                    start_display.to_display_point(display_snapshot)
17493                        ..=end_display.to_display_point(display_snapshot),
17494                );
17495            }
17496        };
17497        let mut start_row: Option<Point> = None;
17498        let mut end_row: Option<Point> = None;
17499        if ranges.len() > count {
17500            return Vec::new();
17501        }
17502        for range in &ranges[start_ix..] {
17503            if range
17504                .start
17505                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17506                .is_ge()
17507            {
17508                break;
17509            }
17510            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17511            if let Some(current_row) = &end_row {
17512                if end.row == current_row.row {
17513                    continue;
17514                }
17515            }
17516            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17517            if start_row.is_none() {
17518                assert_eq!(end_row, None);
17519                start_row = Some(start);
17520                end_row = Some(end);
17521                continue;
17522            }
17523            if let Some(current_end) = end_row.as_mut() {
17524                if start.row > current_end.row + 1 {
17525                    push_region(start_row, end_row);
17526                    start_row = Some(start);
17527                    end_row = Some(end);
17528                } else {
17529                    // Merge two hunks.
17530                    *current_end = end;
17531                }
17532            } else {
17533                unreachable!();
17534            }
17535        }
17536        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17537        push_region(start_row, end_row);
17538        results
17539    }
17540
17541    pub fn gutter_highlights_in_range(
17542        &self,
17543        search_range: Range<Anchor>,
17544        display_snapshot: &DisplaySnapshot,
17545        cx: &App,
17546    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17547        let mut results = Vec::new();
17548        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17549            let color = color_fetcher(cx);
17550            let start_ix = match ranges.binary_search_by(|probe| {
17551                let cmp = probe
17552                    .end
17553                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17554                if cmp.is_gt() {
17555                    Ordering::Greater
17556                } else {
17557                    Ordering::Less
17558                }
17559            }) {
17560                Ok(i) | Err(i) => i,
17561            };
17562            for range in &ranges[start_ix..] {
17563                if range
17564                    .start
17565                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17566                    .is_ge()
17567                {
17568                    break;
17569                }
17570
17571                let start = range.start.to_display_point(display_snapshot);
17572                let end = range.end.to_display_point(display_snapshot);
17573                results.push((start..end, color))
17574            }
17575        }
17576        results
17577    }
17578
17579    /// Get the text ranges corresponding to the redaction query
17580    pub fn redacted_ranges(
17581        &self,
17582        search_range: Range<Anchor>,
17583        display_snapshot: &DisplaySnapshot,
17584        cx: &App,
17585    ) -> Vec<Range<DisplayPoint>> {
17586        display_snapshot
17587            .buffer_snapshot
17588            .redacted_ranges(search_range, |file| {
17589                if let Some(file) = file {
17590                    file.is_private()
17591                        && EditorSettings::get(
17592                            Some(SettingsLocation {
17593                                worktree_id: file.worktree_id(cx),
17594                                path: file.path().as_ref(),
17595                            }),
17596                            cx,
17597                        )
17598                        .redact_private_values
17599                } else {
17600                    false
17601                }
17602            })
17603            .map(|range| {
17604                range.start.to_display_point(display_snapshot)
17605                    ..range.end.to_display_point(display_snapshot)
17606            })
17607            .collect()
17608    }
17609
17610    pub fn highlight_text<T: 'static>(
17611        &mut self,
17612        ranges: Vec<Range<Anchor>>,
17613        style: HighlightStyle,
17614        cx: &mut Context<Self>,
17615    ) {
17616        self.display_map.update(cx, |map, _| {
17617            map.highlight_text(TypeId::of::<T>(), ranges, style)
17618        });
17619        cx.notify();
17620    }
17621
17622    pub(crate) fn highlight_inlays<T: 'static>(
17623        &mut self,
17624        highlights: Vec<InlayHighlight>,
17625        style: HighlightStyle,
17626        cx: &mut Context<Self>,
17627    ) {
17628        self.display_map.update(cx, |map, _| {
17629            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17630        });
17631        cx.notify();
17632    }
17633
17634    pub fn text_highlights<'a, T: 'static>(
17635        &'a self,
17636        cx: &'a App,
17637    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17638        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17639    }
17640
17641    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17642        let cleared = self
17643            .display_map
17644            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17645        if cleared {
17646            cx.notify();
17647        }
17648    }
17649
17650    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17651        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17652            && self.focus_handle.is_focused(window)
17653    }
17654
17655    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17656        self.show_cursor_when_unfocused = is_enabled;
17657        cx.notify();
17658    }
17659
17660    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17661        cx.notify();
17662    }
17663
17664    fn on_debug_session_event(
17665        &mut self,
17666        _session: Entity<Session>,
17667        event: &SessionEvent,
17668        cx: &mut Context<Self>,
17669    ) {
17670        match event {
17671            SessionEvent::InvalidateInlineValue => {
17672                self.refresh_inline_values(cx);
17673            }
17674            _ => {}
17675        }
17676    }
17677
17678    pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17679        let Some(project) = self.project.clone() else {
17680            return;
17681        };
17682        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17683            return;
17684        };
17685        if !self.inline_value_cache.enabled {
17686            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17687            self.splice_inlays(&inlays, Vec::new(), cx);
17688            return;
17689        }
17690
17691        let current_execution_position = self
17692            .highlighted_rows
17693            .get(&TypeId::of::<ActiveDebugLine>())
17694            .and_then(|lines| lines.last().map(|line| line.range.start));
17695
17696        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17697            let snapshot = editor
17698                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17699                .ok()?;
17700
17701            let inline_values = editor
17702                .update(cx, |_, cx| {
17703                    let Some(current_execution_position) = current_execution_position else {
17704                        return Some(Task::ready(Ok(Vec::new())));
17705                    };
17706
17707                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17708                    // anchor is in the same buffer
17709                    let range =
17710                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17711                    project.inline_values(buffer, range, cx)
17712                })
17713                .ok()
17714                .flatten()?
17715                .await
17716                .context("refreshing debugger inlays")
17717                .log_err()?;
17718
17719            let (excerpt_id, buffer_id) = snapshot
17720                .excerpts()
17721                .next()
17722                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17723            editor
17724                .update(cx, |editor, cx| {
17725                    let new_inlays = inline_values
17726                        .into_iter()
17727                        .map(|debugger_value| {
17728                            Inlay::debugger_hint(
17729                                post_inc(&mut editor.next_inlay_id),
17730                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17731                                debugger_value.text(),
17732                            )
17733                        })
17734                        .collect::<Vec<_>>();
17735                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17736                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17737
17738                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17739                })
17740                .ok()?;
17741            Some(())
17742        });
17743    }
17744
17745    fn on_buffer_event(
17746        &mut self,
17747        multibuffer: &Entity<MultiBuffer>,
17748        event: &multi_buffer::Event,
17749        window: &mut Window,
17750        cx: &mut Context<Self>,
17751    ) {
17752        match event {
17753            multi_buffer::Event::Edited {
17754                singleton_buffer_edited,
17755                edited_buffer: buffer_edited,
17756            } => {
17757                self.scrollbar_marker_state.dirty = true;
17758                self.active_indent_guides_state.dirty = true;
17759                self.refresh_active_diagnostics(cx);
17760                self.refresh_code_actions(window, cx);
17761                self.refresh_selected_text_highlights(true, window, cx);
17762                refresh_matching_bracket_highlights(self, window, cx);
17763                if self.has_active_inline_completion() {
17764                    self.update_visible_inline_completion(window, cx);
17765                }
17766                if let Some(buffer) = buffer_edited {
17767                    let buffer_id = buffer.read(cx).remote_id();
17768                    if !self.registered_buffers.contains_key(&buffer_id) {
17769                        if let Some(project) = self.project.as_ref() {
17770                            project.update(cx, |project, cx| {
17771                                self.registered_buffers.insert(
17772                                    buffer_id,
17773                                    project.register_buffer_with_language_servers(&buffer, cx),
17774                                );
17775                            })
17776                        }
17777                    }
17778                }
17779                cx.emit(EditorEvent::BufferEdited);
17780                cx.emit(SearchEvent::MatchesInvalidated);
17781                if *singleton_buffer_edited {
17782                    if let Some(project) = &self.project {
17783                        #[allow(clippy::mutable_key_type)]
17784                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17785                            multibuffer
17786                                .all_buffers()
17787                                .into_iter()
17788                                .filter_map(|buffer| {
17789                                    buffer.update(cx, |buffer, cx| {
17790                                        let language = buffer.language()?;
17791                                        let should_discard = project.update(cx, |project, cx| {
17792                                            project.is_local()
17793                                                && !project.has_language_servers_for(buffer, cx)
17794                                        });
17795                                        should_discard.not().then_some(language.clone())
17796                                    })
17797                                })
17798                                .collect::<HashSet<_>>()
17799                        });
17800                        if !languages_affected.is_empty() {
17801                            self.refresh_inlay_hints(
17802                                InlayHintRefreshReason::BufferEdited(languages_affected),
17803                                cx,
17804                            );
17805                        }
17806                    }
17807                }
17808
17809                let Some(project) = &self.project else { return };
17810                let (telemetry, is_via_ssh) = {
17811                    let project = project.read(cx);
17812                    let telemetry = project.client().telemetry().clone();
17813                    let is_via_ssh = project.is_via_ssh();
17814                    (telemetry, is_via_ssh)
17815                };
17816                refresh_linked_ranges(self, window, cx);
17817                telemetry.log_edit_event("editor", is_via_ssh);
17818            }
17819            multi_buffer::Event::ExcerptsAdded {
17820                buffer,
17821                predecessor,
17822                excerpts,
17823            } => {
17824                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17825                let buffer_id = buffer.read(cx).remote_id();
17826                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17827                    if let Some(project) = &self.project {
17828                        update_uncommitted_diff_for_buffer(
17829                            cx.entity(),
17830                            project,
17831                            [buffer.clone()],
17832                            self.buffer.clone(),
17833                            cx,
17834                        )
17835                        .detach();
17836                    }
17837                }
17838                cx.emit(EditorEvent::ExcerptsAdded {
17839                    buffer: buffer.clone(),
17840                    predecessor: *predecessor,
17841                    excerpts: excerpts.clone(),
17842                });
17843                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17844            }
17845            multi_buffer::Event::ExcerptsRemoved {
17846                ids,
17847                removed_buffer_ids,
17848            } => {
17849                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17850                let buffer = self.buffer.read(cx);
17851                self.registered_buffers
17852                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17853                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17854                cx.emit(EditorEvent::ExcerptsRemoved {
17855                    ids: ids.clone(),
17856                    removed_buffer_ids: removed_buffer_ids.clone(),
17857                })
17858            }
17859            multi_buffer::Event::ExcerptsEdited {
17860                excerpt_ids,
17861                buffer_ids,
17862            } => {
17863                self.display_map.update(cx, |map, cx| {
17864                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17865                });
17866                cx.emit(EditorEvent::ExcerptsEdited {
17867                    ids: excerpt_ids.clone(),
17868                })
17869            }
17870            multi_buffer::Event::ExcerptsExpanded { ids } => {
17871                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17872                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17873            }
17874            multi_buffer::Event::Reparsed(buffer_id) => {
17875                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17876                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17877
17878                cx.emit(EditorEvent::Reparsed(*buffer_id));
17879            }
17880            multi_buffer::Event::DiffHunksToggled => {
17881                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17882            }
17883            multi_buffer::Event::LanguageChanged(buffer_id) => {
17884                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17885                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17886                cx.emit(EditorEvent::Reparsed(*buffer_id));
17887                cx.notify();
17888            }
17889            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17890            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17891            multi_buffer::Event::FileHandleChanged
17892            | multi_buffer::Event::Reloaded
17893            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17894            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17895            multi_buffer::Event::DiagnosticsUpdated => {
17896                self.refresh_active_diagnostics(cx);
17897                self.refresh_inline_diagnostics(true, window, cx);
17898                self.scrollbar_marker_state.dirty = true;
17899                cx.notify();
17900            }
17901            _ => {}
17902        };
17903    }
17904
17905    pub fn start_temporary_diff_override(&mut self) {
17906        self.load_diff_task.take();
17907        self.temporary_diff_override = true;
17908    }
17909
17910    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17911        self.temporary_diff_override = false;
17912        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17913        self.buffer.update(cx, |buffer, cx| {
17914            buffer.set_all_diff_hunks_collapsed(cx);
17915        });
17916
17917        if let Some(project) = self.project.clone() {
17918            self.load_diff_task = Some(
17919                update_uncommitted_diff_for_buffer(
17920                    cx.entity(),
17921                    &project,
17922                    self.buffer.read(cx).all_buffers(),
17923                    self.buffer.clone(),
17924                    cx,
17925                )
17926                .shared(),
17927            );
17928        }
17929    }
17930
17931    fn on_display_map_changed(
17932        &mut self,
17933        _: Entity<DisplayMap>,
17934        _: &mut Window,
17935        cx: &mut Context<Self>,
17936    ) {
17937        cx.notify();
17938    }
17939
17940    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17941        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17942        self.update_edit_prediction_settings(cx);
17943        self.refresh_inline_completion(true, false, window, cx);
17944        self.refresh_inlay_hints(
17945            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17946                self.selections.newest_anchor().head(),
17947                &self.buffer.read(cx).snapshot(cx),
17948                cx,
17949            )),
17950            cx,
17951        );
17952
17953        let old_cursor_shape = self.cursor_shape;
17954
17955        {
17956            let editor_settings = EditorSettings::get_global(cx);
17957            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17958            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17959            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17960            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17961        }
17962
17963        if old_cursor_shape != self.cursor_shape {
17964            cx.emit(EditorEvent::CursorShapeChanged);
17965        }
17966
17967        let project_settings = ProjectSettings::get_global(cx);
17968        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17969
17970        if self.mode.is_full() {
17971            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17972            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17973            if self.show_inline_diagnostics != show_inline_diagnostics {
17974                self.show_inline_diagnostics = show_inline_diagnostics;
17975                self.refresh_inline_diagnostics(false, window, cx);
17976            }
17977
17978            if self.git_blame_inline_enabled != inline_blame_enabled {
17979                self.toggle_git_blame_inline_internal(false, window, cx);
17980            }
17981        }
17982
17983        cx.notify();
17984    }
17985
17986    pub fn set_searchable(&mut self, searchable: bool) {
17987        self.searchable = searchable;
17988    }
17989
17990    pub fn searchable(&self) -> bool {
17991        self.searchable
17992    }
17993
17994    fn open_proposed_changes_editor(
17995        &mut self,
17996        _: &OpenProposedChangesEditor,
17997        window: &mut Window,
17998        cx: &mut Context<Self>,
17999    ) {
18000        let Some(workspace) = self.workspace() else {
18001            cx.propagate();
18002            return;
18003        };
18004
18005        let selections = self.selections.all::<usize>(cx);
18006        let multi_buffer = self.buffer.read(cx);
18007        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18008        let mut new_selections_by_buffer = HashMap::default();
18009        for selection in selections {
18010            for (buffer, range, _) in
18011                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18012            {
18013                let mut range = range.to_point(buffer);
18014                range.start.column = 0;
18015                range.end.column = buffer.line_len(range.end.row);
18016                new_selections_by_buffer
18017                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18018                    .or_insert(Vec::new())
18019                    .push(range)
18020            }
18021        }
18022
18023        let proposed_changes_buffers = new_selections_by_buffer
18024            .into_iter()
18025            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18026            .collect::<Vec<_>>();
18027        let proposed_changes_editor = cx.new(|cx| {
18028            ProposedChangesEditor::new(
18029                "Proposed changes",
18030                proposed_changes_buffers,
18031                self.project.clone(),
18032                window,
18033                cx,
18034            )
18035        });
18036
18037        window.defer(cx, move |window, cx| {
18038            workspace.update(cx, |workspace, cx| {
18039                workspace.active_pane().update(cx, |pane, cx| {
18040                    pane.add_item(
18041                        Box::new(proposed_changes_editor),
18042                        true,
18043                        true,
18044                        None,
18045                        window,
18046                        cx,
18047                    );
18048                });
18049            });
18050        });
18051    }
18052
18053    pub fn open_excerpts_in_split(
18054        &mut self,
18055        _: &OpenExcerptsSplit,
18056        window: &mut Window,
18057        cx: &mut Context<Self>,
18058    ) {
18059        self.open_excerpts_common(None, true, window, cx)
18060    }
18061
18062    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18063        self.open_excerpts_common(None, false, window, cx)
18064    }
18065
18066    fn open_excerpts_common(
18067        &mut self,
18068        jump_data: Option<JumpData>,
18069        split: bool,
18070        window: &mut Window,
18071        cx: &mut Context<Self>,
18072    ) {
18073        let Some(workspace) = self.workspace() else {
18074            cx.propagate();
18075            return;
18076        };
18077
18078        if self.buffer.read(cx).is_singleton() {
18079            cx.propagate();
18080            return;
18081        }
18082
18083        let mut new_selections_by_buffer = HashMap::default();
18084        match &jump_data {
18085            Some(JumpData::MultiBufferPoint {
18086                excerpt_id,
18087                position,
18088                anchor,
18089                line_offset_from_top,
18090            }) => {
18091                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18092                if let Some(buffer) = multi_buffer_snapshot
18093                    .buffer_id_for_excerpt(*excerpt_id)
18094                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18095                {
18096                    let buffer_snapshot = buffer.read(cx).snapshot();
18097                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18098                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18099                    } else {
18100                        buffer_snapshot.clip_point(*position, Bias::Left)
18101                    };
18102                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18103                    new_selections_by_buffer.insert(
18104                        buffer,
18105                        (
18106                            vec![jump_to_offset..jump_to_offset],
18107                            Some(*line_offset_from_top),
18108                        ),
18109                    );
18110                }
18111            }
18112            Some(JumpData::MultiBufferRow {
18113                row,
18114                line_offset_from_top,
18115            }) => {
18116                let point = MultiBufferPoint::new(row.0, 0);
18117                if let Some((buffer, buffer_point, _)) =
18118                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18119                {
18120                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18121                    new_selections_by_buffer
18122                        .entry(buffer)
18123                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18124                        .0
18125                        .push(buffer_offset..buffer_offset)
18126                }
18127            }
18128            None => {
18129                let selections = self.selections.all::<usize>(cx);
18130                let multi_buffer = self.buffer.read(cx);
18131                for selection in selections {
18132                    for (snapshot, range, _, anchor) in multi_buffer
18133                        .snapshot(cx)
18134                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18135                    {
18136                        if let Some(anchor) = anchor {
18137                            // selection is in a deleted hunk
18138                            let Some(buffer_id) = anchor.buffer_id else {
18139                                continue;
18140                            };
18141                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18142                                continue;
18143                            };
18144                            let offset = text::ToOffset::to_offset(
18145                                &anchor.text_anchor,
18146                                &buffer_handle.read(cx).snapshot(),
18147                            );
18148                            let range = offset..offset;
18149                            new_selections_by_buffer
18150                                .entry(buffer_handle)
18151                                .or_insert((Vec::new(), None))
18152                                .0
18153                                .push(range)
18154                        } else {
18155                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18156                            else {
18157                                continue;
18158                            };
18159                            new_selections_by_buffer
18160                                .entry(buffer_handle)
18161                                .or_insert((Vec::new(), None))
18162                                .0
18163                                .push(range)
18164                        }
18165                    }
18166                }
18167            }
18168        }
18169
18170        new_selections_by_buffer
18171            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18172
18173        if new_selections_by_buffer.is_empty() {
18174            return;
18175        }
18176
18177        // We defer the pane interaction because we ourselves are a workspace item
18178        // and activating a new item causes the pane to call a method on us reentrantly,
18179        // which panics if we're on the stack.
18180        window.defer(cx, move |window, cx| {
18181            workspace.update(cx, |workspace, cx| {
18182                let pane = if split {
18183                    workspace.adjacent_pane(window, cx)
18184                } else {
18185                    workspace.active_pane().clone()
18186                };
18187
18188                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18189                    let editor = buffer
18190                        .read(cx)
18191                        .file()
18192                        .is_none()
18193                        .then(|| {
18194                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18195                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18196                            // Instead, we try to activate the existing editor in the pane first.
18197                            let (editor, pane_item_index) =
18198                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18199                                    let editor = item.downcast::<Editor>()?;
18200                                    let singleton_buffer =
18201                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18202                                    if singleton_buffer == buffer {
18203                                        Some((editor, i))
18204                                    } else {
18205                                        None
18206                                    }
18207                                })?;
18208                            pane.update(cx, |pane, cx| {
18209                                pane.activate_item(pane_item_index, true, true, window, cx)
18210                            });
18211                            Some(editor)
18212                        })
18213                        .flatten()
18214                        .unwrap_or_else(|| {
18215                            workspace.open_project_item::<Self>(
18216                                pane.clone(),
18217                                buffer,
18218                                true,
18219                                true,
18220                                window,
18221                                cx,
18222                            )
18223                        });
18224
18225                    editor.update(cx, |editor, cx| {
18226                        let autoscroll = match scroll_offset {
18227                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18228                            None => Autoscroll::newest(),
18229                        };
18230                        let nav_history = editor.nav_history.take();
18231                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18232                            s.select_ranges(ranges);
18233                        });
18234                        editor.nav_history = nav_history;
18235                    });
18236                }
18237            })
18238        });
18239    }
18240
18241    // For now, don't allow opening excerpts in buffers that aren't backed by
18242    // regular project files.
18243    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18244        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18245    }
18246
18247    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18248        let snapshot = self.buffer.read(cx).read(cx);
18249        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18250        Some(
18251            ranges
18252                .iter()
18253                .map(move |range| {
18254                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18255                })
18256                .collect(),
18257        )
18258    }
18259
18260    fn selection_replacement_ranges(
18261        &self,
18262        range: Range<OffsetUtf16>,
18263        cx: &mut App,
18264    ) -> Vec<Range<OffsetUtf16>> {
18265        let selections = self.selections.all::<OffsetUtf16>(cx);
18266        let newest_selection = selections
18267            .iter()
18268            .max_by_key(|selection| selection.id)
18269            .unwrap();
18270        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18271        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18272        let snapshot = self.buffer.read(cx).read(cx);
18273        selections
18274            .into_iter()
18275            .map(|mut selection| {
18276                selection.start.0 =
18277                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18278                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18279                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18280                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18281            })
18282            .collect()
18283    }
18284
18285    fn report_editor_event(
18286        &self,
18287        event_type: &'static str,
18288        file_extension: Option<String>,
18289        cx: &App,
18290    ) {
18291        if cfg!(any(test, feature = "test-support")) {
18292            return;
18293        }
18294
18295        let Some(project) = &self.project else { return };
18296
18297        // If None, we are in a file without an extension
18298        let file = self
18299            .buffer
18300            .read(cx)
18301            .as_singleton()
18302            .and_then(|b| b.read(cx).file());
18303        let file_extension = file_extension.or(file
18304            .as_ref()
18305            .and_then(|file| Path::new(file.file_name(cx)).extension())
18306            .and_then(|e| e.to_str())
18307            .map(|a| a.to_string()));
18308
18309        let vim_mode = vim_enabled(cx);
18310
18311        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18312        let copilot_enabled = edit_predictions_provider
18313            == language::language_settings::EditPredictionProvider::Copilot;
18314        let copilot_enabled_for_language = self
18315            .buffer
18316            .read(cx)
18317            .language_settings(cx)
18318            .show_edit_predictions;
18319
18320        let project = project.read(cx);
18321        telemetry::event!(
18322            event_type,
18323            file_extension,
18324            vim_mode,
18325            copilot_enabled,
18326            copilot_enabled_for_language,
18327            edit_predictions_provider,
18328            is_via_ssh = project.is_via_ssh(),
18329        );
18330    }
18331
18332    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18333    /// with each line being an array of {text, highlight} objects.
18334    fn copy_highlight_json(
18335        &mut self,
18336        _: &CopyHighlightJson,
18337        window: &mut Window,
18338        cx: &mut Context<Self>,
18339    ) {
18340        #[derive(Serialize)]
18341        struct Chunk<'a> {
18342            text: String,
18343            highlight: Option<&'a str>,
18344        }
18345
18346        let snapshot = self.buffer.read(cx).snapshot(cx);
18347        let range = self
18348            .selected_text_range(false, window, cx)
18349            .and_then(|selection| {
18350                if selection.range.is_empty() {
18351                    None
18352                } else {
18353                    Some(selection.range)
18354                }
18355            })
18356            .unwrap_or_else(|| 0..snapshot.len());
18357
18358        let chunks = snapshot.chunks(range, true);
18359        let mut lines = Vec::new();
18360        let mut line: VecDeque<Chunk> = VecDeque::new();
18361
18362        let Some(style) = self.style.as_ref() else {
18363            return;
18364        };
18365
18366        for chunk in chunks {
18367            let highlight = chunk
18368                .syntax_highlight_id
18369                .and_then(|id| id.name(&style.syntax));
18370            let mut chunk_lines = chunk.text.split('\n').peekable();
18371            while let Some(text) = chunk_lines.next() {
18372                let mut merged_with_last_token = false;
18373                if let Some(last_token) = line.back_mut() {
18374                    if last_token.highlight == highlight {
18375                        last_token.text.push_str(text);
18376                        merged_with_last_token = true;
18377                    }
18378                }
18379
18380                if !merged_with_last_token {
18381                    line.push_back(Chunk {
18382                        text: text.into(),
18383                        highlight,
18384                    });
18385                }
18386
18387                if chunk_lines.peek().is_some() {
18388                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18389                        line.pop_front();
18390                    }
18391                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18392                        line.pop_back();
18393                    }
18394
18395                    lines.push(mem::take(&mut line));
18396                }
18397            }
18398        }
18399
18400        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18401            return;
18402        };
18403        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18404    }
18405
18406    pub fn open_context_menu(
18407        &mut self,
18408        _: &OpenContextMenu,
18409        window: &mut Window,
18410        cx: &mut Context<Self>,
18411    ) {
18412        self.request_autoscroll(Autoscroll::newest(), cx);
18413        let position = self.selections.newest_display(cx).start;
18414        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18415    }
18416
18417    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18418        &self.inlay_hint_cache
18419    }
18420
18421    pub fn replay_insert_event(
18422        &mut self,
18423        text: &str,
18424        relative_utf16_range: Option<Range<isize>>,
18425        window: &mut Window,
18426        cx: &mut Context<Self>,
18427    ) {
18428        if !self.input_enabled {
18429            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18430            return;
18431        }
18432        if let Some(relative_utf16_range) = relative_utf16_range {
18433            let selections = self.selections.all::<OffsetUtf16>(cx);
18434            self.change_selections(None, window, cx, |s| {
18435                let new_ranges = selections.into_iter().map(|range| {
18436                    let start = OffsetUtf16(
18437                        range
18438                            .head()
18439                            .0
18440                            .saturating_add_signed(relative_utf16_range.start),
18441                    );
18442                    let end = OffsetUtf16(
18443                        range
18444                            .head()
18445                            .0
18446                            .saturating_add_signed(relative_utf16_range.end),
18447                    );
18448                    start..end
18449                });
18450                s.select_ranges(new_ranges);
18451            });
18452        }
18453
18454        self.handle_input(text, window, cx);
18455    }
18456
18457    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18458        let Some(provider) = self.semantics_provider.as_ref() else {
18459            return false;
18460        };
18461
18462        let mut supports = false;
18463        self.buffer().update(cx, |this, cx| {
18464            this.for_each_buffer(|buffer| {
18465                supports |= provider.supports_inlay_hints(buffer, cx);
18466            });
18467        });
18468
18469        supports
18470    }
18471
18472    pub fn is_focused(&self, window: &Window) -> bool {
18473        self.focus_handle.is_focused(window)
18474    }
18475
18476    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18477        cx.emit(EditorEvent::Focused);
18478
18479        if let Some(descendant) = self
18480            .last_focused_descendant
18481            .take()
18482            .and_then(|descendant| descendant.upgrade())
18483        {
18484            window.focus(&descendant);
18485        } else {
18486            if let Some(blame) = self.blame.as_ref() {
18487                blame.update(cx, GitBlame::focus)
18488            }
18489
18490            self.blink_manager.update(cx, BlinkManager::enable);
18491            self.show_cursor_names(window, cx);
18492            self.buffer.update(cx, |buffer, cx| {
18493                buffer.finalize_last_transaction(cx);
18494                if self.leader_id.is_none() {
18495                    buffer.set_active_selections(
18496                        &self.selections.disjoint_anchors(),
18497                        self.selections.line_mode,
18498                        self.cursor_shape,
18499                        cx,
18500                    );
18501                }
18502            });
18503        }
18504    }
18505
18506    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18507        cx.emit(EditorEvent::FocusedIn)
18508    }
18509
18510    fn handle_focus_out(
18511        &mut self,
18512        event: FocusOutEvent,
18513        _window: &mut Window,
18514        cx: &mut Context<Self>,
18515    ) {
18516        if event.blurred != self.focus_handle {
18517            self.last_focused_descendant = Some(event.blurred);
18518        }
18519        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18520    }
18521
18522    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18523        self.blink_manager.update(cx, BlinkManager::disable);
18524        self.buffer
18525            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18526
18527        if let Some(blame) = self.blame.as_ref() {
18528            blame.update(cx, GitBlame::blur)
18529        }
18530        if !self.hover_state.focused(window, cx) {
18531            hide_hover(self, cx);
18532        }
18533        if !self
18534            .context_menu
18535            .borrow()
18536            .as_ref()
18537            .is_some_and(|context_menu| context_menu.focused(window, cx))
18538        {
18539            self.hide_context_menu(window, cx);
18540        }
18541        self.discard_inline_completion(false, cx);
18542        cx.emit(EditorEvent::Blurred);
18543        cx.notify();
18544    }
18545
18546    pub fn register_action<A: Action>(
18547        &mut self,
18548        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18549    ) -> Subscription {
18550        let id = self.next_editor_action_id.post_inc();
18551        let listener = Arc::new(listener);
18552        self.editor_actions.borrow_mut().insert(
18553            id,
18554            Box::new(move |window, _| {
18555                let listener = listener.clone();
18556                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18557                    let action = action.downcast_ref().unwrap();
18558                    if phase == DispatchPhase::Bubble {
18559                        listener(action, window, cx)
18560                    }
18561                })
18562            }),
18563        );
18564
18565        let editor_actions = self.editor_actions.clone();
18566        Subscription::new(move || {
18567            editor_actions.borrow_mut().remove(&id);
18568        })
18569    }
18570
18571    pub fn file_header_size(&self) -> u32 {
18572        FILE_HEADER_HEIGHT
18573    }
18574
18575    pub fn restore(
18576        &mut self,
18577        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18578        window: &mut Window,
18579        cx: &mut Context<Self>,
18580    ) {
18581        let workspace = self.workspace();
18582        let project = self.project.as_ref();
18583        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18584            let mut tasks = Vec::new();
18585            for (buffer_id, changes) in revert_changes {
18586                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18587                    buffer.update(cx, |buffer, cx| {
18588                        buffer.edit(
18589                            changes
18590                                .into_iter()
18591                                .map(|(range, text)| (range, text.to_string())),
18592                            None,
18593                            cx,
18594                        );
18595                    });
18596
18597                    if let Some(project) =
18598                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18599                    {
18600                        project.update(cx, |project, cx| {
18601                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18602                        })
18603                    }
18604                }
18605            }
18606            tasks
18607        });
18608        cx.spawn_in(window, async move |_, cx| {
18609            for (buffer, task) in save_tasks {
18610                let result = task.await;
18611                if result.is_err() {
18612                    let Some(path) = buffer
18613                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18614                        .ok()
18615                    else {
18616                        continue;
18617                    };
18618                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18619                        let Some(task) = cx
18620                            .update_window_entity(&workspace, |workspace, window, cx| {
18621                                workspace
18622                                    .open_path_preview(path, None, false, false, false, window, cx)
18623                            })
18624                            .ok()
18625                        else {
18626                            continue;
18627                        };
18628                        task.await.log_err();
18629                    }
18630                }
18631            }
18632        })
18633        .detach();
18634        self.change_selections(None, window, cx, |selections| selections.refresh());
18635    }
18636
18637    pub fn to_pixel_point(
18638        &self,
18639        source: multi_buffer::Anchor,
18640        editor_snapshot: &EditorSnapshot,
18641        window: &mut Window,
18642    ) -> Option<gpui::Point<Pixels>> {
18643        let source_point = source.to_display_point(editor_snapshot);
18644        self.display_to_pixel_point(source_point, editor_snapshot, window)
18645    }
18646
18647    pub fn display_to_pixel_point(
18648        &self,
18649        source: DisplayPoint,
18650        editor_snapshot: &EditorSnapshot,
18651        window: &mut Window,
18652    ) -> Option<gpui::Point<Pixels>> {
18653        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18654        let text_layout_details = self.text_layout_details(window);
18655        let scroll_top = text_layout_details
18656            .scroll_anchor
18657            .scroll_position(editor_snapshot)
18658            .y;
18659
18660        if source.row().as_f32() < scroll_top.floor() {
18661            return None;
18662        }
18663        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18664        let source_y = line_height * (source.row().as_f32() - scroll_top);
18665        Some(gpui::Point::new(source_x, source_y))
18666    }
18667
18668    pub fn has_visible_completions_menu(&self) -> bool {
18669        !self.edit_prediction_preview_is_active()
18670            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18671                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18672            })
18673    }
18674
18675    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18676        self.addons
18677            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18678    }
18679
18680    pub fn unregister_addon<T: Addon>(&mut self) {
18681        self.addons.remove(&std::any::TypeId::of::<T>());
18682    }
18683
18684    pub fn addon<T: Addon>(&self) -> Option<&T> {
18685        let type_id = std::any::TypeId::of::<T>();
18686        self.addons
18687            .get(&type_id)
18688            .and_then(|item| item.to_any().downcast_ref::<T>())
18689    }
18690
18691    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18692        let type_id = std::any::TypeId::of::<T>();
18693        self.addons
18694            .get_mut(&type_id)
18695            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18696    }
18697
18698    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18699        let text_layout_details = self.text_layout_details(window);
18700        let style = &text_layout_details.editor_style;
18701        let font_id = window.text_system().resolve_font(&style.text.font());
18702        let font_size = style.text.font_size.to_pixels(window.rem_size());
18703        let line_height = style.text.line_height_in_pixels(window.rem_size());
18704        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18705
18706        gpui::Size::new(em_width, line_height)
18707    }
18708
18709    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18710        self.load_diff_task.clone()
18711    }
18712
18713    fn read_metadata_from_db(
18714        &mut self,
18715        item_id: u64,
18716        workspace_id: WorkspaceId,
18717        window: &mut Window,
18718        cx: &mut Context<Editor>,
18719    ) {
18720        if self.is_singleton(cx)
18721            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18722        {
18723            let buffer_snapshot = OnceCell::new();
18724
18725            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18726                if !folds.is_empty() {
18727                    let snapshot =
18728                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18729                    self.fold_ranges(
18730                        folds
18731                            .into_iter()
18732                            .map(|(start, end)| {
18733                                snapshot.clip_offset(start, Bias::Left)
18734                                    ..snapshot.clip_offset(end, Bias::Right)
18735                            })
18736                            .collect(),
18737                        false,
18738                        window,
18739                        cx,
18740                    );
18741                }
18742            }
18743
18744            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18745                if !selections.is_empty() {
18746                    let snapshot =
18747                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18748                    self.change_selections(None, window, cx, |s| {
18749                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18750                            snapshot.clip_offset(start, Bias::Left)
18751                                ..snapshot.clip_offset(end, Bias::Right)
18752                        }));
18753                    });
18754                }
18755            };
18756        }
18757
18758        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18759    }
18760}
18761
18762fn vim_enabled(cx: &App) -> bool {
18763    cx.global::<SettingsStore>()
18764        .raw_user_settings()
18765        .get("vim_mode")
18766        == Some(&serde_json::Value::Bool(true))
18767}
18768
18769// Consider user intent and default settings
18770fn choose_completion_range(
18771    completion: &Completion,
18772    intent: CompletionIntent,
18773    buffer: &Entity<Buffer>,
18774    cx: &mut Context<Editor>,
18775) -> Range<usize> {
18776    fn should_replace(
18777        completion: &Completion,
18778        insert_range: &Range<text::Anchor>,
18779        intent: CompletionIntent,
18780        completion_mode_setting: LspInsertMode,
18781        buffer: &Buffer,
18782    ) -> bool {
18783        // specific actions take precedence over settings
18784        match intent {
18785            CompletionIntent::CompleteWithInsert => return false,
18786            CompletionIntent::CompleteWithReplace => return true,
18787            CompletionIntent::Complete | CompletionIntent::Compose => {}
18788        }
18789
18790        match completion_mode_setting {
18791            LspInsertMode::Insert => false,
18792            LspInsertMode::Replace => true,
18793            LspInsertMode::ReplaceSubsequence => {
18794                let mut text_to_replace = buffer.chars_for_range(
18795                    buffer.anchor_before(completion.replace_range.start)
18796                        ..buffer.anchor_after(completion.replace_range.end),
18797                );
18798                let mut completion_text = completion.new_text.chars();
18799
18800                // is `text_to_replace` a subsequence of `completion_text`
18801                text_to_replace
18802                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18803            }
18804            LspInsertMode::ReplaceSuffix => {
18805                let range_after_cursor = insert_range.end..completion.replace_range.end;
18806
18807                let text_after_cursor = buffer
18808                    .text_for_range(
18809                        buffer.anchor_before(range_after_cursor.start)
18810                            ..buffer.anchor_after(range_after_cursor.end),
18811                    )
18812                    .collect::<String>();
18813                completion.new_text.ends_with(&text_after_cursor)
18814            }
18815        }
18816    }
18817
18818    let buffer = buffer.read(cx);
18819
18820    if let CompletionSource::Lsp {
18821        insert_range: Some(insert_range),
18822        ..
18823    } = &completion.source
18824    {
18825        let completion_mode_setting =
18826            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18827                .completions
18828                .lsp_insert_mode;
18829
18830        if !should_replace(
18831            completion,
18832            &insert_range,
18833            intent,
18834            completion_mode_setting,
18835            buffer,
18836        ) {
18837            return insert_range.to_offset(buffer);
18838        }
18839    }
18840
18841    completion.replace_range.to_offset(buffer)
18842}
18843
18844fn insert_extra_newline_brackets(
18845    buffer: &MultiBufferSnapshot,
18846    range: Range<usize>,
18847    language: &language::LanguageScope,
18848) -> bool {
18849    let leading_whitespace_len = buffer
18850        .reversed_chars_at(range.start)
18851        .take_while(|c| c.is_whitespace() && *c != '\n')
18852        .map(|c| c.len_utf8())
18853        .sum::<usize>();
18854    let trailing_whitespace_len = buffer
18855        .chars_at(range.end)
18856        .take_while(|c| c.is_whitespace() && *c != '\n')
18857        .map(|c| c.len_utf8())
18858        .sum::<usize>();
18859    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18860
18861    language.brackets().any(|(pair, enabled)| {
18862        let pair_start = pair.start.trim_end();
18863        let pair_end = pair.end.trim_start();
18864
18865        enabled
18866            && pair.newline
18867            && buffer.contains_str_at(range.end, pair_end)
18868            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18869    })
18870}
18871
18872fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18873    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18874        [(buffer, range, _)] => (*buffer, range.clone()),
18875        _ => return false,
18876    };
18877    let pair = {
18878        let mut result: Option<BracketMatch> = None;
18879
18880        for pair in buffer
18881            .all_bracket_ranges(range.clone())
18882            .filter(move |pair| {
18883                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18884            })
18885        {
18886            let len = pair.close_range.end - pair.open_range.start;
18887
18888            if let Some(existing) = &result {
18889                let existing_len = existing.close_range.end - existing.open_range.start;
18890                if len > existing_len {
18891                    continue;
18892                }
18893            }
18894
18895            result = Some(pair);
18896        }
18897
18898        result
18899    };
18900    let Some(pair) = pair else {
18901        return false;
18902    };
18903    pair.newline_only
18904        && buffer
18905            .chars_for_range(pair.open_range.end..range.start)
18906            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18907            .all(|c| c.is_whitespace() && c != '\n')
18908}
18909
18910fn update_uncommitted_diff_for_buffer(
18911    editor: Entity<Editor>,
18912    project: &Entity<Project>,
18913    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18914    buffer: Entity<MultiBuffer>,
18915    cx: &mut App,
18916) -> Task<()> {
18917    let mut tasks = Vec::new();
18918    project.update(cx, |project, cx| {
18919        for buffer in buffers {
18920            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18921                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18922            }
18923        }
18924    });
18925    cx.spawn(async move |cx| {
18926        let diffs = future::join_all(tasks).await;
18927        if editor
18928            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18929            .unwrap_or(false)
18930        {
18931            return;
18932        }
18933
18934        buffer
18935            .update(cx, |buffer, cx| {
18936                for diff in diffs.into_iter().flatten() {
18937                    buffer.add_diff(diff, cx);
18938                }
18939            })
18940            .ok();
18941    })
18942}
18943
18944fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18945    let tab_size = tab_size.get() as usize;
18946    let mut width = offset;
18947
18948    for ch in text.chars() {
18949        width += if ch == '\t' {
18950            tab_size - (width % tab_size)
18951        } else {
18952            1
18953        };
18954    }
18955
18956    width - offset
18957}
18958
18959#[cfg(test)]
18960mod tests {
18961    use super::*;
18962
18963    #[test]
18964    fn test_string_size_with_expanded_tabs() {
18965        let nz = |val| NonZeroU32::new(val).unwrap();
18966        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18967        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18968        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18969        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18970        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18971        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18972        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18973        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18974    }
18975}
18976
18977/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18978struct WordBreakingTokenizer<'a> {
18979    input: &'a str,
18980}
18981
18982impl<'a> WordBreakingTokenizer<'a> {
18983    fn new(input: &'a str) -> Self {
18984        Self { input }
18985    }
18986}
18987
18988fn is_char_ideographic(ch: char) -> bool {
18989    use unicode_script::Script::*;
18990    use unicode_script::UnicodeScript;
18991    matches!(ch.script(), Han | Tangut | Yi)
18992}
18993
18994fn is_grapheme_ideographic(text: &str) -> bool {
18995    text.chars().any(is_char_ideographic)
18996}
18997
18998fn is_grapheme_whitespace(text: &str) -> bool {
18999    text.chars().any(|x| x.is_whitespace())
19000}
19001
19002fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19003    text.chars().next().map_or(false, |ch| {
19004        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19005    })
19006}
19007
19008#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19009enum WordBreakToken<'a> {
19010    Word { token: &'a str, grapheme_len: usize },
19011    InlineWhitespace { token: &'a str, grapheme_len: usize },
19012    Newline,
19013}
19014
19015impl<'a> Iterator for WordBreakingTokenizer<'a> {
19016    /// Yields a span, the count of graphemes in the token, and whether it was
19017    /// whitespace. Note that it also breaks at word boundaries.
19018    type Item = WordBreakToken<'a>;
19019
19020    fn next(&mut self) -> Option<Self::Item> {
19021        use unicode_segmentation::UnicodeSegmentation;
19022        if self.input.is_empty() {
19023            return None;
19024        }
19025
19026        let mut iter = self.input.graphemes(true).peekable();
19027        let mut offset = 0;
19028        let mut grapheme_len = 0;
19029        if let Some(first_grapheme) = iter.next() {
19030            let is_newline = first_grapheme == "\n";
19031            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19032            offset += first_grapheme.len();
19033            grapheme_len += 1;
19034            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19035                if let Some(grapheme) = iter.peek().copied() {
19036                    if should_stay_with_preceding_ideograph(grapheme) {
19037                        offset += grapheme.len();
19038                        grapheme_len += 1;
19039                    }
19040                }
19041            } else {
19042                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19043                let mut next_word_bound = words.peek().copied();
19044                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19045                    next_word_bound = words.next();
19046                }
19047                while let Some(grapheme) = iter.peek().copied() {
19048                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19049                        break;
19050                    };
19051                    if is_grapheme_whitespace(grapheme) != is_whitespace
19052                        || (grapheme == "\n") != is_newline
19053                    {
19054                        break;
19055                    };
19056                    offset += grapheme.len();
19057                    grapheme_len += 1;
19058                    iter.next();
19059                }
19060            }
19061            let token = &self.input[..offset];
19062            self.input = &self.input[offset..];
19063            if token == "\n" {
19064                Some(WordBreakToken::Newline)
19065            } else if is_whitespace {
19066                Some(WordBreakToken::InlineWhitespace {
19067                    token,
19068                    grapheme_len,
19069                })
19070            } else {
19071                Some(WordBreakToken::Word {
19072                    token,
19073                    grapheme_len,
19074                })
19075            }
19076        } else {
19077            None
19078        }
19079    }
19080}
19081
19082#[test]
19083fn test_word_breaking_tokenizer() {
19084    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19085        ("", &[]),
19086        ("  ", &[whitespace("  ", 2)]),
19087        ("Ʒ", &[word("Ʒ", 1)]),
19088        ("Ǽ", &[word("Ǽ", 1)]),
19089        ("", &[word("", 1)]),
19090        ("⋑⋑", &[word("⋑⋑", 2)]),
19091        (
19092            "原理,进而",
19093            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19094        ),
19095        (
19096            "hello world",
19097            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19098        ),
19099        (
19100            "hello, world",
19101            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19102        ),
19103        (
19104            "  hello world",
19105            &[
19106                whitespace("  ", 2),
19107                word("hello", 5),
19108                whitespace(" ", 1),
19109                word("world", 5),
19110            ],
19111        ),
19112        (
19113            "这是什么 \n 钢笔",
19114            &[
19115                word("", 1),
19116                word("", 1),
19117                word("", 1),
19118                word("", 1),
19119                whitespace(" ", 1),
19120                newline(),
19121                whitespace(" ", 1),
19122                word("", 1),
19123                word("", 1),
19124            ],
19125        ),
19126        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19127    ];
19128
19129    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19130        WordBreakToken::Word {
19131            token,
19132            grapheme_len,
19133        }
19134    }
19135
19136    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19137        WordBreakToken::InlineWhitespace {
19138            token,
19139            grapheme_len,
19140        }
19141    }
19142
19143    fn newline() -> WordBreakToken<'static> {
19144        WordBreakToken::Newline
19145    }
19146
19147    for (input, result) in tests {
19148        assert_eq!(
19149            WordBreakingTokenizer::new(input)
19150                .collect::<Vec<_>>()
19151                .as_slice(),
19152            *result,
19153        );
19154    }
19155}
19156
19157fn wrap_with_prefix(
19158    line_prefix: String,
19159    unwrapped_text: String,
19160    wrap_column: usize,
19161    tab_size: NonZeroU32,
19162    preserve_existing_whitespace: bool,
19163) -> String {
19164    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19165    let mut wrapped_text = String::new();
19166    let mut current_line = line_prefix.clone();
19167
19168    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19169    let mut current_line_len = line_prefix_len;
19170    let mut in_whitespace = false;
19171    for token in tokenizer {
19172        let have_preceding_whitespace = in_whitespace;
19173        match token {
19174            WordBreakToken::Word {
19175                token,
19176                grapheme_len,
19177            } => {
19178                in_whitespace = false;
19179                if current_line_len + grapheme_len > wrap_column
19180                    && current_line_len != line_prefix_len
19181                {
19182                    wrapped_text.push_str(current_line.trim_end());
19183                    wrapped_text.push('\n');
19184                    current_line.truncate(line_prefix.len());
19185                    current_line_len = line_prefix_len;
19186                }
19187                current_line.push_str(token);
19188                current_line_len += grapheme_len;
19189            }
19190            WordBreakToken::InlineWhitespace {
19191                mut token,
19192                mut grapheme_len,
19193            } => {
19194                in_whitespace = true;
19195                if have_preceding_whitespace && !preserve_existing_whitespace {
19196                    continue;
19197                }
19198                if !preserve_existing_whitespace {
19199                    token = " ";
19200                    grapheme_len = 1;
19201                }
19202                if current_line_len + grapheme_len > wrap_column {
19203                    wrapped_text.push_str(current_line.trim_end());
19204                    wrapped_text.push('\n');
19205                    current_line.truncate(line_prefix.len());
19206                    current_line_len = line_prefix_len;
19207                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19208                    current_line.push_str(token);
19209                    current_line_len += grapheme_len;
19210                }
19211            }
19212            WordBreakToken::Newline => {
19213                in_whitespace = true;
19214                if preserve_existing_whitespace {
19215                    wrapped_text.push_str(current_line.trim_end());
19216                    wrapped_text.push('\n');
19217                    current_line.truncate(line_prefix.len());
19218                    current_line_len = line_prefix_len;
19219                } else if have_preceding_whitespace {
19220                    continue;
19221                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19222                {
19223                    wrapped_text.push_str(current_line.trim_end());
19224                    wrapped_text.push('\n');
19225                    current_line.truncate(line_prefix.len());
19226                    current_line_len = line_prefix_len;
19227                } else if current_line_len != line_prefix_len {
19228                    current_line.push(' ');
19229                    current_line_len += 1;
19230                }
19231            }
19232        }
19233    }
19234
19235    if !current_line.is_empty() {
19236        wrapped_text.push_str(&current_line);
19237    }
19238    wrapped_text
19239}
19240
19241#[test]
19242fn test_wrap_with_prefix() {
19243    assert_eq!(
19244        wrap_with_prefix(
19245            "# ".to_string(),
19246            "abcdefg".to_string(),
19247            4,
19248            NonZeroU32::new(4).unwrap(),
19249            false,
19250        ),
19251        "# abcdefg"
19252    );
19253    assert_eq!(
19254        wrap_with_prefix(
19255            "".to_string(),
19256            "\thello world".to_string(),
19257            8,
19258            NonZeroU32::new(4).unwrap(),
19259            false,
19260        ),
19261        "hello\nworld"
19262    );
19263    assert_eq!(
19264        wrap_with_prefix(
19265            "// ".to_string(),
19266            "xx \nyy zz aa bb cc".to_string(),
19267            12,
19268            NonZeroU32::new(4).unwrap(),
19269            false,
19270        ),
19271        "// xx yy zz\n// aa bb cc"
19272    );
19273    assert_eq!(
19274        wrap_with_prefix(
19275            String::new(),
19276            "这是什么 \n 钢笔".to_string(),
19277            3,
19278            NonZeroU32::new(4).unwrap(),
19279            false,
19280        ),
19281        "这是什\n么 钢\n"
19282    );
19283}
19284
19285pub trait CollaborationHub {
19286    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19287    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19288    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19289}
19290
19291impl CollaborationHub for Entity<Project> {
19292    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19293        self.read(cx).collaborators()
19294    }
19295
19296    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19297        self.read(cx).user_store().read(cx).participant_indices()
19298    }
19299
19300    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19301        let this = self.read(cx);
19302        let user_ids = this.collaborators().values().map(|c| c.user_id);
19303        this.user_store().read_with(cx, |user_store, cx| {
19304            user_store.participant_names(user_ids, cx)
19305        })
19306    }
19307}
19308
19309pub trait SemanticsProvider {
19310    fn hover(
19311        &self,
19312        buffer: &Entity<Buffer>,
19313        position: text::Anchor,
19314        cx: &mut App,
19315    ) -> Option<Task<Vec<project::Hover>>>;
19316
19317    fn inline_values(
19318        &self,
19319        buffer_handle: Entity<Buffer>,
19320        range: Range<text::Anchor>,
19321        cx: &mut App,
19322    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19323
19324    fn inlay_hints(
19325        &self,
19326        buffer_handle: Entity<Buffer>,
19327        range: Range<text::Anchor>,
19328        cx: &mut App,
19329    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19330
19331    fn resolve_inlay_hint(
19332        &self,
19333        hint: InlayHint,
19334        buffer_handle: Entity<Buffer>,
19335        server_id: LanguageServerId,
19336        cx: &mut App,
19337    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19338
19339    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19340
19341    fn document_highlights(
19342        &self,
19343        buffer: &Entity<Buffer>,
19344        position: text::Anchor,
19345        cx: &mut App,
19346    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19347
19348    fn definitions(
19349        &self,
19350        buffer: &Entity<Buffer>,
19351        position: text::Anchor,
19352        kind: GotoDefinitionKind,
19353        cx: &mut App,
19354    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19355
19356    fn range_for_rename(
19357        &self,
19358        buffer: &Entity<Buffer>,
19359        position: text::Anchor,
19360        cx: &mut App,
19361    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19362
19363    fn perform_rename(
19364        &self,
19365        buffer: &Entity<Buffer>,
19366        position: text::Anchor,
19367        new_name: String,
19368        cx: &mut App,
19369    ) -> Option<Task<Result<ProjectTransaction>>>;
19370}
19371
19372pub trait CompletionProvider {
19373    fn completions(
19374        &self,
19375        excerpt_id: ExcerptId,
19376        buffer: &Entity<Buffer>,
19377        buffer_position: text::Anchor,
19378        trigger: CompletionContext,
19379        window: &mut Window,
19380        cx: &mut Context<Editor>,
19381    ) -> Task<Result<Option<Vec<Completion>>>>;
19382
19383    fn resolve_completions(
19384        &self,
19385        buffer: Entity<Buffer>,
19386        completion_indices: Vec<usize>,
19387        completions: Rc<RefCell<Box<[Completion]>>>,
19388        cx: &mut Context<Editor>,
19389    ) -> Task<Result<bool>>;
19390
19391    fn apply_additional_edits_for_completion(
19392        &self,
19393        _buffer: Entity<Buffer>,
19394        _completions: Rc<RefCell<Box<[Completion]>>>,
19395        _completion_index: usize,
19396        _push_to_history: bool,
19397        _cx: &mut Context<Editor>,
19398    ) -> Task<Result<Option<language::Transaction>>> {
19399        Task::ready(Ok(None))
19400    }
19401
19402    fn is_completion_trigger(
19403        &self,
19404        buffer: &Entity<Buffer>,
19405        position: language::Anchor,
19406        text: &str,
19407        trigger_in_words: bool,
19408        cx: &mut Context<Editor>,
19409    ) -> bool;
19410
19411    fn sort_completions(&self) -> bool {
19412        true
19413    }
19414
19415    fn filter_completions(&self) -> bool {
19416        true
19417    }
19418}
19419
19420pub trait CodeActionProvider {
19421    fn id(&self) -> Arc<str>;
19422
19423    fn code_actions(
19424        &self,
19425        buffer: &Entity<Buffer>,
19426        range: Range<text::Anchor>,
19427        window: &mut Window,
19428        cx: &mut App,
19429    ) -> Task<Result<Vec<CodeAction>>>;
19430
19431    fn apply_code_action(
19432        &self,
19433        buffer_handle: Entity<Buffer>,
19434        action: CodeAction,
19435        excerpt_id: ExcerptId,
19436        push_to_history: bool,
19437        window: &mut Window,
19438        cx: &mut App,
19439    ) -> Task<Result<ProjectTransaction>>;
19440}
19441
19442impl CodeActionProvider for Entity<Project> {
19443    fn id(&self) -> Arc<str> {
19444        "project".into()
19445    }
19446
19447    fn code_actions(
19448        &self,
19449        buffer: &Entity<Buffer>,
19450        range: Range<text::Anchor>,
19451        _window: &mut Window,
19452        cx: &mut App,
19453    ) -> Task<Result<Vec<CodeAction>>> {
19454        self.update(cx, |project, cx| {
19455            let code_lens = project.code_lens(buffer, range.clone(), cx);
19456            let code_actions = project.code_actions(buffer, range, None, cx);
19457            cx.background_spawn(async move {
19458                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19459                Ok(code_lens
19460                    .context("code lens fetch")?
19461                    .into_iter()
19462                    .chain(code_actions.context("code action fetch")?)
19463                    .collect())
19464            })
19465        })
19466    }
19467
19468    fn apply_code_action(
19469        &self,
19470        buffer_handle: Entity<Buffer>,
19471        action: CodeAction,
19472        _excerpt_id: ExcerptId,
19473        push_to_history: bool,
19474        _window: &mut Window,
19475        cx: &mut App,
19476    ) -> Task<Result<ProjectTransaction>> {
19477        self.update(cx, |project, cx| {
19478            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19479        })
19480    }
19481}
19482
19483fn snippet_completions(
19484    project: &Project,
19485    buffer: &Entity<Buffer>,
19486    buffer_position: text::Anchor,
19487    cx: &mut App,
19488) -> Task<Result<Vec<Completion>>> {
19489    let languages = buffer.read(cx).languages_at(buffer_position);
19490    let snippet_store = project.snippets().read(cx);
19491
19492    let scopes: Vec<_> = languages
19493        .iter()
19494        .filter_map(|language| {
19495            let language_name = language.lsp_id();
19496            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19497
19498            if snippets.is_empty() {
19499                None
19500            } else {
19501                Some((language.default_scope(), snippets))
19502            }
19503        })
19504        .collect();
19505
19506    if scopes.is_empty() {
19507        return Task::ready(Ok(vec![]));
19508    }
19509
19510    let snapshot = buffer.read(cx).text_snapshot();
19511    let chars: String = snapshot
19512        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19513        .collect();
19514    let executor = cx.background_executor().clone();
19515
19516    cx.background_spawn(async move {
19517        let mut all_results: Vec<Completion> = Vec::new();
19518        for (scope, snippets) in scopes.into_iter() {
19519            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19520            let mut last_word = chars
19521                .chars()
19522                .take_while(|c| classifier.is_word(*c))
19523                .collect::<String>();
19524            last_word = last_word.chars().rev().collect();
19525
19526            if last_word.is_empty() {
19527                return Ok(vec![]);
19528            }
19529
19530            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19531            let to_lsp = |point: &text::Anchor| {
19532                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19533                point_to_lsp(end)
19534            };
19535            let lsp_end = to_lsp(&buffer_position);
19536
19537            let candidates = snippets
19538                .iter()
19539                .enumerate()
19540                .flat_map(|(ix, snippet)| {
19541                    snippet
19542                        .prefix
19543                        .iter()
19544                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19545                })
19546                .collect::<Vec<StringMatchCandidate>>();
19547
19548            let mut matches = fuzzy::match_strings(
19549                &candidates,
19550                &last_word,
19551                last_word.chars().any(|c| c.is_uppercase()),
19552                100,
19553                &Default::default(),
19554                executor.clone(),
19555            )
19556            .await;
19557
19558            // Remove all candidates where the query's start does not match the start of any word in the candidate
19559            if let Some(query_start) = last_word.chars().next() {
19560                matches.retain(|string_match| {
19561                    split_words(&string_match.string).any(|word| {
19562                        // Check that the first codepoint of the word as lowercase matches the first
19563                        // codepoint of the query as lowercase
19564                        word.chars()
19565                            .flat_map(|codepoint| codepoint.to_lowercase())
19566                            .zip(query_start.to_lowercase())
19567                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19568                    })
19569                });
19570            }
19571
19572            let matched_strings = matches
19573                .into_iter()
19574                .map(|m| m.string)
19575                .collect::<HashSet<_>>();
19576
19577            let mut result: Vec<Completion> = snippets
19578                .iter()
19579                .filter_map(|snippet| {
19580                    let matching_prefix = snippet
19581                        .prefix
19582                        .iter()
19583                        .find(|prefix| matched_strings.contains(*prefix))?;
19584                    let start = as_offset - last_word.len();
19585                    let start = snapshot.anchor_before(start);
19586                    let range = start..buffer_position;
19587                    let lsp_start = to_lsp(&start);
19588                    let lsp_range = lsp::Range {
19589                        start: lsp_start,
19590                        end: lsp_end,
19591                    };
19592                    Some(Completion {
19593                        replace_range: range,
19594                        new_text: snippet.body.clone(),
19595                        source: CompletionSource::Lsp {
19596                            insert_range: None,
19597                            server_id: LanguageServerId(usize::MAX),
19598                            resolved: true,
19599                            lsp_completion: Box::new(lsp::CompletionItem {
19600                                label: snippet.prefix.first().unwrap().clone(),
19601                                kind: Some(CompletionItemKind::SNIPPET),
19602                                label_details: snippet.description.as_ref().map(|description| {
19603                                    lsp::CompletionItemLabelDetails {
19604                                        detail: Some(description.clone()),
19605                                        description: None,
19606                                    }
19607                                }),
19608                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19609                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19610                                    lsp::InsertReplaceEdit {
19611                                        new_text: snippet.body.clone(),
19612                                        insert: lsp_range,
19613                                        replace: lsp_range,
19614                                    },
19615                                )),
19616                                filter_text: Some(snippet.body.clone()),
19617                                sort_text: Some(char::MAX.to_string()),
19618                                ..lsp::CompletionItem::default()
19619                            }),
19620                            lsp_defaults: None,
19621                        },
19622                        label: CodeLabel {
19623                            text: matching_prefix.clone(),
19624                            runs: Vec::new(),
19625                            filter_range: 0..matching_prefix.len(),
19626                        },
19627                        icon_path: None,
19628                        documentation: snippet.description.clone().map(|description| {
19629                            CompletionDocumentation::SingleLine(description.into())
19630                        }),
19631                        insert_text_mode: None,
19632                        confirm: None,
19633                    })
19634                })
19635                .collect();
19636
19637            all_results.append(&mut result);
19638        }
19639
19640        Ok(all_results)
19641    })
19642}
19643
19644impl CompletionProvider for Entity<Project> {
19645    fn completions(
19646        &self,
19647        _excerpt_id: ExcerptId,
19648        buffer: &Entity<Buffer>,
19649        buffer_position: text::Anchor,
19650        options: CompletionContext,
19651        _window: &mut Window,
19652        cx: &mut Context<Editor>,
19653    ) -> Task<Result<Option<Vec<Completion>>>> {
19654        self.update(cx, |project, cx| {
19655            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19656            let project_completions = project.completions(buffer, buffer_position, options, cx);
19657            cx.background_spawn(async move {
19658                let snippets_completions = snippets.await?;
19659                match project_completions.await? {
19660                    Some(mut completions) => {
19661                        completions.extend(snippets_completions);
19662                        Ok(Some(completions))
19663                    }
19664                    None => {
19665                        if snippets_completions.is_empty() {
19666                            Ok(None)
19667                        } else {
19668                            Ok(Some(snippets_completions))
19669                        }
19670                    }
19671                }
19672            })
19673        })
19674    }
19675
19676    fn resolve_completions(
19677        &self,
19678        buffer: Entity<Buffer>,
19679        completion_indices: Vec<usize>,
19680        completions: Rc<RefCell<Box<[Completion]>>>,
19681        cx: &mut Context<Editor>,
19682    ) -> Task<Result<bool>> {
19683        self.update(cx, |project, cx| {
19684            project.lsp_store().update(cx, |lsp_store, cx| {
19685                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19686            })
19687        })
19688    }
19689
19690    fn apply_additional_edits_for_completion(
19691        &self,
19692        buffer: Entity<Buffer>,
19693        completions: Rc<RefCell<Box<[Completion]>>>,
19694        completion_index: usize,
19695        push_to_history: bool,
19696        cx: &mut Context<Editor>,
19697    ) -> Task<Result<Option<language::Transaction>>> {
19698        self.update(cx, |project, cx| {
19699            project.lsp_store().update(cx, |lsp_store, cx| {
19700                lsp_store.apply_additional_edits_for_completion(
19701                    buffer,
19702                    completions,
19703                    completion_index,
19704                    push_to_history,
19705                    cx,
19706                )
19707            })
19708        })
19709    }
19710
19711    fn is_completion_trigger(
19712        &self,
19713        buffer: &Entity<Buffer>,
19714        position: language::Anchor,
19715        text: &str,
19716        trigger_in_words: bool,
19717        cx: &mut Context<Editor>,
19718    ) -> bool {
19719        let mut chars = text.chars();
19720        let char = if let Some(char) = chars.next() {
19721            char
19722        } else {
19723            return false;
19724        };
19725        if chars.next().is_some() {
19726            return false;
19727        }
19728
19729        let buffer = buffer.read(cx);
19730        let snapshot = buffer.snapshot();
19731        if !snapshot.settings_at(position, cx).show_completions_on_input {
19732            return false;
19733        }
19734        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19735        if trigger_in_words && classifier.is_word(char) {
19736            return true;
19737        }
19738
19739        buffer.completion_triggers().contains(text)
19740    }
19741}
19742
19743impl SemanticsProvider for Entity<Project> {
19744    fn hover(
19745        &self,
19746        buffer: &Entity<Buffer>,
19747        position: text::Anchor,
19748        cx: &mut App,
19749    ) -> Option<Task<Vec<project::Hover>>> {
19750        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19751    }
19752
19753    fn document_highlights(
19754        &self,
19755        buffer: &Entity<Buffer>,
19756        position: text::Anchor,
19757        cx: &mut App,
19758    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19759        Some(self.update(cx, |project, cx| {
19760            project.document_highlights(buffer, position, cx)
19761        }))
19762    }
19763
19764    fn definitions(
19765        &self,
19766        buffer: &Entity<Buffer>,
19767        position: text::Anchor,
19768        kind: GotoDefinitionKind,
19769        cx: &mut App,
19770    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19771        Some(self.update(cx, |project, cx| match kind {
19772            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19773            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19774            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19775            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19776        }))
19777    }
19778
19779    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19780        // TODO: make this work for remote projects
19781        self.update(cx, |project, cx| {
19782            if project
19783                .active_debug_session(cx)
19784                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19785            {
19786                return true;
19787            }
19788
19789            buffer.update(cx, |buffer, cx| {
19790                project.any_language_server_supports_inlay_hints(buffer, cx)
19791            })
19792        })
19793    }
19794
19795    fn inline_values(
19796        &self,
19797        buffer_handle: Entity<Buffer>,
19798        range: Range<text::Anchor>,
19799        cx: &mut App,
19800    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19801        self.update(cx, |project, cx| {
19802            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19803
19804            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19805        })
19806    }
19807
19808    fn inlay_hints(
19809        &self,
19810        buffer_handle: Entity<Buffer>,
19811        range: Range<text::Anchor>,
19812        cx: &mut App,
19813    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19814        Some(self.update(cx, |project, cx| {
19815            project.inlay_hints(buffer_handle, range, cx)
19816        }))
19817    }
19818
19819    fn resolve_inlay_hint(
19820        &self,
19821        hint: InlayHint,
19822        buffer_handle: Entity<Buffer>,
19823        server_id: LanguageServerId,
19824        cx: &mut App,
19825    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19826        Some(self.update(cx, |project, cx| {
19827            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19828        }))
19829    }
19830
19831    fn range_for_rename(
19832        &self,
19833        buffer: &Entity<Buffer>,
19834        position: text::Anchor,
19835        cx: &mut App,
19836    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19837        Some(self.update(cx, |project, cx| {
19838            let buffer = buffer.clone();
19839            let task = project.prepare_rename(buffer.clone(), position, cx);
19840            cx.spawn(async move |_, cx| {
19841                Ok(match task.await? {
19842                    PrepareRenameResponse::Success(range) => Some(range),
19843                    PrepareRenameResponse::InvalidPosition => None,
19844                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19845                        // Fallback on using TreeSitter info to determine identifier range
19846                        buffer.update(cx, |buffer, _| {
19847                            let snapshot = buffer.snapshot();
19848                            let (range, kind) = snapshot.surrounding_word(position);
19849                            if kind != Some(CharKind::Word) {
19850                                return None;
19851                            }
19852                            Some(
19853                                snapshot.anchor_before(range.start)
19854                                    ..snapshot.anchor_after(range.end),
19855                            )
19856                        })?
19857                    }
19858                })
19859            })
19860        }))
19861    }
19862
19863    fn perform_rename(
19864        &self,
19865        buffer: &Entity<Buffer>,
19866        position: text::Anchor,
19867        new_name: String,
19868        cx: &mut App,
19869    ) -> Option<Task<Result<ProjectTransaction>>> {
19870        Some(self.update(cx, |project, cx| {
19871            project.perform_rename(buffer.clone(), position, new_name, cx)
19872        }))
19873    }
19874}
19875
19876fn inlay_hint_settings(
19877    location: Anchor,
19878    snapshot: &MultiBufferSnapshot,
19879    cx: &mut Context<Editor>,
19880) -> InlayHintSettings {
19881    let file = snapshot.file_at(location);
19882    let language = snapshot.language_at(location).map(|l| l.name());
19883    language_settings(language, file, cx).inlay_hints
19884}
19885
19886fn consume_contiguous_rows(
19887    contiguous_row_selections: &mut Vec<Selection<Point>>,
19888    selection: &Selection<Point>,
19889    display_map: &DisplaySnapshot,
19890    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19891) -> (MultiBufferRow, MultiBufferRow) {
19892    contiguous_row_selections.push(selection.clone());
19893    let start_row = MultiBufferRow(selection.start.row);
19894    let mut end_row = ending_row(selection, display_map);
19895
19896    while let Some(next_selection) = selections.peek() {
19897        if next_selection.start.row <= end_row.0 {
19898            end_row = ending_row(next_selection, display_map);
19899            contiguous_row_selections.push(selections.next().unwrap().clone());
19900        } else {
19901            break;
19902        }
19903    }
19904    (start_row, end_row)
19905}
19906
19907fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19908    if next_selection.end.column > 0 || next_selection.is_empty() {
19909        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19910    } else {
19911        MultiBufferRow(next_selection.end.row)
19912    }
19913}
19914
19915impl EditorSnapshot {
19916    pub fn remote_selections_in_range<'a>(
19917        &'a self,
19918        range: &'a Range<Anchor>,
19919        collaboration_hub: &dyn CollaborationHub,
19920        cx: &'a App,
19921    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19922        let participant_names = collaboration_hub.user_names(cx);
19923        let participant_indices = collaboration_hub.user_participant_indices(cx);
19924        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19925        let collaborators_by_replica_id = collaborators_by_peer_id
19926            .iter()
19927            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19928            .collect::<HashMap<_, _>>();
19929        self.buffer_snapshot
19930            .selections_in_range(range, false)
19931            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19932                if replica_id == AGENT_REPLICA_ID {
19933                    Some(RemoteSelection {
19934                        replica_id,
19935                        selection,
19936                        cursor_shape,
19937                        line_mode,
19938                        collaborator_id: CollaboratorId::Agent,
19939                        user_name: Some("Agent".into()),
19940                        color: cx.theme().players().agent(),
19941                    })
19942                } else {
19943                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19944                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19945                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19946                    Some(RemoteSelection {
19947                        replica_id,
19948                        selection,
19949                        cursor_shape,
19950                        line_mode,
19951                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19952                        user_name,
19953                        color: if let Some(index) = participant_index {
19954                            cx.theme().players().color_for_participant(index.0)
19955                        } else {
19956                            cx.theme().players().absent()
19957                        },
19958                    })
19959                }
19960            })
19961    }
19962
19963    pub fn hunks_for_ranges(
19964        &self,
19965        ranges: impl IntoIterator<Item = Range<Point>>,
19966    ) -> Vec<MultiBufferDiffHunk> {
19967        let mut hunks = Vec::new();
19968        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19969            HashMap::default();
19970        for query_range in ranges {
19971            let query_rows =
19972                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19973            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19974                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19975            ) {
19976                // Include deleted hunks that are adjacent to the query range, because
19977                // otherwise they would be missed.
19978                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19979                if hunk.status().is_deleted() {
19980                    intersects_range |= hunk.row_range.start == query_rows.end;
19981                    intersects_range |= hunk.row_range.end == query_rows.start;
19982                }
19983                if intersects_range {
19984                    if !processed_buffer_rows
19985                        .entry(hunk.buffer_id)
19986                        .or_default()
19987                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19988                    {
19989                        continue;
19990                    }
19991                    hunks.push(hunk);
19992                }
19993            }
19994        }
19995
19996        hunks
19997    }
19998
19999    fn display_diff_hunks_for_rows<'a>(
20000        &'a self,
20001        display_rows: Range<DisplayRow>,
20002        folded_buffers: &'a HashSet<BufferId>,
20003    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20004        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20005        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20006
20007        self.buffer_snapshot
20008            .diff_hunks_in_range(buffer_start..buffer_end)
20009            .filter_map(|hunk| {
20010                if folded_buffers.contains(&hunk.buffer_id) {
20011                    return None;
20012                }
20013
20014                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20015                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20016
20017                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20018                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20019
20020                let display_hunk = if hunk_display_start.column() != 0 {
20021                    DisplayDiffHunk::Folded {
20022                        display_row: hunk_display_start.row(),
20023                    }
20024                } else {
20025                    let mut end_row = hunk_display_end.row();
20026                    if hunk_display_end.column() > 0 {
20027                        end_row.0 += 1;
20028                    }
20029                    let is_created_file = hunk.is_created_file();
20030                    DisplayDiffHunk::Unfolded {
20031                        status: hunk.status(),
20032                        diff_base_byte_range: hunk.diff_base_byte_range,
20033                        display_row_range: hunk_display_start.row()..end_row,
20034                        multi_buffer_range: Anchor::range_in_buffer(
20035                            hunk.excerpt_id,
20036                            hunk.buffer_id,
20037                            hunk.buffer_range,
20038                        ),
20039                        is_created_file,
20040                    }
20041                };
20042
20043                Some(display_hunk)
20044            })
20045    }
20046
20047    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20048        self.display_snapshot.buffer_snapshot.language_at(position)
20049    }
20050
20051    pub fn is_focused(&self) -> bool {
20052        self.is_focused
20053    }
20054
20055    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20056        self.placeholder_text.as_ref()
20057    }
20058
20059    pub fn scroll_position(&self) -> gpui::Point<f32> {
20060        self.scroll_anchor.scroll_position(&self.display_snapshot)
20061    }
20062
20063    fn gutter_dimensions(
20064        &self,
20065        font_id: FontId,
20066        font_size: Pixels,
20067        max_line_number_width: Pixels,
20068        cx: &App,
20069    ) -> Option<GutterDimensions> {
20070        if !self.show_gutter {
20071            return None;
20072        }
20073
20074        let descent = cx.text_system().descent(font_id, font_size);
20075        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20076        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20077
20078        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20079            matches!(
20080                ProjectSettings::get_global(cx).git.git_gutter,
20081                Some(GitGutterSetting::TrackedFiles)
20082            )
20083        });
20084        let gutter_settings = EditorSettings::get_global(cx).gutter;
20085        let show_line_numbers = self
20086            .show_line_numbers
20087            .unwrap_or(gutter_settings.line_numbers);
20088        let line_gutter_width = if show_line_numbers {
20089            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20090            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20091            max_line_number_width.max(min_width_for_number_on_gutter)
20092        } else {
20093            0.0.into()
20094        };
20095
20096        let show_code_actions = self
20097            .show_code_actions
20098            .unwrap_or(gutter_settings.code_actions);
20099
20100        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20101        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20102
20103        let git_blame_entries_width =
20104            self.git_blame_gutter_max_author_length
20105                .map(|max_author_length| {
20106                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20107                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20108
20109                    /// The number of characters to dedicate to gaps and margins.
20110                    const SPACING_WIDTH: usize = 4;
20111
20112                    let max_char_count = max_author_length.min(renderer.max_author_length())
20113                        + ::git::SHORT_SHA_LENGTH
20114                        + MAX_RELATIVE_TIMESTAMP.len()
20115                        + SPACING_WIDTH;
20116
20117                    em_advance * max_char_count
20118                });
20119
20120        let is_singleton = self.buffer_snapshot.is_singleton();
20121
20122        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20123        left_padding += if !is_singleton {
20124            em_width * 4.0
20125        } else if show_code_actions || show_runnables || show_breakpoints {
20126            em_width * 3.0
20127        } else if show_git_gutter && show_line_numbers {
20128            em_width * 2.0
20129        } else if show_git_gutter || show_line_numbers {
20130            em_width
20131        } else {
20132            px(0.)
20133        };
20134
20135        let shows_folds = is_singleton && gutter_settings.folds;
20136
20137        let right_padding = if shows_folds && show_line_numbers {
20138            em_width * 4.0
20139        } else if shows_folds || (!is_singleton && show_line_numbers) {
20140            em_width * 3.0
20141        } else if show_line_numbers {
20142            em_width
20143        } else {
20144            px(0.)
20145        };
20146
20147        Some(GutterDimensions {
20148            left_padding,
20149            right_padding,
20150            width: line_gutter_width + left_padding + right_padding,
20151            margin: -descent,
20152            git_blame_entries_width,
20153        })
20154    }
20155
20156    pub fn render_crease_toggle(
20157        &self,
20158        buffer_row: MultiBufferRow,
20159        row_contains_cursor: bool,
20160        editor: Entity<Editor>,
20161        window: &mut Window,
20162        cx: &mut App,
20163    ) -> Option<AnyElement> {
20164        let folded = self.is_line_folded(buffer_row);
20165        let mut is_foldable = false;
20166
20167        if let Some(crease) = self
20168            .crease_snapshot
20169            .query_row(buffer_row, &self.buffer_snapshot)
20170        {
20171            is_foldable = true;
20172            match crease {
20173                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20174                    if let Some(render_toggle) = render_toggle {
20175                        let toggle_callback =
20176                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20177                                if folded {
20178                                    editor.update(cx, |editor, cx| {
20179                                        editor.fold_at(buffer_row, window, cx)
20180                                    });
20181                                } else {
20182                                    editor.update(cx, |editor, cx| {
20183                                        editor.unfold_at(buffer_row, window, cx)
20184                                    });
20185                                }
20186                            });
20187                        return Some((render_toggle)(
20188                            buffer_row,
20189                            folded,
20190                            toggle_callback,
20191                            window,
20192                            cx,
20193                        ));
20194                    }
20195                }
20196            }
20197        }
20198
20199        is_foldable |= self.starts_indent(buffer_row);
20200
20201        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20202            Some(
20203                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20204                    .toggle_state(folded)
20205                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20206                        if folded {
20207                            this.unfold_at(buffer_row, window, cx);
20208                        } else {
20209                            this.fold_at(buffer_row, window, cx);
20210                        }
20211                    }))
20212                    .into_any_element(),
20213            )
20214        } else {
20215            None
20216        }
20217    }
20218
20219    pub fn render_crease_trailer(
20220        &self,
20221        buffer_row: MultiBufferRow,
20222        window: &mut Window,
20223        cx: &mut App,
20224    ) -> Option<AnyElement> {
20225        let folded = self.is_line_folded(buffer_row);
20226        if let Crease::Inline { render_trailer, .. } = self
20227            .crease_snapshot
20228            .query_row(buffer_row, &self.buffer_snapshot)?
20229        {
20230            let render_trailer = render_trailer.as_ref()?;
20231            Some(render_trailer(buffer_row, folded, window, cx))
20232        } else {
20233            None
20234        }
20235    }
20236}
20237
20238impl Deref for EditorSnapshot {
20239    type Target = DisplaySnapshot;
20240
20241    fn deref(&self) -> &Self::Target {
20242        &self.display_snapshot
20243    }
20244}
20245
20246#[derive(Clone, Debug, PartialEq, Eq)]
20247pub enum EditorEvent {
20248    InputIgnored {
20249        text: Arc<str>,
20250    },
20251    InputHandled {
20252        utf16_range_to_replace: Option<Range<isize>>,
20253        text: Arc<str>,
20254    },
20255    ExcerptsAdded {
20256        buffer: Entity<Buffer>,
20257        predecessor: ExcerptId,
20258        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20259    },
20260    ExcerptsRemoved {
20261        ids: Vec<ExcerptId>,
20262        removed_buffer_ids: Vec<BufferId>,
20263    },
20264    BufferFoldToggled {
20265        ids: Vec<ExcerptId>,
20266        folded: bool,
20267    },
20268    ExcerptsEdited {
20269        ids: Vec<ExcerptId>,
20270    },
20271    ExcerptsExpanded {
20272        ids: Vec<ExcerptId>,
20273    },
20274    BufferEdited,
20275    Edited {
20276        transaction_id: clock::Lamport,
20277    },
20278    Reparsed(BufferId),
20279    Focused,
20280    FocusedIn,
20281    Blurred,
20282    DirtyChanged,
20283    Saved,
20284    TitleChanged,
20285    DiffBaseChanged,
20286    SelectionsChanged {
20287        local: bool,
20288    },
20289    ScrollPositionChanged {
20290        local: bool,
20291        autoscroll: bool,
20292    },
20293    Closed,
20294    TransactionUndone {
20295        transaction_id: clock::Lamport,
20296    },
20297    TransactionBegun {
20298        transaction_id: clock::Lamport,
20299    },
20300    Reloaded,
20301    CursorShapeChanged,
20302    PushedToNavHistory {
20303        anchor: Anchor,
20304        is_deactivate: bool,
20305    },
20306}
20307
20308impl EventEmitter<EditorEvent> for Editor {}
20309
20310impl Focusable for Editor {
20311    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20312        self.focus_handle.clone()
20313    }
20314}
20315
20316impl Render for Editor {
20317    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20318        let settings = ThemeSettings::get_global(cx);
20319
20320        let mut text_style = match self.mode {
20321            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20322                color: cx.theme().colors().editor_foreground,
20323                font_family: settings.ui_font.family.clone(),
20324                font_features: settings.ui_font.features.clone(),
20325                font_fallbacks: settings.ui_font.fallbacks.clone(),
20326                font_size: rems(0.875).into(),
20327                font_weight: settings.ui_font.weight,
20328                line_height: relative(settings.buffer_line_height.value()),
20329                ..Default::default()
20330            },
20331            EditorMode::Full { .. } => TextStyle {
20332                color: cx.theme().colors().editor_foreground,
20333                font_family: settings.buffer_font.family.clone(),
20334                font_features: settings.buffer_font.features.clone(),
20335                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20336                font_size: settings.buffer_font_size(cx).into(),
20337                font_weight: settings.buffer_font.weight,
20338                line_height: relative(settings.buffer_line_height.value()),
20339                ..Default::default()
20340            },
20341        };
20342        if let Some(text_style_refinement) = &self.text_style_refinement {
20343            text_style.refine(text_style_refinement)
20344        }
20345
20346        let background = match self.mode {
20347            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20348            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20349            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20350        };
20351
20352        EditorElement::new(
20353            &cx.entity(),
20354            EditorStyle {
20355                background,
20356                horizontal_padding: Pixels::default(),
20357                local_player: cx.theme().players().local(),
20358                text: text_style,
20359                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20360                syntax: cx.theme().syntax().clone(),
20361                status: cx.theme().status().clone(),
20362                inlay_hints_style: make_inlay_hints_style(cx),
20363                inline_completion_styles: make_suggestion_styles(cx),
20364                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20365            },
20366        )
20367    }
20368}
20369
20370impl EntityInputHandler for Editor {
20371    fn text_for_range(
20372        &mut self,
20373        range_utf16: Range<usize>,
20374        adjusted_range: &mut Option<Range<usize>>,
20375        _: &mut Window,
20376        cx: &mut Context<Self>,
20377    ) -> Option<String> {
20378        let snapshot = self.buffer.read(cx).read(cx);
20379        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20380        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20381        if (start.0..end.0) != range_utf16 {
20382            adjusted_range.replace(start.0..end.0);
20383        }
20384        Some(snapshot.text_for_range(start..end).collect())
20385    }
20386
20387    fn selected_text_range(
20388        &mut self,
20389        ignore_disabled_input: bool,
20390        _: &mut Window,
20391        cx: &mut Context<Self>,
20392    ) -> Option<UTF16Selection> {
20393        // Prevent the IME menu from appearing when holding down an alphabetic key
20394        // while input is disabled.
20395        if !ignore_disabled_input && !self.input_enabled {
20396            return None;
20397        }
20398
20399        let selection = self.selections.newest::<OffsetUtf16>(cx);
20400        let range = selection.range();
20401
20402        Some(UTF16Selection {
20403            range: range.start.0..range.end.0,
20404            reversed: selection.reversed,
20405        })
20406    }
20407
20408    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20409        let snapshot = self.buffer.read(cx).read(cx);
20410        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20411        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20412    }
20413
20414    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20415        self.clear_highlights::<InputComposition>(cx);
20416        self.ime_transaction.take();
20417    }
20418
20419    fn replace_text_in_range(
20420        &mut self,
20421        range_utf16: Option<Range<usize>>,
20422        text: &str,
20423        window: &mut Window,
20424        cx: &mut Context<Self>,
20425    ) {
20426        if !self.input_enabled {
20427            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20428            return;
20429        }
20430
20431        self.transact(window, cx, |this, window, cx| {
20432            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20433                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20434                Some(this.selection_replacement_ranges(range_utf16, cx))
20435            } else {
20436                this.marked_text_ranges(cx)
20437            };
20438
20439            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20440                let newest_selection_id = this.selections.newest_anchor().id;
20441                this.selections
20442                    .all::<OffsetUtf16>(cx)
20443                    .iter()
20444                    .zip(ranges_to_replace.iter())
20445                    .find_map(|(selection, range)| {
20446                        if selection.id == newest_selection_id {
20447                            Some(
20448                                (range.start.0 as isize - selection.head().0 as isize)
20449                                    ..(range.end.0 as isize - selection.head().0 as isize),
20450                            )
20451                        } else {
20452                            None
20453                        }
20454                    })
20455            });
20456
20457            cx.emit(EditorEvent::InputHandled {
20458                utf16_range_to_replace: range_to_replace,
20459                text: text.into(),
20460            });
20461
20462            if let Some(new_selected_ranges) = new_selected_ranges {
20463                this.change_selections(None, window, cx, |selections| {
20464                    selections.select_ranges(new_selected_ranges)
20465                });
20466                this.backspace(&Default::default(), window, cx);
20467            }
20468
20469            this.handle_input(text, window, cx);
20470        });
20471
20472        if let Some(transaction) = self.ime_transaction {
20473            self.buffer.update(cx, |buffer, cx| {
20474                buffer.group_until_transaction(transaction, cx);
20475            });
20476        }
20477
20478        self.unmark_text(window, cx);
20479    }
20480
20481    fn replace_and_mark_text_in_range(
20482        &mut self,
20483        range_utf16: Option<Range<usize>>,
20484        text: &str,
20485        new_selected_range_utf16: Option<Range<usize>>,
20486        window: &mut Window,
20487        cx: &mut Context<Self>,
20488    ) {
20489        if !self.input_enabled {
20490            return;
20491        }
20492
20493        let transaction = self.transact(window, cx, |this, window, cx| {
20494            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20495                let snapshot = this.buffer.read(cx).read(cx);
20496                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20497                    for marked_range in &mut marked_ranges {
20498                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20499                        marked_range.start.0 += relative_range_utf16.start;
20500                        marked_range.start =
20501                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20502                        marked_range.end =
20503                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20504                    }
20505                }
20506                Some(marked_ranges)
20507            } else if let Some(range_utf16) = range_utf16 {
20508                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20509                Some(this.selection_replacement_ranges(range_utf16, cx))
20510            } else {
20511                None
20512            };
20513
20514            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20515                let newest_selection_id = this.selections.newest_anchor().id;
20516                this.selections
20517                    .all::<OffsetUtf16>(cx)
20518                    .iter()
20519                    .zip(ranges_to_replace.iter())
20520                    .find_map(|(selection, range)| {
20521                        if selection.id == newest_selection_id {
20522                            Some(
20523                                (range.start.0 as isize - selection.head().0 as isize)
20524                                    ..(range.end.0 as isize - selection.head().0 as isize),
20525                            )
20526                        } else {
20527                            None
20528                        }
20529                    })
20530            });
20531
20532            cx.emit(EditorEvent::InputHandled {
20533                utf16_range_to_replace: range_to_replace,
20534                text: text.into(),
20535            });
20536
20537            if let Some(ranges) = ranges_to_replace {
20538                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20539            }
20540
20541            let marked_ranges = {
20542                let snapshot = this.buffer.read(cx).read(cx);
20543                this.selections
20544                    .disjoint_anchors()
20545                    .iter()
20546                    .map(|selection| {
20547                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20548                    })
20549                    .collect::<Vec<_>>()
20550            };
20551
20552            if text.is_empty() {
20553                this.unmark_text(window, cx);
20554            } else {
20555                this.highlight_text::<InputComposition>(
20556                    marked_ranges.clone(),
20557                    HighlightStyle {
20558                        underline: Some(UnderlineStyle {
20559                            thickness: px(1.),
20560                            color: None,
20561                            wavy: false,
20562                        }),
20563                        ..Default::default()
20564                    },
20565                    cx,
20566                );
20567            }
20568
20569            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20570            let use_autoclose = this.use_autoclose;
20571            let use_auto_surround = this.use_auto_surround;
20572            this.set_use_autoclose(false);
20573            this.set_use_auto_surround(false);
20574            this.handle_input(text, window, cx);
20575            this.set_use_autoclose(use_autoclose);
20576            this.set_use_auto_surround(use_auto_surround);
20577
20578            if let Some(new_selected_range) = new_selected_range_utf16 {
20579                let snapshot = this.buffer.read(cx).read(cx);
20580                let new_selected_ranges = marked_ranges
20581                    .into_iter()
20582                    .map(|marked_range| {
20583                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20584                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20585                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20586                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20587                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20588                    })
20589                    .collect::<Vec<_>>();
20590
20591                drop(snapshot);
20592                this.change_selections(None, window, cx, |selections| {
20593                    selections.select_ranges(new_selected_ranges)
20594                });
20595            }
20596        });
20597
20598        self.ime_transaction = self.ime_transaction.or(transaction);
20599        if let Some(transaction) = self.ime_transaction {
20600            self.buffer.update(cx, |buffer, cx| {
20601                buffer.group_until_transaction(transaction, cx);
20602            });
20603        }
20604
20605        if self.text_highlights::<InputComposition>(cx).is_none() {
20606            self.ime_transaction.take();
20607        }
20608    }
20609
20610    fn bounds_for_range(
20611        &mut self,
20612        range_utf16: Range<usize>,
20613        element_bounds: gpui::Bounds<Pixels>,
20614        window: &mut Window,
20615        cx: &mut Context<Self>,
20616    ) -> Option<gpui::Bounds<Pixels>> {
20617        let text_layout_details = self.text_layout_details(window);
20618        let gpui::Size {
20619            width: em_width,
20620            height: line_height,
20621        } = self.character_size(window);
20622
20623        let snapshot = self.snapshot(window, cx);
20624        let scroll_position = snapshot.scroll_position();
20625        let scroll_left = scroll_position.x * em_width;
20626
20627        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20628        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20629            + self.gutter_dimensions.width
20630            + self.gutter_dimensions.margin;
20631        let y = line_height * (start.row().as_f32() - scroll_position.y);
20632
20633        Some(Bounds {
20634            origin: element_bounds.origin + point(x, y),
20635            size: size(em_width, line_height),
20636        })
20637    }
20638
20639    fn character_index_for_point(
20640        &mut self,
20641        point: gpui::Point<Pixels>,
20642        _window: &mut Window,
20643        _cx: &mut Context<Self>,
20644    ) -> Option<usize> {
20645        let position_map = self.last_position_map.as_ref()?;
20646        if !position_map.text_hitbox.contains(&point) {
20647            return None;
20648        }
20649        let display_point = position_map.point_for_position(point).previous_valid;
20650        let anchor = position_map
20651            .snapshot
20652            .display_point_to_anchor(display_point, Bias::Left);
20653        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20654        Some(utf16_offset.0)
20655    }
20656}
20657
20658trait SelectionExt {
20659    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20660    fn spanned_rows(
20661        &self,
20662        include_end_if_at_line_start: bool,
20663        map: &DisplaySnapshot,
20664    ) -> Range<MultiBufferRow>;
20665}
20666
20667impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20668    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20669        let start = self
20670            .start
20671            .to_point(&map.buffer_snapshot)
20672            .to_display_point(map);
20673        let end = self
20674            .end
20675            .to_point(&map.buffer_snapshot)
20676            .to_display_point(map);
20677        if self.reversed {
20678            end..start
20679        } else {
20680            start..end
20681        }
20682    }
20683
20684    fn spanned_rows(
20685        &self,
20686        include_end_if_at_line_start: bool,
20687        map: &DisplaySnapshot,
20688    ) -> Range<MultiBufferRow> {
20689        let start = self.start.to_point(&map.buffer_snapshot);
20690        let mut end = self.end.to_point(&map.buffer_snapshot);
20691        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20692            end.row -= 1;
20693        }
20694
20695        let buffer_start = map.prev_line_boundary(start).0;
20696        let buffer_end = map.next_line_boundary(end).0;
20697        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20698    }
20699}
20700
20701impl<T: InvalidationRegion> InvalidationStack<T> {
20702    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20703    where
20704        S: Clone + ToOffset,
20705    {
20706        while let Some(region) = self.last() {
20707            let all_selections_inside_invalidation_ranges =
20708                if selections.len() == region.ranges().len() {
20709                    selections
20710                        .iter()
20711                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20712                        .all(|(selection, invalidation_range)| {
20713                            let head = selection.head().to_offset(buffer);
20714                            invalidation_range.start <= head && invalidation_range.end >= head
20715                        })
20716                } else {
20717                    false
20718                };
20719
20720            if all_selections_inside_invalidation_ranges {
20721                break;
20722            } else {
20723                self.pop();
20724            }
20725        }
20726    }
20727}
20728
20729impl<T> Default for InvalidationStack<T> {
20730    fn default() -> Self {
20731        Self(Default::default())
20732    }
20733}
20734
20735impl<T> Deref for InvalidationStack<T> {
20736    type Target = Vec<T>;
20737
20738    fn deref(&self) -> &Self::Target {
20739        &self.0
20740    }
20741}
20742
20743impl<T> DerefMut for InvalidationStack<T> {
20744    fn deref_mut(&mut self) -> &mut Self::Target {
20745        &mut self.0
20746    }
20747}
20748
20749impl InvalidationRegion for SnippetState {
20750    fn ranges(&self) -> &[Range<Anchor>] {
20751        &self.ranges[self.active_index]
20752    }
20753}
20754
20755fn inline_completion_edit_text(
20756    current_snapshot: &BufferSnapshot,
20757    edits: &[(Range<Anchor>, String)],
20758    edit_preview: &EditPreview,
20759    include_deletions: bool,
20760    cx: &App,
20761) -> HighlightedText {
20762    let edits = edits
20763        .iter()
20764        .map(|(anchor, text)| {
20765            (
20766                anchor.start.text_anchor..anchor.end.text_anchor,
20767                text.clone(),
20768            )
20769        })
20770        .collect::<Vec<_>>();
20771
20772    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20773}
20774
20775pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20776    match severity {
20777        DiagnosticSeverity::ERROR => colors.error,
20778        DiagnosticSeverity::WARNING => colors.warning,
20779        DiagnosticSeverity::INFORMATION => colors.info,
20780        DiagnosticSeverity::HINT => colors.info,
20781        _ => colors.ignored,
20782    }
20783}
20784
20785pub fn styled_runs_for_code_label<'a>(
20786    label: &'a CodeLabel,
20787    syntax_theme: &'a theme::SyntaxTheme,
20788) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20789    let fade_out = HighlightStyle {
20790        fade_out: Some(0.35),
20791        ..Default::default()
20792    };
20793
20794    let mut prev_end = label.filter_range.end;
20795    label
20796        .runs
20797        .iter()
20798        .enumerate()
20799        .flat_map(move |(ix, (range, highlight_id))| {
20800            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20801                style
20802            } else {
20803                return Default::default();
20804            };
20805            let mut muted_style = style;
20806            muted_style.highlight(fade_out);
20807
20808            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20809            if range.start >= label.filter_range.end {
20810                if range.start > prev_end {
20811                    runs.push((prev_end..range.start, fade_out));
20812                }
20813                runs.push((range.clone(), muted_style));
20814            } else if range.end <= label.filter_range.end {
20815                runs.push((range.clone(), style));
20816            } else {
20817                runs.push((range.start..label.filter_range.end, style));
20818                runs.push((label.filter_range.end..range.end, muted_style));
20819            }
20820            prev_end = cmp::max(prev_end, range.end);
20821
20822            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20823                runs.push((prev_end..label.text.len(), fade_out));
20824            }
20825
20826            runs
20827        })
20828}
20829
20830pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20831    let mut prev_index = 0;
20832    let mut prev_codepoint: Option<char> = None;
20833    text.char_indices()
20834        .chain([(text.len(), '\0')])
20835        .filter_map(move |(index, codepoint)| {
20836            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20837            let is_boundary = index == text.len()
20838                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20839                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20840            if is_boundary {
20841                let chunk = &text[prev_index..index];
20842                prev_index = index;
20843                Some(chunk)
20844            } else {
20845                None
20846            }
20847        })
20848}
20849
20850pub trait RangeToAnchorExt: Sized {
20851    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20852
20853    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20854        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20855        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20856    }
20857}
20858
20859impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20860    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20861        let start_offset = self.start.to_offset(snapshot);
20862        let end_offset = self.end.to_offset(snapshot);
20863        if start_offset == end_offset {
20864            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20865        } else {
20866            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20867        }
20868    }
20869}
20870
20871pub trait RowExt {
20872    fn as_f32(&self) -> f32;
20873
20874    fn next_row(&self) -> Self;
20875
20876    fn previous_row(&self) -> Self;
20877
20878    fn minus(&self, other: Self) -> u32;
20879}
20880
20881impl RowExt for DisplayRow {
20882    fn as_f32(&self) -> f32 {
20883        self.0 as f32
20884    }
20885
20886    fn next_row(&self) -> Self {
20887        Self(self.0 + 1)
20888    }
20889
20890    fn previous_row(&self) -> Self {
20891        Self(self.0.saturating_sub(1))
20892    }
20893
20894    fn minus(&self, other: Self) -> u32 {
20895        self.0 - other.0
20896    }
20897}
20898
20899impl RowExt for MultiBufferRow {
20900    fn as_f32(&self) -> f32 {
20901        self.0 as f32
20902    }
20903
20904    fn next_row(&self) -> Self {
20905        Self(self.0 + 1)
20906    }
20907
20908    fn previous_row(&self) -> Self {
20909        Self(self.0.saturating_sub(1))
20910    }
20911
20912    fn minus(&self, other: Self) -> u32 {
20913        self.0 - other.0
20914    }
20915}
20916
20917trait RowRangeExt {
20918    type Row;
20919
20920    fn len(&self) -> usize;
20921
20922    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20923}
20924
20925impl RowRangeExt for Range<MultiBufferRow> {
20926    type Row = MultiBufferRow;
20927
20928    fn len(&self) -> usize {
20929        (self.end.0 - self.start.0) as usize
20930    }
20931
20932    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20933        (self.start.0..self.end.0).map(MultiBufferRow)
20934    }
20935}
20936
20937impl RowRangeExt for Range<DisplayRow> {
20938    type Row = DisplayRow;
20939
20940    fn len(&self) -> usize {
20941        (self.end.0 - self.start.0) as usize
20942    }
20943
20944    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20945        (self.start.0..self.end.0).map(DisplayRow)
20946    }
20947}
20948
20949/// If select range has more than one line, we
20950/// just point the cursor to range.start.
20951fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20952    if range.start.row == range.end.row {
20953        range
20954    } else {
20955        range.start..range.start
20956    }
20957}
20958pub struct KillRing(ClipboardItem);
20959impl Global for KillRing {}
20960
20961const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20962
20963enum BreakpointPromptEditAction {
20964    Log,
20965    Condition,
20966    HitCondition,
20967}
20968
20969struct BreakpointPromptEditor {
20970    pub(crate) prompt: Entity<Editor>,
20971    editor: WeakEntity<Editor>,
20972    breakpoint_anchor: Anchor,
20973    breakpoint: Breakpoint,
20974    edit_action: BreakpointPromptEditAction,
20975    block_ids: HashSet<CustomBlockId>,
20976    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20977    _subscriptions: Vec<Subscription>,
20978}
20979
20980impl BreakpointPromptEditor {
20981    const MAX_LINES: u8 = 4;
20982
20983    fn new(
20984        editor: WeakEntity<Editor>,
20985        breakpoint_anchor: Anchor,
20986        breakpoint: Breakpoint,
20987        edit_action: BreakpointPromptEditAction,
20988        window: &mut Window,
20989        cx: &mut Context<Self>,
20990    ) -> Self {
20991        let base_text = match edit_action {
20992            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20993            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20994            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20995        }
20996        .map(|msg| msg.to_string())
20997        .unwrap_or_default();
20998
20999        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
21000        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
21001
21002        let prompt = cx.new(|cx| {
21003            let mut prompt = Editor::new(
21004                EditorMode::AutoHeight {
21005                    max_lines: Self::MAX_LINES as usize,
21006                },
21007                buffer,
21008                None,
21009                window,
21010                cx,
21011            );
21012            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21013            prompt.set_show_cursor_when_unfocused(false, cx);
21014            prompt.set_placeholder_text(
21015                match edit_action {
21016                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21017                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21018                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21019                },
21020                cx,
21021            );
21022
21023            prompt
21024        });
21025
21026        Self {
21027            prompt,
21028            editor,
21029            breakpoint_anchor,
21030            breakpoint,
21031            edit_action,
21032            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21033            block_ids: Default::default(),
21034            _subscriptions: vec![],
21035        }
21036    }
21037
21038    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21039        self.block_ids.extend(block_ids)
21040    }
21041
21042    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21043        if let Some(editor) = self.editor.upgrade() {
21044            let message = self
21045                .prompt
21046                .read(cx)
21047                .buffer
21048                .read(cx)
21049                .as_singleton()
21050                .expect("A multi buffer in breakpoint prompt isn't possible")
21051                .read(cx)
21052                .as_rope()
21053                .to_string();
21054
21055            editor.update(cx, |editor, cx| {
21056                editor.edit_breakpoint_at_anchor(
21057                    self.breakpoint_anchor,
21058                    self.breakpoint.clone(),
21059                    match self.edit_action {
21060                        BreakpointPromptEditAction::Log => {
21061                            BreakpointEditAction::EditLogMessage(message.into())
21062                        }
21063                        BreakpointPromptEditAction::Condition => {
21064                            BreakpointEditAction::EditCondition(message.into())
21065                        }
21066                        BreakpointPromptEditAction::HitCondition => {
21067                            BreakpointEditAction::EditHitCondition(message.into())
21068                        }
21069                    },
21070                    cx,
21071                );
21072
21073                editor.remove_blocks(self.block_ids.clone(), None, cx);
21074                cx.focus_self(window);
21075            });
21076        }
21077    }
21078
21079    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21080        self.editor
21081            .update(cx, |editor, cx| {
21082                editor.remove_blocks(self.block_ids.clone(), None, cx);
21083                window.focus(&editor.focus_handle);
21084            })
21085            .log_err();
21086    }
21087
21088    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21089        let settings = ThemeSettings::get_global(cx);
21090        let text_style = TextStyle {
21091            color: if self.prompt.read(cx).read_only(cx) {
21092                cx.theme().colors().text_disabled
21093            } else {
21094                cx.theme().colors().text
21095            },
21096            font_family: settings.buffer_font.family.clone(),
21097            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21098            font_size: settings.buffer_font_size(cx).into(),
21099            font_weight: settings.buffer_font.weight,
21100            line_height: relative(settings.buffer_line_height.value()),
21101            ..Default::default()
21102        };
21103        EditorElement::new(
21104            &self.prompt,
21105            EditorStyle {
21106                background: cx.theme().colors().editor_background,
21107                local_player: cx.theme().players().local(),
21108                text: text_style,
21109                ..Default::default()
21110            },
21111        )
21112    }
21113}
21114
21115impl Render for BreakpointPromptEditor {
21116    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21117        let gutter_dimensions = *self.gutter_dimensions.lock();
21118        h_flex()
21119            .key_context("Editor")
21120            .bg(cx.theme().colors().editor_background)
21121            .border_y_1()
21122            .border_color(cx.theme().status().info_border)
21123            .size_full()
21124            .py(window.line_height() / 2.5)
21125            .on_action(cx.listener(Self::confirm))
21126            .on_action(cx.listener(Self::cancel))
21127            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21128            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21129    }
21130}
21131
21132impl Focusable for BreakpointPromptEditor {
21133    fn focus_handle(&self, cx: &App) -> FocusHandle {
21134        self.prompt.focus_handle(cx)
21135    }
21136}
21137
21138fn all_edits_insertions_or_deletions(
21139    edits: &Vec<(Range<Anchor>, String)>,
21140    snapshot: &MultiBufferSnapshot,
21141) -> bool {
21142    let mut all_insertions = true;
21143    let mut all_deletions = true;
21144
21145    for (range, new_text) in edits.iter() {
21146        let range_is_empty = range.to_offset(&snapshot).is_empty();
21147        let text_is_empty = new_text.is_empty();
21148
21149        if range_is_empty != text_is_empty {
21150            if range_is_empty {
21151                all_deletions = false;
21152            } else {
21153                all_insertions = false;
21154            }
21155        } else {
21156            return false;
21157        }
21158
21159        if !all_insertions && !all_deletions {
21160            return false;
21161        }
21162    }
21163    all_insertions || all_deletions
21164}
21165
21166struct MissingEditPredictionKeybindingTooltip;
21167
21168impl Render for MissingEditPredictionKeybindingTooltip {
21169    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21170        ui::tooltip_container(window, cx, |container, _, cx| {
21171            container
21172                .flex_shrink_0()
21173                .max_w_80()
21174                .min_h(rems_from_px(124.))
21175                .justify_between()
21176                .child(
21177                    v_flex()
21178                        .flex_1()
21179                        .text_ui_sm(cx)
21180                        .child(Label::new("Conflict with Accept Keybinding"))
21181                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21182                )
21183                .child(
21184                    h_flex()
21185                        .pb_1()
21186                        .gap_1()
21187                        .items_end()
21188                        .w_full()
21189                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21190                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21191                        }))
21192                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21193                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21194                        })),
21195                )
21196        })
21197    }
21198}
21199
21200#[derive(Debug, Clone, Copy, PartialEq)]
21201pub struct LineHighlight {
21202    pub background: Background,
21203    pub border: Option<gpui::Hsla>,
21204    pub include_gutter: bool,
21205    pub type_id: Option<TypeId>,
21206}
21207
21208fn render_diff_hunk_controls(
21209    row: u32,
21210    status: &DiffHunkStatus,
21211    hunk_range: Range<Anchor>,
21212    is_created_file: bool,
21213    line_height: Pixels,
21214    editor: &Entity<Editor>,
21215    _window: &mut Window,
21216    cx: &mut App,
21217) -> AnyElement {
21218    h_flex()
21219        .h(line_height)
21220        .mr_1()
21221        .gap_1()
21222        .px_0p5()
21223        .pb_1()
21224        .border_x_1()
21225        .border_b_1()
21226        .border_color(cx.theme().colors().border_variant)
21227        .rounded_b_lg()
21228        .bg(cx.theme().colors().editor_background)
21229        .gap_1()
21230        .occlude()
21231        .shadow_md()
21232        .child(if status.has_secondary_hunk() {
21233            Button::new(("stage", row as u64), "Stage")
21234                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21235                .tooltip({
21236                    let focus_handle = editor.focus_handle(cx);
21237                    move |window, cx| {
21238                        Tooltip::for_action_in(
21239                            "Stage Hunk",
21240                            &::git::ToggleStaged,
21241                            &focus_handle,
21242                            window,
21243                            cx,
21244                        )
21245                    }
21246                })
21247                .on_click({
21248                    let editor = editor.clone();
21249                    move |_event, _window, cx| {
21250                        editor.update(cx, |editor, cx| {
21251                            editor.stage_or_unstage_diff_hunks(
21252                                true,
21253                                vec![hunk_range.start..hunk_range.start],
21254                                cx,
21255                            );
21256                        });
21257                    }
21258                })
21259        } else {
21260            Button::new(("unstage", row as u64), "Unstage")
21261                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21262                .tooltip({
21263                    let focus_handle = editor.focus_handle(cx);
21264                    move |window, cx| {
21265                        Tooltip::for_action_in(
21266                            "Unstage Hunk",
21267                            &::git::ToggleStaged,
21268                            &focus_handle,
21269                            window,
21270                            cx,
21271                        )
21272                    }
21273                })
21274                .on_click({
21275                    let editor = editor.clone();
21276                    move |_event, _window, cx| {
21277                        editor.update(cx, |editor, cx| {
21278                            editor.stage_or_unstage_diff_hunks(
21279                                false,
21280                                vec![hunk_range.start..hunk_range.start],
21281                                cx,
21282                            );
21283                        });
21284                    }
21285                })
21286        })
21287        .child(
21288            Button::new(("restore", row as u64), "Restore")
21289                .tooltip({
21290                    let focus_handle = editor.focus_handle(cx);
21291                    move |window, cx| {
21292                        Tooltip::for_action_in(
21293                            "Restore Hunk",
21294                            &::git::Restore,
21295                            &focus_handle,
21296                            window,
21297                            cx,
21298                        )
21299                    }
21300                })
21301                .on_click({
21302                    let editor = editor.clone();
21303                    move |_event, window, cx| {
21304                        editor.update(cx, |editor, cx| {
21305                            let snapshot = editor.snapshot(window, cx);
21306                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21307                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21308                        });
21309                    }
21310                })
21311                .disabled(is_created_file),
21312        )
21313        .when(
21314            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21315            |el| {
21316                el.child(
21317                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21318                        .shape(IconButtonShape::Square)
21319                        .icon_size(IconSize::Small)
21320                        // .disabled(!has_multiple_hunks)
21321                        .tooltip({
21322                            let focus_handle = editor.focus_handle(cx);
21323                            move |window, cx| {
21324                                Tooltip::for_action_in(
21325                                    "Next Hunk",
21326                                    &GoToHunk,
21327                                    &focus_handle,
21328                                    window,
21329                                    cx,
21330                                )
21331                            }
21332                        })
21333                        .on_click({
21334                            let editor = editor.clone();
21335                            move |_event, window, cx| {
21336                                editor.update(cx, |editor, cx| {
21337                                    let snapshot = editor.snapshot(window, cx);
21338                                    let position =
21339                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21340                                    editor.go_to_hunk_before_or_after_position(
21341                                        &snapshot,
21342                                        position,
21343                                        Direction::Next,
21344                                        window,
21345                                        cx,
21346                                    );
21347                                    editor.expand_selected_diff_hunks(cx);
21348                                });
21349                            }
21350                        }),
21351                )
21352                .child(
21353                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21354                        .shape(IconButtonShape::Square)
21355                        .icon_size(IconSize::Small)
21356                        // .disabled(!has_multiple_hunks)
21357                        .tooltip({
21358                            let focus_handle = editor.focus_handle(cx);
21359                            move |window, cx| {
21360                                Tooltip::for_action_in(
21361                                    "Previous Hunk",
21362                                    &GoToPreviousHunk,
21363                                    &focus_handle,
21364                                    window,
21365                                    cx,
21366                                )
21367                            }
21368                        })
21369                        .on_click({
21370                            let editor = editor.clone();
21371                            move |_event, window, cx| {
21372                                editor.update(cx, |editor, cx| {
21373                                    let snapshot = editor.snapshot(window, cx);
21374                                    let point =
21375                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21376                                    editor.go_to_hunk_before_or_after_position(
21377                                        &snapshot,
21378                                        point,
21379                                        Direction::Prev,
21380                                        window,
21381                                        cx,
21382                                    );
21383                                    editor.expand_selected_diff_hunks(cx);
21384                                });
21385                            }
21386                        }),
21387                )
21388            },
21389        )
21390        .into_any_element()
21391}