editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132};
  133
  134pub use git::blame::BlameRenderer;
  135pub use proposed_changes_editor::{
  136    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  137};
  138use smallvec::smallvec;
  139use std::{cell::OnceCell, iter::Peekable};
  140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  141
  142pub use lsp::CompletionContext;
  143use lsp::{
  144    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  145    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  146};
  147
  148use language::BufferSnapshot;
  149pub use lsp_ext::lsp_tasks;
  150use movement::TextLayoutDetails;
  151pub use multi_buffer::{
  152    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  153    RowInfo, ToOffset, ToPoint,
  154};
  155use multi_buffer::{
  156    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  157    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  158};
  159use parking_lot::Mutex;
  160use project::{
  161    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  162    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  163    TaskSourceKind,
  164    debugger::breakpoint_store::Breakpoint,
  165    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  166    project_settings::{GitGutterSetting, ProjectSettings},
  167};
  168use rand::prelude::*;
  169use rpc::{ErrorExt, proto::*};
  170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  171use selections_collection::{
  172    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  173};
  174use serde::{Deserialize, Serialize};
  175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  176use smallvec::SmallVec;
  177use snippet::Snippet;
  178use std::sync::Arc;
  179use std::{
  180    any::TypeId,
  181    borrow::Cow,
  182    cell::RefCell,
  183    cmp::{self, Ordering, Reverse},
  184    mem,
  185    num::NonZeroU32,
  186    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  187    path::{Path, PathBuf},
  188    rc::Rc,
  189    time::{Duration, Instant},
  190};
  191pub use sum_tree::Bias;
  192use sum_tree::TreeMap;
  193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  194use theme::{
  195    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  196    observe_buffer_font_size_adjustment,
  197};
  198use ui::{
  199    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  200    IconSize, Key, Tooltip, h_flex, prelude::*,
  201};
  202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  203use workspace::{
  204    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  205    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  206    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  207    item::{ItemHandle, PreviewTabsSettings},
  208    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  209    searchable::SearchEvent,
  210};
  211
  212use crate::hover_links::{find_url, find_url_from_range};
  213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  214
  215pub const FILE_HEADER_HEIGHT: u32 = 2;
  216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  219const MAX_LINE_LEN: usize = 1024;
  220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  223#[doc(hidden)]
  224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  226
  227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  230
  231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  234
  235pub type RenderDiffHunkControlsFn = Arc<
  236    dyn Fn(
  237        u32,
  238        &DiffHunkStatus,
  239        Range<Anchor>,
  240        bool,
  241        Pixels,
  242        &Entity<Editor>,
  243        &mut Window,
  244        &mut App,
  245    ) -> AnyElement,
  246>;
  247
  248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  249    alt: true,
  250    shift: true,
  251    control: false,
  252    platform: false,
  253    function: false,
  254};
  255
  256struct InlineValueCache {
  257    enabled: bool,
  258    inlays: Vec<InlayId>,
  259    refresh_task: Task<Option<()>>,
  260}
  261
  262impl InlineValueCache {
  263    fn new(enabled: bool) -> Self {
  264        Self {
  265            enabled,
  266            inlays: Vec::new(),
  267            refresh_task: Task::ready(None),
  268        }
  269    }
  270}
  271
  272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  273pub enum InlayId {
  274    InlineCompletion(usize),
  275    Hint(usize),
  276    DebuggerValue(usize),
  277}
  278
  279impl InlayId {
  280    fn id(&self) -> usize {
  281        match self {
  282            Self::InlineCompletion(id) => *id,
  283            Self::Hint(id) => *id,
  284            Self::DebuggerValue(id) => *id,
  285        }
  286    }
  287}
  288
  289pub enum ActiveDebugLine {}
  290enum DocumentHighlightRead {}
  291enum DocumentHighlightWrite {}
  292enum InputComposition {}
  293enum SelectedTextHighlight {}
  294
  295pub enum ConflictsOuter {}
  296pub enum ConflictsOurs {}
  297pub enum ConflictsTheirs {}
  298pub enum ConflictsOursMarker {}
  299pub enum ConflictsTheirsMarker {}
  300
  301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  302pub enum Navigated {
  303    Yes,
  304    No,
  305}
  306
  307impl Navigated {
  308    pub fn from_bool(yes: bool) -> Navigated {
  309        if yes { Navigated::Yes } else { Navigated::No }
  310    }
  311}
  312
  313#[derive(Debug, Clone, PartialEq, Eq)]
  314enum DisplayDiffHunk {
  315    Folded {
  316        display_row: DisplayRow,
  317    },
  318    Unfolded {
  319        is_created_file: bool,
  320        diff_base_byte_range: Range<usize>,
  321        display_row_range: Range<DisplayRow>,
  322        multi_buffer_range: Range<Anchor>,
  323        status: DiffHunkStatus,
  324    },
  325}
  326
  327pub enum HideMouseCursorOrigin {
  328    TypingAction,
  329    MovementAction,
  330}
  331
  332pub fn init_settings(cx: &mut App) {
  333    EditorSettings::register(cx);
  334}
  335
  336pub fn init(cx: &mut App) {
  337    init_settings(cx);
  338
  339    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  340
  341    workspace::register_project_item::<Editor>(cx);
  342    workspace::FollowableViewRegistry::register::<Editor>(cx);
  343    workspace::register_serializable_item::<Editor>(cx);
  344
  345    cx.observe_new(
  346        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  347            workspace.register_action(Editor::new_file);
  348            workspace.register_action(Editor::new_file_vertical);
  349            workspace.register_action(Editor::new_file_horizontal);
  350            workspace.register_action(Editor::cancel_language_server_work);
  351        },
  352    )
  353    .detach();
  354
  355    cx.on_action(move |_: &workspace::NewFile, cx| {
  356        let app_state = workspace::AppState::global(cx);
  357        if let Some(app_state) = app_state.upgrade() {
  358            workspace::open_new(
  359                Default::default(),
  360                app_state,
  361                cx,
  362                |workspace, window, cx| {
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369    cx.on_action(move |_: &workspace::NewWindow, cx| {
  370        let app_state = workspace::AppState::global(cx);
  371        if let Some(app_state) = app_state.upgrade() {
  372            workspace::open_new(
  373                Default::default(),
  374                app_state,
  375                cx,
  376                |workspace, window, cx| {
  377                    cx.activate(true);
  378                    Editor::new_file(workspace, &Default::default(), window, cx)
  379                },
  380            )
  381            .detach();
  382        }
  383    });
  384}
  385
  386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  387    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  388}
  389
  390pub trait DiagnosticRenderer {
  391    fn render_group(
  392        &self,
  393        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  394        buffer_id: BufferId,
  395        snapshot: EditorSnapshot,
  396        editor: WeakEntity<Editor>,
  397        cx: &mut App,
  398    ) -> Vec<BlockProperties<Anchor>>;
  399
  400    fn render_hover(
  401        &self,
  402        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  403        range: Range<Point>,
  404        buffer_id: BufferId,
  405        cx: &mut App,
  406    ) -> Option<Entity<markdown::Markdown>>;
  407
  408    fn open_link(
  409        &self,
  410        editor: &mut Editor,
  411        link: SharedString,
  412        window: &mut Window,
  413        cx: &mut Context<Editor>,
  414    );
  415}
  416
  417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  418
  419impl GlobalDiagnosticRenderer {
  420    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  421        cx.try_global::<Self>().map(|g| g.0.clone())
  422    }
  423}
  424
  425impl gpui::Global for GlobalDiagnosticRenderer {}
  426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  427    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  428}
  429
  430pub struct SearchWithinRange;
  431
  432trait InvalidationRegion {
  433    fn ranges(&self) -> &[Range<Anchor>];
  434}
  435
  436#[derive(Clone, Debug, PartialEq)]
  437pub enum SelectPhase {
  438    Begin {
  439        position: DisplayPoint,
  440        add: bool,
  441        click_count: usize,
  442    },
  443    BeginColumnar {
  444        position: DisplayPoint,
  445        reset: bool,
  446        goal_column: u32,
  447    },
  448    Extend {
  449        position: DisplayPoint,
  450        click_count: usize,
  451    },
  452    Update {
  453        position: DisplayPoint,
  454        goal_column: u32,
  455        scroll_delta: gpui::Point<f32>,
  456    },
  457    End,
  458}
  459
  460#[derive(Clone, Debug)]
  461pub enum SelectMode {
  462    Character,
  463    Word(Range<Anchor>),
  464    Line(Range<Anchor>),
  465    All,
  466}
  467
  468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  469pub enum EditorMode {
  470    SingleLine {
  471        auto_width: bool,
  472    },
  473    AutoHeight {
  474        max_lines: usize,
  475    },
  476    Full {
  477        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  478        scale_ui_elements_with_buffer_font_size: bool,
  479        /// When set to `true`, the editor will render a background for the active line.
  480        show_active_line_background: bool,
  481        /// When set to `true`, the editor's height will be determined by its content.
  482        sized_by_content: bool,
  483    },
  484}
  485
  486impl EditorMode {
  487    pub fn full() -> Self {
  488        Self::Full {
  489            scale_ui_elements_with_buffer_font_size: true,
  490            show_active_line_background: true,
  491            sized_by_content: false,
  492        }
  493    }
  494
  495    pub fn is_full(&self) -> bool {
  496        matches!(self, Self::Full { .. })
  497    }
  498}
  499
  500#[derive(Copy, Clone, Debug)]
  501pub enum SoftWrap {
  502    /// Prefer not to wrap at all.
  503    ///
  504    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  505    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  506    GitDiff,
  507    /// Prefer a single line generally, unless an overly long line is encountered.
  508    None,
  509    /// Soft wrap lines that exceed the editor width.
  510    EditorWidth,
  511    /// Soft wrap lines at the preferred line length.
  512    Column(u32),
  513    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  514    Bounded(u32),
  515}
  516
  517#[derive(Clone)]
  518pub struct EditorStyle {
  519    pub background: Hsla,
  520    pub local_player: PlayerColor,
  521    pub text: TextStyle,
  522    pub scrollbar_width: Pixels,
  523    pub syntax: Arc<SyntaxTheme>,
  524    pub status: StatusColors,
  525    pub inlay_hints_style: HighlightStyle,
  526    pub inline_completion_styles: InlineCompletionStyles,
  527    pub unnecessary_code_fade: f32,
  528}
  529
  530impl Default for EditorStyle {
  531    fn default() -> Self {
  532        Self {
  533            background: Hsla::default(),
  534            local_player: PlayerColor::default(),
  535            text: TextStyle::default(),
  536            scrollbar_width: Pixels::default(),
  537            syntax: Default::default(),
  538            // HACK: Status colors don't have a real default.
  539            // We should look into removing the status colors from the editor
  540            // style and retrieve them directly from the theme.
  541            status: StatusColors::dark(),
  542            inlay_hints_style: HighlightStyle::default(),
  543            inline_completion_styles: InlineCompletionStyles {
  544                insertion: HighlightStyle::default(),
  545                whitespace: HighlightStyle::default(),
  546            },
  547            unnecessary_code_fade: Default::default(),
  548        }
  549    }
  550}
  551
  552pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  553    let show_background = language_settings::language_settings(None, None, cx)
  554        .inlay_hints
  555        .show_background;
  556
  557    HighlightStyle {
  558        color: Some(cx.theme().status().hint),
  559        background_color: show_background.then(|| cx.theme().status().hint_background),
  560        ..HighlightStyle::default()
  561    }
  562}
  563
  564pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  565    InlineCompletionStyles {
  566        insertion: HighlightStyle {
  567            color: Some(cx.theme().status().predictive),
  568            ..HighlightStyle::default()
  569        },
  570        whitespace: HighlightStyle {
  571            background_color: Some(cx.theme().status().created_background),
  572            ..HighlightStyle::default()
  573        },
  574    }
  575}
  576
  577type CompletionId = usize;
  578
  579pub(crate) enum EditDisplayMode {
  580    TabAccept,
  581    DiffPopover,
  582    Inline,
  583}
  584
  585enum InlineCompletion {
  586    Edit {
  587        edits: Vec<(Range<Anchor>, String)>,
  588        edit_preview: Option<EditPreview>,
  589        display_mode: EditDisplayMode,
  590        snapshot: BufferSnapshot,
  591    },
  592    Move {
  593        target: Anchor,
  594        snapshot: BufferSnapshot,
  595    },
  596}
  597
  598struct InlineCompletionState {
  599    inlay_ids: Vec<InlayId>,
  600    completion: InlineCompletion,
  601    completion_id: Option<SharedString>,
  602    invalidation_range: Range<Anchor>,
  603}
  604
  605enum EditPredictionSettings {
  606    Disabled,
  607    Enabled {
  608        show_in_menu: bool,
  609        preview_requires_modifier: bool,
  610    },
  611}
  612
  613enum InlineCompletionHighlight {}
  614
  615#[derive(Debug, Clone)]
  616struct InlineDiagnostic {
  617    message: SharedString,
  618    group_id: usize,
  619    is_primary: bool,
  620    start: Point,
  621    severity: DiagnosticSeverity,
  622}
  623
  624pub enum MenuInlineCompletionsPolicy {
  625    Never,
  626    ByProvider,
  627}
  628
  629pub enum EditPredictionPreview {
  630    /// Modifier is not pressed
  631    Inactive { released_too_fast: bool },
  632    /// Modifier pressed
  633    Active {
  634        since: Instant,
  635        previous_scroll_position: Option<ScrollAnchor>,
  636    },
  637}
  638
  639impl EditPredictionPreview {
  640    pub fn released_too_fast(&self) -> bool {
  641        match self {
  642            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  643            EditPredictionPreview::Active { .. } => false,
  644        }
  645    }
  646
  647    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  648        if let EditPredictionPreview::Active {
  649            previous_scroll_position,
  650            ..
  651        } = self
  652        {
  653            *previous_scroll_position = scroll_position;
  654        }
  655    }
  656}
  657
  658pub struct ContextMenuOptions {
  659    pub min_entries_visible: usize,
  660    pub max_entries_visible: usize,
  661    pub placement: Option<ContextMenuPlacement>,
  662}
  663
  664#[derive(Debug, Clone, PartialEq, Eq)]
  665pub enum ContextMenuPlacement {
  666    Above,
  667    Below,
  668}
  669
  670#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  671struct EditorActionId(usize);
  672
  673impl EditorActionId {
  674    pub fn post_inc(&mut self) -> Self {
  675        let answer = self.0;
  676
  677        *self = Self(answer + 1);
  678
  679        Self(answer)
  680    }
  681}
  682
  683// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  684// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  685
  686type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  687type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  688
  689#[derive(Default)]
  690struct ScrollbarMarkerState {
  691    scrollbar_size: Size<Pixels>,
  692    dirty: bool,
  693    markers: Arc<[PaintQuad]>,
  694    pending_refresh: Option<Task<Result<()>>>,
  695}
  696
  697impl ScrollbarMarkerState {
  698    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  699        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  700    }
  701}
  702
  703#[derive(Clone, Debug)]
  704struct RunnableTasks {
  705    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  706    offset: multi_buffer::Anchor,
  707    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  708    column: u32,
  709    // Values of all named captures, including those starting with '_'
  710    extra_variables: HashMap<String, String>,
  711    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  712    context_range: Range<BufferOffset>,
  713}
  714
  715impl RunnableTasks {
  716    fn resolve<'a>(
  717        &'a self,
  718        cx: &'a task::TaskContext,
  719    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  720        self.templates.iter().filter_map(|(kind, template)| {
  721            template
  722                .resolve_task(&kind.to_id_base(), cx)
  723                .map(|task| (kind.clone(), task))
  724        })
  725    }
  726}
  727
  728#[derive(Clone)]
  729struct ResolvedTasks {
  730    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  731    position: Anchor,
  732}
  733
  734#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  735struct BufferOffset(usize);
  736
  737// Addons allow storing per-editor state in other crates (e.g. Vim)
  738pub trait Addon: 'static {
  739    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  740
  741    fn render_buffer_header_controls(
  742        &self,
  743        _: &ExcerptInfo,
  744        _: &Window,
  745        _: &App,
  746    ) -> Option<AnyElement> {
  747        None
  748    }
  749
  750    fn to_any(&self) -> &dyn std::any::Any;
  751
  752    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  753        None
  754    }
  755}
  756
  757/// A set of caret positions, registered when the editor was edited.
  758pub struct ChangeList {
  759    changes: Vec<Vec<Anchor>>,
  760    /// Currently "selected" change.
  761    position: Option<usize>,
  762}
  763
  764impl ChangeList {
  765    pub fn new() -> Self {
  766        Self {
  767            changes: Vec::new(),
  768            position: None,
  769        }
  770    }
  771
  772    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  773    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  774    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  775        if self.changes.is_empty() {
  776            return None;
  777        }
  778
  779        let prev = self.position.unwrap_or(self.changes.len());
  780        let next = if direction == Direction::Prev {
  781            prev.saturating_sub(count)
  782        } else {
  783            (prev + count).min(self.changes.len() - 1)
  784        };
  785        self.position = Some(next);
  786        self.changes.get(next).map(|anchors| anchors.as_slice())
  787    }
  788
  789    /// Adds a new change to the list, resetting the change list position.
  790    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  791        self.position.take();
  792        if pop_state {
  793            self.changes.pop();
  794        }
  795        self.changes.push(new_positions.clone());
  796    }
  797
  798    pub fn last(&self) -> Option<&[Anchor]> {
  799        self.changes.last().map(|anchors| anchors.as_slice())
  800    }
  801}
  802
  803#[derive(Clone)]
  804struct InlineBlamePopoverState {
  805    scroll_handle: ScrollHandle,
  806    commit_message: Option<ParsedCommitMessage>,
  807    markdown: Entity<Markdown>,
  808}
  809
  810struct InlineBlamePopover {
  811    position: gpui::Point<Pixels>,
  812    show_task: Option<Task<()>>,
  813    hide_task: Option<Task<()>>,
  814    popover_bounds: Option<Bounds<Pixels>>,
  815    popover_state: InlineBlamePopoverState,
  816}
  817
  818/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  819/// a breakpoint on them.
  820#[derive(Clone, Copy, Debug)]
  821struct PhantomBreakpointIndicator {
  822    display_row: DisplayRow,
  823    /// There's a small debounce between hovering over the line and showing the indicator.
  824    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  825    is_active: bool,
  826    collides_with_existing_breakpoint: bool,
  827}
  828/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  829///
  830/// See the [module level documentation](self) for more information.
  831pub struct Editor {
  832    focus_handle: FocusHandle,
  833    last_focused_descendant: Option<WeakFocusHandle>,
  834    /// The text buffer being edited
  835    buffer: Entity<MultiBuffer>,
  836    /// Map of how text in the buffer should be displayed.
  837    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  838    pub display_map: Entity<DisplayMap>,
  839    pub selections: SelectionsCollection,
  840    pub scroll_manager: ScrollManager,
  841    /// When inline assist editors are linked, they all render cursors because
  842    /// typing enters text into each of them, even the ones that aren't focused.
  843    pub(crate) show_cursor_when_unfocused: bool,
  844    columnar_selection_tail: Option<Anchor>,
  845    add_selections_state: Option<AddSelectionsState>,
  846    select_next_state: Option<SelectNextState>,
  847    select_prev_state: Option<SelectNextState>,
  848    selection_history: SelectionHistory,
  849    autoclose_regions: Vec<AutocloseRegion>,
  850    snippet_stack: InvalidationStack<SnippetState>,
  851    select_syntax_node_history: SelectSyntaxNodeHistory,
  852    ime_transaction: Option<TransactionId>,
  853    active_diagnostics: ActiveDiagnostic,
  854    show_inline_diagnostics: bool,
  855    inline_diagnostics_update: Task<()>,
  856    inline_diagnostics_enabled: bool,
  857    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  858    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  859    hard_wrap: Option<usize>,
  860
  861    // TODO: make this a access method
  862    pub project: Option<Entity<Project>>,
  863    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  864    completion_provider: Option<Box<dyn CompletionProvider>>,
  865    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  866    blink_manager: Entity<BlinkManager>,
  867    show_cursor_names: bool,
  868    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  869    pub show_local_selections: bool,
  870    mode: EditorMode,
  871    show_breadcrumbs: bool,
  872    show_gutter: bool,
  873    show_scrollbars: bool,
  874    disable_expand_excerpt_buttons: bool,
  875    show_line_numbers: Option<bool>,
  876    use_relative_line_numbers: Option<bool>,
  877    show_git_diff_gutter: Option<bool>,
  878    show_code_actions: Option<bool>,
  879    show_runnables: Option<bool>,
  880    show_breakpoints: Option<bool>,
  881    show_wrap_guides: Option<bool>,
  882    show_indent_guides: Option<bool>,
  883    placeholder_text: Option<Arc<str>>,
  884    highlight_order: usize,
  885    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  886    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  887    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  888    scrollbar_marker_state: ScrollbarMarkerState,
  889    active_indent_guides_state: ActiveIndentGuidesState,
  890    nav_history: Option<ItemNavHistory>,
  891    context_menu: RefCell<Option<CodeContextMenu>>,
  892    context_menu_options: Option<ContextMenuOptions>,
  893    mouse_context_menu: Option<MouseContextMenu>,
  894    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  895    inline_blame_popover: Option<InlineBlamePopover>,
  896    signature_help_state: SignatureHelpState,
  897    auto_signature_help: Option<bool>,
  898    find_all_references_task_sources: Vec<Anchor>,
  899    next_completion_id: CompletionId,
  900    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  901    code_actions_task: Option<Task<Result<()>>>,
  902    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  903    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  904    document_highlights_task: Option<Task<()>>,
  905    linked_editing_range_task: Option<Task<Option<()>>>,
  906    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  907    pending_rename: Option<RenameState>,
  908    searchable: bool,
  909    cursor_shape: CursorShape,
  910    current_line_highlight: Option<CurrentLineHighlight>,
  911    collapse_matches: bool,
  912    autoindent_mode: Option<AutoindentMode>,
  913    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  914    input_enabled: bool,
  915    use_modal_editing: bool,
  916    read_only: bool,
  917    leader_id: Option<CollaboratorId>,
  918    remote_id: Option<ViewId>,
  919    pub hover_state: HoverState,
  920    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  921    gutter_hovered: bool,
  922    hovered_link_state: Option<HoveredLinkState>,
  923    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  924    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  925    active_inline_completion: Option<InlineCompletionState>,
  926    /// Used to prevent flickering as the user types while the menu is open
  927    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  928    edit_prediction_settings: EditPredictionSettings,
  929    inline_completions_hidden_for_vim_mode: bool,
  930    show_inline_completions_override: Option<bool>,
  931    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  932    edit_prediction_preview: EditPredictionPreview,
  933    edit_prediction_indent_conflict: bool,
  934    edit_prediction_requires_modifier_in_indent_conflict: bool,
  935    inlay_hint_cache: InlayHintCache,
  936    next_inlay_id: usize,
  937    _subscriptions: Vec<Subscription>,
  938    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  939    gutter_dimensions: GutterDimensions,
  940    style: Option<EditorStyle>,
  941    text_style_refinement: Option<TextStyleRefinement>,
  942    next_editor_action_id: EditorActionId,
  943    editor_actions:
  944        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  945    use_autoclose: bool,
  946    use_auto_surround: bool,
  947    auto_replace_emoji_shortcode: bool,
  948    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  949    show_git_blame_gutter: bool,
  950    show_git_blame_inline: bool,
  951    show_git_blame_inline_delay_task: Option<Task<()>>,
  952    git_blame_inline_enabled: bool,
  953    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  954    serialize_dirty_buffers: bool,
  955    show_selection_menu: Option<bool>,
  956    blame: Option<Entity<GitBlame>>,
  957    blame_subscription: Option<Subscription>,
  958    custom_context_menu: Option<
  959        Box<
  960            dyn 'static
  961                + Fn(
  962                    &mut Self,
  963                    DisplayPoint,
  964                    &mut Window,
  965                    &mut Context<Self>,
  966                ) -> Option<Entity<ui::ContextMenu>>,
  967        >,
  968    >,
  969    last_bounds: Option<Bounds<Pixels>>,
  970    last_position_map: Option<Rc<PositionMap>>,
  971    expect_bounds_change: Option<Bounds<Pixels>>,
  972    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  973    tasks_update_task: Option<Task<()>>,
  974    breakpoint_store: Option<Entity<BreakpointStore>>,
  975    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
  976    in_project_search: bool,
  977    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  978    breadcrumb_header: Option<String>,
  979    focused_block: Option<FocusedBlock>,
  980    next_scroll_position: NextScrollCursorCenterTopBottom,
  981    addons: HashMap<TypeId, Box<dyn Addon>>,
  982    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  983    load_diff_task: Option<Shared<Task<()>>>,
  984    /// Whether we are temporarily displaying a diff other than git's
  985    temporary_diff_override: bool,
  986    selection_mark_mode: bool,
  987    toggle_fold_multiple_buffers: Task<()>,
  988    _scroll_cursor_center_top_bottom_task: Task<()>,
  989    serialize_selections: Task<()>,
  990    serialize_folds: Task<()>,
  991    mouse_cursor_hidden: bool,
  992    hide_mouse_mode: HideMouseMode,
  993    pub change_list: ChangeList,
  994    inline_value_cache: InlineValueCache,
  995}
  996
  997#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  998enum NextScrollCursorCenterTopBottom {
  999    #[default]
 1000    Center,
 1001    Top,
 1002    Bottom,
 1003}
 1004
 1005impl NextScrollCursorCenterTopBottom {
 1006    fn next(&self) -> Self {
 1007        match self {
 1008            Self::Center => Self::Top,
 1009            Self::Top => Self::Bottom,
 1010            Self::Bottom => Self::Center,
 1011        }
 1012    }
 1013}
 1014
 1015#[derive(Clone)]
 1016pub struct EditorSnapshot {
 1017    pub mode: EditorMode,
 1018    show_gutter: bool,
 1019    show_line_numbers: Option<bool>,
 1020    show_git_diff_gutter: Option<bool>,
 1021    show_code_actions: Option<bool>,
 1022    show_runnables: Option<bool>,
 1023    show_breakpoints: Option<bool>,
 1024    git_blame_gutter_max_author_length: Option<usize>,
 1025    pub display_snapshot: DisplaySnapshot,
 1026    pub placeholder_text: Option<Arc<str>>,
 1027    is_focused: bool,
 1028    scroll_anchor: ScrollAnchor,
 1029    ongoing_scroll: OngoingScroll,
 1030    current_line_highlight: CurrentLineHighlight,
 1031    gutter_hovered: bool,
 1032}
 1033
 1034#[derive(Default, Debug, Clone, Copy)]
 1035pub struct GutterDimensions {
 1036    pub left_padding: Pixels,
 1037    pub right_padding: Pixels,
 1038    pub width: Pixels,
 1039    pub margin: Pixels,
 1040    pub git_blame_entries_width: Option<Pixels>,
 1041}
 1042
 1043impl GutterDimensions {
 1044    /// The full width of the space taken up by the gutter.
 1045    pub fn full_width(&self) -> Pixels {
 1046        self.margin + self.width
 1047    }
 1048
 1049    /// The width of the space reserved for the fold indicators,
 1050    /// use alongside 'justify_end' and `gutter_width` to
 1051    /// right align content with the line numbers
 1052    pub fn fold_area_width(&self) -> Pixels {
 1053        self.margin + self.right_padding
 1054    }
 1055}
 1056
 1057#[derive(Debug)]
 1058pub struct RemoteSelection {
 1059    pub replica_id: ReplicaId,
 1060    pub selection: Selection<Anchor>,
 1061    pub cursor_shape: CursorShape,
 1062    pub collaborator_id: CollaboratorId,
 1063    pub line_mode: bool,
 1064    pub user_name: Option<SharedString>,
 1065    pub color: PlayerColor,
 1066}
 1067
 1068#[derive(Clone, Debug)]
 1069struct SelectionHistoryEntry {
 1070    selections: Arc<[Selection<Anchor>]>,
 1071    select_next_state: Option<SelectNextState>,
 1072    select_prev_state: Option<SelectNextState>,
 1073    add_selections_state: Option<AddSelectionsState>,
 1074}
 1075
 1076enum SelectionHistoryMode {
 1077    Normal,
 1078    Undoing,
 1079    Redoing,
 1080}
 1081
 1082#[derive(Clone, PartialEq, Eq, Hash)]
 1083struct HoveredCursor {
 1084    replica_id: u16,
 1085    selection_id: usize,
 1086}
 1087
 1088impl Default for SelectionHistoryMode {
 1089    fn default() -> Self {
 1090        Self::Normal
 1091    }
 1092}
 1093
 1094#[derive(Default)]
 1095struct SelectionHistory {
 1096    #[allow(clippy::type_complexity)]
 1097    selections_by_transaction:
 1098        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1099    mode: SelectionHistoryMode,
 1100    undo_stack: VecDeque<SelectionHistoryEntry>,
 1101    redo_stack: VecDeque<SelectionHistoryEntry>,
 1102}
 1103
 1104impl SelectionHistory {
 1105    fn insert_transaction(
 1106        &mut self,
 1107        transaction_id: TransactionId,
 1108        selections: Arc<[Selection<Anchor>]>,
 1109    ) {
 1110        self.selections_by_transaction
 1111            .insert(transaction_id, (selections, None));
 1112    }
 1113
 1114    #[allow(clippy::type_complexity)]
 1115    fn transaction(
 1116        &self,
 1117        transaction_id: TransactionId,
 1118    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1119        self.selections_by_transaction.get(&transaction_id)
 1120    }
 1121
 1122    #[allow(clippy::type_complexity)]
 1123    fn transaction_mut(
 1124        &mut self,
 1125        transaction_id: TransactionId,
 1126    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1127        self.selections_by_transaction.get_mut(&transaction_id)
 1128    }
 1129
 1130    fn push(&mut self, entry: SelectionHistoryEntry) {
 1131        if !entry.selections.is_empty() {
 1132            match self.mode {
 1133                SelectionHistoryMode::Normal => {
 1134                    self.push_undo(entry);
 1135                    self.redo_stack.clear();
 1136                }
 1137                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1138                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1139            }
 1140        }
 1141    }
 1142
 1143    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1144        if self
 1145            .undo_stack
 1146            .back()
 1147            .map_or(true, |e| e.selections != entry.selections)
 1148        {
 1149            self.undo_stack.push_back(entry);
 1150            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1151                self.undo_stack.pop_front();
 1152            }
 1153        }
 1154    }
 1155
 1156    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1157        if self
 1158            .redo_stack
 1159            .back()
 1160            .map_or(true, |e| e.selections != entry.selections)
 1161        {
 1162            self.redo_stack.push_back(entry);
 1163            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1164                self.redo_stack.pop_front();
 1165            }
 1166        }
 1167    }
 1168}
 1169
 1170#[derive(Clone, Copy)]
 1171pub struct RowHighlightOptions {
 1172    pub autoscroll: bool,
 1173    pub include_gutter: bool,
 1174}
 1175
 1176impl Default for RowHighlightOptions {
 1177    fn default() -> Self {
 1178        Self {
 1179            autoscroll: Default::default(),
 1180            include_gutter: true,
 1181        }
 1182    }
 1183}
 1184
 1185struct RowHighlight {
 1186    index: usize,
 1187    range: Range<Anchor>,
 1188    color: Hsla,
 1189    options: RowHighlightOptions,
 1190    type_id: TypeId,
 1191}
 1192
 1193#[derive(Clone, Debug)]
 1194struct AddSelectionsState {
 1195    above: bool,
 1196    stack: Vec<usize>,
 1197}
 1198
 1199#[derive(Clone)]
 1200struct SelectNextState {
 1201    query: AhoCorasick,
 1202    wordwise: bool,
 1203    done: bool,
 1204}
 1205
 1206impl std::fmt::Debug for SelectNextState {
 1207    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1208        f.debug_struct(std::any::type_name::<Self>())
 1209            .field("wordwise", &self.wordwise)
 1210            .field("done", &self.done)
 1211            .finish()
 1212    }
 1213}
 1214
 1215#[derive(Debug)]
 1216struct AutocloseRegion {
 1217    selection_id: usize,
 1218    range: Range<Anchor>,
 1219    pair: BracketPair,
 1220}
 1221
 1222#[derive(Debug)]
 1223struct SnippetState {
 1224    ranges: Vec<Vec<Range<Anchor>>>,
 1225    active_index: usize,
 1226    choices: Vec<Option<Vec<String>>>,
 1227}
 1228
 1229#[doc(hidden)]
 1230pub struct RenameState {
 1231    pub range: Range<Anchor>,
 1232    pub old_name: Arc<str>,
 1233    pub editor: Entity<Editor>,
 1234    block_id: CustomBlockId,
 1235}
 1236
 1237struct InvalidationStack<T>(Vec<T>);
 1238
 1239struct RegisteredInlineCompletionProvider {
 1240    provider: Arc<dyn InlineCompletionProviderHandle>,
 1241    _subscription: Subscription,
 1242}
 1243
 1244#[derive(Debug, PartialEq, Eq)]
 1245pub struct ActiveDiagnosticGroup {
 1246    pub active_range: Range<Anchor>,
 1247    pub active_message: String,
 1248    pub group_id: usize,
 1249    pub blocks: HashSet<CustomBlockId>,
 1250}
 1251
 1252#[derive(Debug, PartialEq, Eq)]
 1253#[allow(clippy::large_enum_variant)]
 1254pub(crate) enum ActiveDiagnostic {
 1255    None,
 1256    All,
 1257    Group(ActiveDiagnosticGroup),
 1258}
 1259
 1260#[derive(Serialize, Deserialize, Clone, Debug)]
 1261pub struct ClipboardSelection {
 1262    /// The number of bytes in this selection.
 1263    pub len: usize,
 1264    /// Whether this was a full-line selection.
 1265    pub is_entire_line: bool,
 1266    /// The indentation of the first line when this content was originally copied.
 1267    pub first_line_indent: u32,
 1268}
 1269
 1270// selections, scroll behavior, was newest selection reversed
 1271type SelectSyntaxNodeHistoryState = (
 1272    Box<[Selection<usize>]>,
 1273    SelectSyntaxNodeScrollBehavior,
 1274    bool,
 1275);
 1276
 1277#[derive(Default)]
 1278struct SelectSyntaxNodeHistory {
 1279    stack: Vec<SelectSyntaxNodeHistoryState>,
 1280    // disable temporarily to allow changing selections without losing the stack
 1281    pub disable_clearing: bool,
 1282}
 1283
 1284impl SelectSyntaxNodeHistory {
 1285    pub fn try_clear(&mut self) {
 1286        if !self.disable_clearing {
 1287            self.stack.clear();
 1288        }
 1289    }
 1290
 1291    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1292        self.stack.push(selection);
 1293    }
 1294
 1295    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1296        self.stack.pop()
 1297    }
 1298}
 1299
 1300enum SelectSyntaxNodeScrollBehavior {
 1301    CursorTop,
 1302    FitSelection,
 1303    CursorBottom,
 1304}
 1305
 1306#[derive(Debug)]
 1307pub(crate) struct NavigationData {
 1308    cursor_anchor: Anchor,
 1309    cursor_position: Point,
 1310    scroll_anchor: ScrollAnchor,
 1311    scroll_top_row: u32,
 1312}
 1313
 1314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1315pub enum GotoDefinitionKind {
 1316    Symbol,
 1317    Declaration,
 1318    Type,
 1319    Implementation,
 1320}
 1321
 1322#[derive(Debug, Clone)]
 1323enum InlayHintRefreshReason {
 1324    ModifiersChanged(bool),
 1325    Toggle(bool),
 1326    SettingsChange(InlayHintSettings),
 1327    NewLinesShown,
 1328    BufferEdited(HashSet<Arc<Language>>),
 1329    RefreshRequested,
 1330    ExcerptsRemoved(Vec<ExcerptId>),
 1331}
 1332
 1333impl InlayHintRefreshReason {
 1334    fn description(&self) -> &'static str {
 1335        match self {
 1336            Self::ModifiersChanged(_) => "modifiers changed",
 1337            Self::Toggle(_) => "toggle",
 1338            Self::SettingsChange(_) => "settings change",
 1339            Self::NewLinesShown => "new lines shown",
 1340            Self::BufferEdited(_) => "buffer edited",
 1341            Self::RefreshRequested => "refresh requested",
 1342            Self::ExcerptsRemoved(_) => "excerpts removed",
 1343        }
 1344    }
 1345}
 1346
 1347pub enum FormatTarget {
 1348    Buffers,
 1349    Ranges(Vec<Range<MultiBufferPoint>>),
 1350}
 1351
 1352pub(crate) struct FocusedBlock {
 1353    id: BlockId,
 1354    focus_handle: WeakFocusHandle,
 1355}
 1356
 1357#[derive(Clone)]
 1358enum JumpData {
 1359    MultiBufferRow {
 1360        row: MultiBufferRow,
 1361        line_offset_from_top: u32,
 1362    },
 1363    MultiBufferPoint {
 1364        excerpt_id: ExcerptId,
 1365        position: Point,
 1366        anchor: text::Anchor,
 1367        line_offset_from_top: u32,
 1368    },
 1369}
 1370
 1371pub enum MultibufferSelectionMode {
 1372    First,
 1373    All,
 1374}
 1375
 1376#[derive(Clone, Copy, Debug, Default)]
 1377pub struct RewrapOptions {
 1378    pub override_language_settings: bool,
 1379    pub preserve_existing_whitespace: bool,
 1380}
 1381
 1382impl Editor {
 1383    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1384        let buffer = cx.new(|cx| Buffer::local("", cx));
 1385        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1386        Self::new(
 1387            EditorMode::SingleLine { auto_width: false },
 1388            buffer,
 1389            None,
 1390            window,
 1391            cx,
 1392        )
 1393    }
 1394
 1395    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1396        let buffer = cx.new(|cx| Buffer::local("", cx));
 1397        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1398        Self::new(EditorMode::full(), buffer, None, window, cx)
 1399    }
 1400
 1401    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1402        let buffer = cx.new(|cx| Buffer::local("", cx));
 1403        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1404        Self::new(
 1405            EditorMode::SingleLine { auto_width: true },
 1406            buffer,
 1407            None,
 1408            window,
 1409            cx,
 1410        )
 1411    }
 1412
 1413    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1414        let buffer = cx.new(|cx| Buffer::local("", cx));
 1415        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1416        Self::new(
 1417            EditorMode::AutoHeight { max_lines },
 1418            buffer,
 1419            None,
 1420            window,
 1421            cx,
 1422        )
 1423    }
 1424
 1425    pub fn for_buffer(
 1426        buffer: Entity<Buffer>,
 1427        project: Option<Entity<Project>>,
 1428        window: &mut Window,
 1429        cx: &mut Context<Self>,
 1430    ) -> Self {
 1431        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1432        Self::new(EditorMode::full(), buffer, project, window, cx)
 1433    }
 1434
 1435    pub fn for_multibuffer(
 1436        buffer: Entity<MultiBuffer>,
 1437        project: Option<Entity<Project>>,
 1438        window: &mut Window,
 1439        cx: &mut Context<Self>,
 1440    ) -> Self {
 1441        Self::new(EditorMode::full(), buffer, project, window, cx)
 1442    }
 1443
 1444    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1445        let mut clone = Self::new(
 1446            self.mode,
 1447            self.buffer.clone(),
 1448            self.project.clone(),
 1449            window,
 1450            cx,
 1451        );
 1452        self.display_map.update(cx, |display_map, cx| {
 1453            let snapshot = display_map.snapshot(cx);
 1454            clone.display_map.update(cx, |display_map, cx| {
 1455                display_map.set_state(&snapshot, cx);
 1456            });
 1457        });
 1458        clone.folds_did_change(cx);
 1459        clone.selections.clone_state(&self.selections);
 1460        clone.scroll_manager.clone_state(&self.scroll_manager);
 1461        clone.searchable = self.searchable;
 1462        clone.read_only = self.read_only;
 1463        clone
 1464    }
 1465
 1466    pub fn new(
 1467        mode: EditorMode,
 1468        buffer: Entity<MultiBuffer>,
 1469        project: Option<Entity<Project>>,
 1470        window: &mut Window,
 1471        cx: &mut Context<Self>,
 1472    ) -> Self {
 1473        let style = window.text_style();
 1474        let font_size = style.font_size.to_pixels(window.rem_size());
 1475        let editor = cx.entity().downgrade();
 1476        let fold_placeholder = FoldPlaceholder {
 1477            constrain_width: true,
 1478            render: Arc::new(move |fold_id, fold_range, cx| {
 1479                let editor = editor.clone();
 1480                div()
 1481                    .id(fold_id)
 1482                    .bg(cx.theme().colors().ghost_element_background)
 1483                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1484                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1485                    .rounded_xs()
 1486                    .size_full()
 1487                    .cursor_pointer()
 1488                    .child("")
 1489                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1490                    .on_click(move |_, _window, cx| {
 1491                        editor
 1492                            .update(cx, |editor, cx| {
 1493                                editor.unfold_ranges(
 1494                                    &[fold_range.start..fold_range.end],
 1495                                    true,
 1496                                    false,
 1497                                    cx,
 1498                                );
 1499                                cx.stop_propagation();
 1500                            })
 1501                            .ok();
 1502                    })
 1503                    .into_any()
 1504            }),
 1505            merge_adjacent: true,
 1506            ..Default::default()
 1507        };
 1508        let display_map = cx.new(|cx| {
 1509            DisplayMap::new(
 1510                buffer.clone(),
 1511                style.font(),
 1512                font_size,
 1513                None,
 1514                FILE_HEADER_HEIGHT,
 1515                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1516                fold_placeholder,
 1517                cx,
 1518            )
 1519        });
 1520
 1521        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1522
 1523        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1524
 1525        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1526            .then(|| language_settings::SoftWrap::None);
 1527
 1528        let mut project_subscriptions = Vec::new();
 1529        if mode.is_full() {
 1530            if let Some(project) = project.as_ref() {
 1531                project_subscriptions.push(cx.subscribe_in(
 1532                    project,
 1533                    window,
 1534                    |editor, _, event, window, cx| match event {
 1535                        project::Event::RefreshCodeLens => {
 1536                            // we always query lens with actions, without storing them, always refreshing them
 1537                        }
 1538                        project::Event::RefreshInlayHints => {
 1539                            editor
 1540                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1541                        }
 1542                        project::Event::SnippetEdit(id, snippet_edits) => {
 1543                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1544                                let focus_handle = editor.focus_handle(cx);
 1545                                if focus_handle.is_focused(window) {
 1546                                    let snapshot = buffer.read(cx).snapshot();
 1547                                    for (range, snippet) in snippet_edits {
 1548                                        let editor_range =
 1549                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1550                                        editor
 1551                                            .insert_snippet(
 1552                                                &[editor_range],
 1553                                                snippet.clone(),
 1554                                                window,
 1555                                                cx,
 1556                                            )
 1557                                            .ok();
 1558                                    }
 1559                                }
 1560                            }
 1561                        }
 1562                        _ => {}
 1563                    },
 1564                ));
 1565                if let Some(task_inventory) = project
 1566                    .read(cx)
 1567                    .task_store()
 1568                    .read(cx)
 1569                    .task_inventory()
 1570                    .cloned()
 1571                {
 1572                    project_subscriptions.push(cx.observe_in(
 1573                        &task_inventory,
 1574                        window,
 1575                        |editor, _, window, cx| {
 1576                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1577                        },
 1578                    ));
 1579                };
 1580
 1581                project_subscriptions.push(cx.subscribe_in(
 1582                    &project.read(cx).breakpoint_store(),
 1583                    window,
 1584                    |editor, _, event, window, cx| match event {
 1585                        BreakpointStoreEvent::ClearDebugLines => {
 1586                            editor.clear_row_highlights::<ActiveDebugLine>();
 1587                            editor.refresh_inline_values(cx);
 1588                        }
 1589                        BreakpointStoreEvent::SetDebugLine => {
 1590                            if editor.go_to_active_debug_line(window, cx) {
 1591                                cx.stop_propagation();
 1592                            }
 1593
 1594                            editor.refresh_inline_values(cx);
 1595                        }
 1596                        _ => {}
 1597                    },
 1598                ));
 1599            }
 1600        }
 1601
 1602        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1603
 1604        let inlay_hint_settings =
 1605            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1606        let focus_handle = cx.focus_handle();
 1607        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1608            .detach();
 1609        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1610            .detach();
 1611        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1612            .detach();
 1613        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1614            .detach();
 1615
 1616        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1617            Some(false)
 1618        } else {
 1619            None
 1620        };
 1621
 1622        let breakpoint_store = match (mode, project.as_ref()) {
 1623            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1624            _ => None,
 1625        };
 1626
 1627        let mut code_action_providers = Vec::new();
 1628        let mut load_uncommitted_diff = None;
 1629        if let Some(project) = project.clone() {
 1630            load_uncommitted_diff = Some(
 1631                update_uncommitted_diff_for_buffer(
 1632                    cx.entity(),
 1633                    &project,
 1634                    buffer.read(cx).all_buffers(),
 1635                    buffer.clone(),
 1636                    cx,
 1637                )
 1638                .shared(),
 1639            );
 1640            code_action_providers.push(Rc::new(project) as Rc<_>);
 1641        }
 1642
 1643        let mut this = Self {
 1644            focus_handle,
 1645            show_cursor_when_unfocused: false,
 1646            last_focused_descendant: None,
 1647            buffer: buffer.clone(),
 1648            display_map: display_map.clone(),
 1649            selections,
 1650            scroll_manager: ScrollManager::new(cx),
 1651            columnar_selection_tail: None,
 1652            add_selections_state: None,
 1653            select_next_state: None,
 1654            select_prev_state: None,
 1655            selection_history: Default::default(),
 1656            autoclose_regions: Default::default(),
 1657            snippet_stack: Default::default(),
 1658            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1659            ime_transaction: Default::default(),
 1660            active_diagnostics: ActiveDiagnostic::None,
 1661            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1662            inline_diagnostics_update: Task::ready(()),
 1663            inline_diagnostics: Vec::new(),
 1664            soft_wrap_mode_override,
 1665            hard_wrap: None,
 1666            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1667            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1668            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1669            project,
 1670            blink_manager: blink_manager.clone(),
 1671            show_local_selections: true,
 1672            show_scrollbars: true,
 1673            mode,
 1674            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1675            show_gutter: mode.is_full(),
 1676            show_line_numbers: None,
 1677            use_relative_line_numbers: None,
 1678            disable_expand_excerpt_buttons: false,
 1679            show_git_diff_gutter: None,
 1680            show_code_actions: None,
 1681            show_runnables: None,
 1682            show_breakpoints: None,
 1683            show_wrap_guides: None,
 1684            show_indent_guides,
 1685            placeholder_text: None,
 1686            highlight_order: 0,
 1687            highlighted_rows: HashMap::default(),
 1688            background_highlights: Default::default(),
 1689            gutter_highlights: TreeMap::default(),
 1690            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1691            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1692            nav_history: None,
 1693            context_menu: RefCell::new(None),
 1694            context_menu_options: None,
 1695            mouse_context_menu: None,
 1696            completion_tasks: Default::default(),
 1697            inline_blame_popover: Default::default(),
 1698            signature_help_state: SignatureHelpState::default(),
 1699            auto_signature_help: None,
 1700            find_all_references_task_sources: Vec::new(),
 1701            next_completion_id: 0,
 1702            next_inlay_id: 0,
 1703            code_action_providers,
 1704            available_code_actions: Default::default(),
 1705            code_actions_task: Default::default(),
 1706            quick_selection_highlight_task: Default::default(),
 1707            debounced_selection_highlight_task: Default::default(),
 1708            document_highlights_task: Default::default(),
 1709            linked_editing_range_task: Default::default(),
 1710            pending_rename: Default::default(),
 1711            searchable: true,
 1712            cursor_shape: EditorSettings::get_global(cx)
 1713                .cursor_shape
 1714                .unwrap_or_default(),
 1715            current_line_highlight: None,
 1716            autoindent_mode: Some(AutoindentMode::EachLine),
 1717            collapse_matches: false,
 1718            workspace: None,
 1719            input_enabled: true,
 1720            use_modal_editing: mode.is_full(),
 1721            read_only: false,
 1722            use_autoclose: true,
 1723            use_auto_surround: true,
 1724            auto_replace_emoji_shortcode: false,
 1725            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1726            leader_id: None,
 1727            remote_id: None,
 1728            hover_state: Default::default(),
 1729            pending_mouse_down: None,
 1730            hovered_link_state: Default::default(),
 1731            edit_prediction_provider: None,
 1732            active_inline_completion: None,
 1733            stale_inline_completion_in_menu: None,
 1734            edit_prediction_preview: EditPredictionPreview::Inactive {
 1735                released_too_fast: false,
 1736            },
 1737            inline_diagnostics_enabled: mode.is_full(),
 1738            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1739            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1740
 1741            gutter_hovered: false,
 1742            pixel_position_of_newest_cursor: None,
 1743            last_bounds: None,
 1744            last_position_map: None,
 1745            expect_bounds_change: None,
 1746            gutter_dimensions: GutterDimensions::default(),
 1747            style: None,
 1748            show_cursor_names: false,
 1749            hovered_cursors: Default::default(),
 1750            next_editor_action_id: EditorActionId::default(),
 1751            editor_actions: Rc::default(),
 1752            inline_completions_hidden_for_vim_mode: false,
 1753            show_inline_completions_override: None,
 1754            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1755            edit_prediction_settings: EditPredictionSettings::Disabled,
 1756            edit_prediction_indent_conflict: false,
 1757            edit_prediction_requires_modifier_in_indent_conflict: true,
 1758            custom_context_menu: None,
 1759            show_git_blame_gutter: false,
 1760            show_git_blame_inline: false,
 1761            show_selection_menu: None,
 1762            show_git_blame_inline_delay_task: None,
 1763            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1764            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1765            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1766                .session
 1767                .restore_unsaved_buffers,
 1768            blame: None,
 1769            blame_subscription: None,
 1770            tasks: Default::default(),
 1771
 1772            breakpoint_store,
 1773            gutter_breakpoint_indicator: (None, None),
 1774            _subscriptions: vec![
 1775                cx.observe(&buffer, Self::on_buffer_changed),
 1776                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1777                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1778                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1779                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1780                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1781                cx.observe_window_activation(window, |editor, window, cx| {
 1782                    let active = window.is_window_active();
 1783                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1784                        if active {
 1785                            blink_manager.enable(cx);
 1786                        } else {
 1787                            blink_manager.disable(cx);
 1788                        }
 1789                    });
 1790                }),
 1791            ],
 1792            tasks_update_task: None,
 1793            linked_edit_ranges: Default::default(),
 1794            in_project_search: false,
 1795            previous_search_ranges: None,
 1796            breadcrumb_header: None,
 1797            focused_block: None,
 1798            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1799            addons: HashMap::default(),
 1800            registered_buffers: HashMap::default(),
 1801            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1802            selection_mark_mode: false,
 1803            toggle_fold_multiple_buffers: Task::ready(()),
 1804            serialize_selections: Task::ready(()),
 1805            serialize_folds: Task::ready(()),
 1806            text_style_refinement: None,
 1807            load_diff_task: load_uncommitted_diff,
 1808            temporary_diff_override: false,
 1809            mouse_cursor_hidden: false,
 1810            hide_mouse_mode: EditorSettings::get_global(cx)
 1811                .hide_mouse
 1812                .unwrap_or_default(),
 1813            change_list: ChangeList::new(),
 1814        };
 1815        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1816            this._subscriptions
 1817                .push(cx.observe(breakpoints, |_, _, cx| {
 1818                    cx.notify();
 1819                }));
 1820        }
 1821        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1822        this._subscriptions.extend(project_subscriptions);
 1823
 1824        this._subscriptions.push(cx.subscribe_in(
 1825            &cx.entity(),
 1826            window,
 1827            |editor, _, e: &EditorEvent, window, cx| match e {
 1828                EditorEvent::ScrollPositionChanged { local, .. } => {
 1829                    if *local {
 1830                        let new_anchor = editor.scroll_manager.anchor();
 1831                        let snapshot = editor.snapshot(window, cx);
 1832                        editor.update_restoration_data(cx, move |data| {
 1833                            data.scroll_position = (
 1834                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1835                                new_anchor.offset,
 1836                            );
 1837                        });
 1838                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1839                        editor.inline_blame_popover.take();
 1840                    }
 1841                }
 1842                EditorEvent::Edited { .. } => {
 1843                    if !vim_enabled(cx) {
 1844                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1845                        let pop_state = editor
 1846                            .change_list
 1847                            .last()
 1848                            .map(|previous| {
 1849                                previous.len() == selections.len()
 1850                                    && previous.iter().enumerate().all(|(ix, p)| {
 1851                                        p.to_display_point(&map).row()
 1852                                            == selections[ix].head().row()
 1853                                    })
 1854                            })
 1855                            .unwrap_or(false);
 1856                        let new_positions = selections
 1857                            .into_iter()
 1858                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1859                            .collect();
 1860                        editor
 1861                            .change_list
 1862                            .push_to_change_list(pop_state, new_positions);
 1863                    }
 1864                }
 1865                _ => (),
 1866            },
 1867        ));
 1868
 1869        if let Some(dap_store) = this
 1870            .project
 1871            .as_ref()
 1872            .map(|project| project.read(cx).dap_store())
 1873        {
 1874            let weak_editor = cx.weak_entity();
 1875
 1876            this._subscriptions
 1877                .push(
 1878                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1879                        let session_entity = cx.entity();
 1880                        weak_editor
 1881                            .update(cx, |editor, cx| {
 1882                                editor._subscriptions.push(
 1883                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1884                                );
 1885                            })
 1886                            .ok();
 1887                    }),
 1888                );
 1889
 1890            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1891                this._subscriptions
 1892                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1893            }
 1894        }
 1895
 1896        this.end_selection(window, cx);
 1897        this.scroll_manager.show_scrollbars(window, cx);
 1898        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1899
 1900        if mode.is_full() {
 1901            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1902            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1903
 1904            if this.git_blame_inline_enabled {
 1905                this.git_blame_inline_enabled = true;
 1906                this.start_git_blame_inline(false, window, cx);
 1907            }
 1908
 1909            this.go_to_active_debug_line(window, cx);
 1910
 1911            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1912                if let Some(project) = this.project.as_ref() {
 1913                    let handle = project.update(cx, |project, cx| {
 1914                        project.register_buffer_with_language_servers(&buffer, cx)
 1915                    });
 1916                    this.registered_buffers
 1917                        .insert(buffer.read(cx).remote_id(), handle);
 1918                }
 1919            }
 1920        }
 1921
 1922        this.report_editor_event("Editor Opened", None, cx);
 1923        this
 1924    }
 1925
 1926    pub fn deploy_mouse_context_menu(
 1927        &mut self,
 1928        position: gpui::Point<Pixels>,
 1929        context_menu: Entity<ContextMenu>,
 1930        window: &mut Window,
 1931        cx: &mut Context<Self>,
 1932    ) {
 1933        self.mouse_context_menu = Some(MouseContextMenu::new(
 1934            self,
 1935            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1936            context_menu,
 1937            window,
 1938            cx,
 1939        ));
 1940    }
 1941
 1942    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1943        self.mouse_context_menu
 1944            .as_ref()
 1945            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1946    }
 1947
 1948    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1949        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1950    }
 1951
 1952    fn key_context_internal(
 1953        &self,
 1954        has_active_edit_prediction: bool,
 1955        window: &Window,
 1956        cx: &App,
 1957    ) -> KeyContext {
 1958        let mut key_context = KeyContext::new_with_defaults();
 1959        key_context.add("Editor");
 1960        let mode = match self.mode {
 1961            EditorMode::SingleLine { .. } => "single_line",
 1962            EditorMode::AutoHeight { .. } => "auto_height",
 1963            EditorMode::Full { .. } => "full",
 1964        };
 1965
 1966        if EditorSettings::jupyter_enabled(cx) {
 1967            key_context.add("jupyter");
 1968        }
 1969
 1970        key_context.set("mode", mode);
 1971        if self.pending_rename.is_some() {
 1972            key_context.add("renaming");
 1973        }
 1974
 1975        match self.context_menu.borrow().as_ref() {
 1976            Some(CodeContextMenu::Completions(_)) => {
 1977                key_context.add("menu");
 1978                key_context.add("showing_completions");
 1979            }
 1980            Some(CodeContextMenu::CodeActions(_)) => {
 1981                key_context.add("menu");
 1982                key_context.add("showing_code_actions")
 1983            }
 1984            None => {}
 1985        }
 1986
 1987        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1988        if !self.focus_handle(cx).contains_focused(window, cx)
 1989            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1990        {
 1991            for addon in self.addons.values() {
 1992                addon.extend_key_context(&mut key_context, cx)
 1993            }
 1994        }
 1995
 1996        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1997            if let Some(extension) = singleton_buffer
 1998                .read(cx)
 1999                .file()
 2000                .and_then(|file| file.path().extension()?.to_str())
 2001            {
 2002                key_context.set("extension", extension.to_string());
 2003            }
 2004        } else {
 2005            key_context.add("multibuffer");
 2006        }
 2007
 2008        if has_active_edit_prediction {
 2009            if self.edit_prediction_in_conflict() {
 2010                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2011            } else {
 2012                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2013                key_context.add("copilot_suggestion");
 2014            }
 2015        }
 2016
 2017        if self.selection_mark_mode {
 2018            key_context.add("selection_mode");
 2019        }
 2020
 2021        key_context
 2022    }
 2023
 2024    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2025        self.mouse_cursor_hidden = match origin {
 2026            HideMouseCursorOrigin::TypingAction => {
 2027                matches!(
 2028                    self.hide_mouse_mode,
 2029                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2030                )
 2031            }
 2032            HideMouseCursorOrigin::MovementAction => {
 2033                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2034            }
 2035        };
 2036    }
 2037
 2038    pub fn edit_prediction_in_conflict(&self) -> bool {
 2039        if !self.show_edit_predictions_in_menu() {
 2040            return false;
 2041        }
 2042
 2043        let showing_completions = self
 2044            .context_menu
 2045            .borrow()
 2046            .as_ref()
 2047            .map_or(false, |context| {
 2048                matches!(context, CodeContextMenu::Completions(_))
 2049            });
 2050
 2051        showing_completions
 2052            || self.edit_prediction_requires_modifier()
 2053            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2054            // bindings to insert tab characters.
 2055            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2056    }
 2057
 2058    pub fn accept_edit_prediction_keybind(
 2059        &self,
 2060        window: &Window,
 2061        cx: &App,
 2062    ) -> AcceptEditPredictionBinding {
 2063        let key_context = self.key_context_internal(true, window, cx);
 2064        let in_conflict = self.edit_prediction_in_conflict();
 2065
 2066        AcceptEditPredictionBinding(
 2067            window
 2068                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2069                .into_iter()
 2070                .filter(|binding| {
 2071                    !in_conflict
 2072                        || binding
 2073                            .keystrokes()
 2074                            .first()
 2075                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2076                })
 2077                .rev()
 2078                .min_by_key(|binding| {
 2079                    binding
 2080                        .keystrokes()
 2081                        .first()
 2082                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2083                }),
 2084        )
 2085    }
 2086
 2087    pub fn new_file(
 2088        workspace: &mut Workspace,
 2089        _: &workspace::NewFile,
 2090        window: &mut Window,
 2091        cx: &mut Context<Workspace>,
 2092    ) {
 2093        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2094            "Failed to create buffer",
 2095            window,
 2096            cx,
 2097            |e, _, _| match e.error_code() {
 2098                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2099                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2100                e.error_tag("required").unwrap_or("the latest version")
 2101            )),
 2102                _ => None,
 2103            },
 2104        );
 2105    }
 2106
 2107    pub fn new_in_workspace(
 2108        workspace: &mut Workspace,
 2109        window: &mut Window,
 2110        cx: &mut Context<Workspace>,
 2111    ) -> Task<Result<Entity<Editor>>> {
 2112        let project = workspace.project().clone();
 2113        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2114
 2115        cx.spawn_in(window, async move |workspace, cx| {
 2116            let buffer = create.await?;
 2117            workspace.update_in(cx, |workspace, window, cx| {
 2118                let editor =
 2119                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2120                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2121                editor
 2122            })
 2123        })
 2124    }
 2125
 2126    fn new_file_vertical(
 2127        workspace: &mut Workspace,
 2128        _: &workspace::NewFileSplitVertical,
 2129        window: &mut Window,
 2130        cx: &mut Context<Workspace>,
 2131    ) {
 2132        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2133    }
 2134
 2135    fn new_file_horizontal(
 2136        workspace: &mut Workspace,
 2137        _: &workspace::NewFileSplitHorizontal,
 2138        window: &mut Window,
 2139        cx: &mut Context<Workspace>,
 2140    ) {
 2141        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2142    }
 2143
 2144    fn new_file_in_direction(
 2145        workspace: &mut Workspace,
 2146        direction: SplitDirection,
 2147        window: &mut Window,
 2148        cx: &mut Context<Workspace>,
 2149    ) {
 2150        let project = workspace.project().clone();
 2151        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2152
 2153        cx.spawn_in(window, async move |workspace, cx| {
 2154            let buffer = create.await?;
 2155            workspace.update_in(cx, move |workspace, window, cx| {
 2156                workspace.split_item(
 2157                    direction,
 2158                    Box::new(
 2159                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2160                    ),
 2161                    window,
 2162                    cx,
 2163                )
 2164            })?;
 2165            anyhow::Ok(())
 2166        })
 2167        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2168            match e.error_code() {
 2169                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2170                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2171                e.error_tag("required").unwrap_or("the latest version")
 2172            )),
 2173                _ => None,
 2174            }
 2175        });
 2176    }
 2177
 2178    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2179        self.leader_id
 2180    }
 2181
 2182    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2183        &self.buffer
 2184    }
 2185
 2186    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2187        self.workspace.as_ref()?.0.upgrade()
 2188    }
 2189
 2190    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2191        self.buffer().read(cx).title(cx)
 2192    }
 2193
 2194    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2195        let git_blame_gutter_max_author_length = self
 2196            .render_git_blame_gutter(cx)
 2197            .then(|| {
 2198                if let Some(blame) = self.blame.as_ref() {
 2199                    let max_author_length =
 2200                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2201                    Some(max_author_length)
 2202                } else {
 2203                    None
 2204                }
 2205            })
 2206            .flatten();
 2207
 2208        EditorSnapshot {
 2209            mode: self.mode,
 2210            show_gutter: self.show_gutter,
 2211            show_line_numbers: self.show_line_numbers,
 2212            show_git_diff_gutter: self.show_git_diff_gutter,
 2213            show_code_actions: self.show_code_actions,
 2214            show_runnables: self.show_runnables,
 2215            show_breakpoints: self.show_breakpoints,
 2216            git_blame_gutter_max_author_length,
 2217            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2218            scroll_anchor: self.scroll_manager.anchor(),
 2219            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2220            placeholder_text: self.placeholder_text.clone(),
 2221            is_focused: self.focus_handle.is_focused(window),
 2222            current_line_highlight: self
 2223                .current_line_highlight
 2224                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2225            gutter_hovered: self.gutter_hovered,
 2226        }
 2227    }
 2228
 2229    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2230        self.buffer.read(cx).language_at(point, cx)
 2231    }
 2232
 2233    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2234        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2235    }
 2236
 2237    pub fn active_excerpt(
 2238        &self,
 2239        cx: &App,
 2240    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2241        self.buffer
 2242            .read(cx)
 2243            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2244    }
 2245
 2246    pub fn mode(&self) -> EditorMode {
 2247        self.mode
 2248    }
 2249
 2250    pub fn set_mode(&mut self, mode: EditorMode) {
 2251        self.mode = mode;
 2252    }
 2253
 2254    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2255        self.collaboration_hub.as_deref()
 2256    }
 2257
 2258    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2259        self.collaboration_hub = Some(hub);
 2260    }
 2261
 2262    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2263        self.in_project_search = in_project_search;
 2264    }
 2265
 2266    pub fn set_custom_context_menu(
 2267        &mut self,
 2268        f: impl 'static
 2269        + Fn(
 2270            &mut Self,
 2271            DisplayPoint,
 2272            &mut Window,
 2273            &mut Context<Self>,
 2274        ) -> Option<Entity<ui::ContextMenu>>,
 2275    ) {
 2276        self.custom_context_menu = Some(Box::new(f))
 2277    }
 2278
 2279    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2280        self.completion_provider = provider;
 2281    }
 2282
 2283    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2284        self.semantics_provider.clone()
 2285    }
 2286
 2287    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2288        self.semantics_provider = provider;
 2289    }
 2290
 2291    pub fn set_edit_prediction_provider<T>(
 2292        &mut self,
 2293        provider: Option<Entity<T>>,
 2294        window: &mut Window,
 2295        cx: &mut Context<Self>,
 2296    ) where
 2297        T: EditPredictionProvider,
 2298    {
 2299        self.edit_prediction_provider =
 2300            provider.map(|provider| RegisteredInlineCompletionProvider {
 2301                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2302                    if this.focus_handle.is_focused(window) {
 2303                        this.update_visible_inline_completion(window, cx);
 2304                    }
 2305                }),
 2306                provider: Arc::new(provider),
 2307            });
 2308        self.update_edit_prediction_settings(cx);
 2309        self.refresh_inline_completion(false, false, window, cx);
 2310    }
 2311
 2312    pub fn placeholder_text(&self) -> Option<&str> {
 2313        self.placeholder_text.as_deref()
 2314    }
 2315
 2316    pub fn set_placeholder_text(
 2317        &mut self,
 2318        placeholder_text: impl Into<Arc<str>>,
 2319        cx: &mut Context<Self>,
 2320    ) {
 2321        let placeholder_text = Some(placeholder_text.into());
 2322        if self.placeholder_text != placeholder_text {
 2323            self.placeholder_text = placeholder_text;
 2324            cx.notify();
 2325        }
 2326    }
 2327
 2328    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2329        self.cursor_shape = cursor_shape;
 2330
 2331        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2332        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2333
 2334        cx.notify();
 2335    }
 2336
 2337    pub fn set_current_line_highlight(
 2338        &mut self,
 2339        current_line_highlight: Option<CurrentLineHighlight>,
 2340    ) {
 2341        self.current_line_highlight = current_line_highlight;
 2342    }
 2343
 2344    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2345        self.collapse_matches = collapse_matches;
 2346    }
 2347
 2348    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2349        let buffers = self.buffer.read(cx).all_buffers();
 2350        let Some(project) = self.project.as_ref() else {
 2351            return;
 2352        };
 2353        project.update(cx, |project, cx| {
 2354            for buffer in buffers {
 2355                self.registered_buffers
 2356                    .entry(buffer.read(cx).remote_id())
 2357                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2358            }
 2359        })
 2360    }
 2361
 2362    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2363        if self.collapse_matches {
 2364            return range.start..range.start;
 2365        }
 2366        range.clone()
 2367    }
 2368
 2369    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2370        if self.display_map.read(cx).clip_at_line_ends != clip {
 2371            self.display_map
 2372                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2373        }
 2374    }
 2375
 2376    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2377        self.input_enabled = input_enabled;
 2378    }
 2379
 2380    pub fn set_inline_completions_hidden_for_vim_mode(
 2381        &mut self,
 2382        hidden: bool,
 2383        window: &mut Window,
 2384        cx: &mut Context<Self>,
 2385    ) {
 2386        if hidden != self.inline_completions_hidden_for_vim_mode {
 2387            self.inline_completions_hidden_for_vim_mode = hidden;
 2388            if hidden {
 2389                self.update_visible_inline_completion(window, cx);
 2390            } else {
 2391                self.refresh_inline_completion(true, false, window, cx);
 2392            }
 2393        }
 2394    }
 2395
 2396    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2397        self.menu_inline_completions_policy = value;
 2398    }
 2399
 2400    pub fn set_autoindent(&mut self, autoindent: bool) {
 2401        if autoindent {
 2402            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2403        } else {
 2404            self.autoindent_mode = None;
 2405        }
 2406    }
 2407
 2408    pub fn read_only(&self, cx: &App) -> bool {
 2409        self.read_only || self.buffer.read(cx).read_only()
 2410    }
 2411
 2412    pub fn set_read_only(&mut self, read_only: bool) {
 2413        self.read_only = read_only;
 2414    }
 2415
 2416    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2417        self.use_autoclose = autoclose;
 2418    }
 2419
 2420    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2421        self.use_auto_surround = auto_surround;
 2422    }
 2423
 2424    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2425        self.auto_replace_emoji_shortcode = auto_replace;
 2426    }
 2427
 2428    pub fn toggle_edit_predictions(
 2429        &mut self,
 2430        _: &ToggleEditPrediction,
 2431        window: &mut Window,
 2432        cx: &mut Context<Self>,
 2433    ) {
 2434        if self.show_inline_completions_override.is_some() {
 2435            self.set_show_edit_predictions(None, window, cx);
 2436        } else {
 2437            let show_edit_predictions = !self.edit_predictions_enabled();
 2438            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2439        }
 2440    }
 2441
 2442    pub fn set_show_edit_predictions(
 2443        &mut self,
 2444        show_edit_predictions: Option<bool>,
 2445        window: &mut Window,
 2446        cx: &mut Context<Self>,
 2447    ) {
 2448        self.show_inline_completions_override = show_edit_predictions;
 2449        self.update_edit_prediction_settings(cx);
 2450
 2451        if let Some(false) = show_edit_predictions {
 2452            self.discard_inline_completion(false, cx);
 2453        } else {
 2454            self.refresh_inline_completion(false, true, window, cx);
 2455        }
 2456    }
 2457
 2458    fn inline_completions_disabled_in_scope(
 2459        &self,
 2460        buffer: &Entity<Buffer>,
 2461        buffer_position: language::Anchor,
 2462        cx: &App,
 2463    ) -> bool {
 2464        let snapshot = buffer.read(cx).snapshot();
 2465        let settings = snapshot.settings_at(buffer_position, cx);
 2466
 2467        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2468            return false;
 2469        };
 2470
 2471        scope.override_name().map_or(false, |scope_name| {
 2472            settings
 2473                .edit_predictions_disabled_in
 2474                .iter()
 2475                .any(|s| s == scope_name)
 2476        })
 2477    }
 2478
 2479    pub fn set_use_modal_editing(&mut self, to: bool) {
 2480        self.use_modal_editing = to;
 2481    }
 2482
 2483    pub fn use_modal_editing(&self) -> bool {
 2484        self.use_modal_editing
 2485    }
 2486
 2487    fn selections_did_change(
 2488        &mut self,
 2489        local: bool,
 2490        old_cursor_position: &Anchor,
 2491        show_completions: bool,
 2492        window: &mut Window,
 2493        cx: &mut Context<Self>,
 2494    ) {
 2495        window.invalidate_character_coordinates();
 2496
 2497        // Copy selections to primary selection buffer
 2498        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2499        if local {
 2500            let selections = self.selections.all::<usize>(cx);
 2501            let buffer_handle = self.buffer.read(cx).read(cx);
 2502
 2503            let mut text = String::new();
 2504            for (index, selection) in selections.iter().enumerate() {
 2505                let text_for_selection = buffer_handle
 2506                    .text_for_range(selection.start..selection.end)
 2507                    .collect::<String>();
 2508
 2509                text.push_str(&text_for_selection);
 2510                if index != selections.len() - 1 {
 2511                    text.push('\n');
 2512                }
 2513            }
 2514
 2515            if !text.is_empty() {
 2516                cx.write_to_primary(ClipboardItem::new_string(text));
 2517            }
 2518        }
 2519
 2520        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2521            self.buffer.update(cx, |buffer, cx| {
 2522                buffer.set_active_selections(
 2523                    &self.selections.disjoint_anchors(),
 2524                    self.selections.line_mode,
 2525                    self.cursor_shape,
 2526                    cx,
 2527                )
 2528            });
 2529        }
 2530        let display_map = self
 2531            .display_map
 2532            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2533        let buffer = &display_map.buffer_snapshot;
 2534        self.add_selections_state = None;
 2535        self.select_next_state = None;
 2536        self.select_prev_state = None;
 2537        self.select_syntax_node_history.try_clear();
 2538        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2539        self.snippet_stack
 2540            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2541        self.take_rename(false, window, cx);
 2542
 2543        let new_cursor_position = self.selections.newest_anchor().head();
 2544
 2545        self.push_to_nav_history(
 2546            *old_cursor_position,
 2547            Some(new_cursor_position.to_point(buffer)),
 2548            false,
 2549            cx,
 2550        );
 2551
 2552        if local {
 2553            let new_cursor_position = self.selections.newest_anchor().head();
 2554            let mut context_menu = self.context_menu.borrow_mut();
 2555            let completion_menu = match context_menu.as_ref() {
 2556                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2557                _ => {
 2558                    *context_menu = None;
 2559                    None
 2560                }
 2561            };
 2562            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2563                if !self.registered_buffers.contains_key(&buffer_id) {
 2564                    if let Some(project) = self.project.as_ref() {
 2565                        project.update(cx, |project, cx| {
 2566                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2567                                return;
 2568                            };
 2569                            self.registered_buffers.insert(
 2570                                buffer_id,
 2571                                project.register_buffer_with_language_servers(&buffer, cx),
 2572                            );
 2573                        })
 2574                    }
 2575                }
 2576            }
 2577
 2578            if let Some(completion_menu) = completion_menu {
 2579                let cursor_position = new_cursor_position.to_offset(buffer);
 2580                let (word_range, kind) =
 2581                    buffer.surrounding_word(completion_menu.initial_position, true);
 2582                if kind == Some(CharKind::Word)
 2583                    && word_range.to_inclusive().contains(&cursor_position)
 2584                {
 2585                    let mut completion_menu = completion_menu.clone();
 2586                    drop(context_menu);
 2587
 2588                    let query = Self::completion_query(buffer, cursor_position);
 2589                    cx.spawn(async move |this, cx| {
 2590                        completion_menu
 2591                            .filter(query.as_deref(), cx.background_executor().clone())
 2592                            .await;
 2593
 2594                        this.update(cx, |this, cx| {
 2595                            let mut context_menu = this.context_menu.borrow_mut();
 2596                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2597                            else {
 2598                                return;
 2599                            };
 2600
 2601                            if menu.id > completion_menu.id {
 2602                                return;
 2603                            }
 2604
 2605                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2606                            drop(context_menu);
 2607                            cx.notify();
 2608                        })
 2609                    })
 2610                    .detach();
 2611
 2612                    if show_completions {
 2613                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2614                    }
 2615                } else {
 2616                    drop(context_menu);
 2617                    self.hide_context_menu(window, cx);
 2618                }
 2619            } else {
 2620                drop(context_menu);
 2621            }
 2622
 2623            hide_hover(self, cx);
 2624
 2625            if old_cursor_position.to_display_point(&display_map).row()
 2626                != new_cursor_position.to_display_point(&display_map).row()
 2627            {
 2628                self.available_code_actions.take();
 2629            }
 2630            self.refresh_code_actions(window, cx);
 2631            self.refresh_document_highlights(cx);
 2632            self.refresh_selected_text_highlights(false, window, cx);
 2633            refresh_matching_bracket_highlights(self, window, cx);
 2634            self.update_visible_inline_completion(window, cx);
 2635            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2636            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2637            self.inline_blame_popover.take();
 2638            if self.git_blame_inline_enabled {
 2639                self.start_inline_blame_timer(window, cx);
 2640            }
 2641        }
 2642
 2643        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2644        cx.emit(EditorEvent::SelectionsChanged { local });
 2645
 2646        let selections = &self.selections.disjoint;
 2647        if selections.len() == 1 {
 2648            cx.emit(SearchEvent::ActiveMatchChanged)
 2649        }
 2650        if local {
 2651            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2652                let inmemory_selections = selections
 2653                    .iter()
 2654                    .map(|s| {
 2655                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2656                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2657                    })
 2658                    .collect();
 2659                self.update_restoration_data(cx, |data| {
 2660                    data.selections = inmemory_selections;
 2661                });
 2662
 2663                if WorkspaceSettings::get(None, cx).restore_on_startup
 2664                    != RestoreOnStartupBehavior::None
 2665                {
 2666                    if let Some(workspace_id) =
 2667                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2668                    {
 2669                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2670                        let selections = selections.clone();
 2671                        let background_executor = cx.background_executor().clone();
 2672                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2673                        self.serialize_selections = cx.background_spawn(async move {
 2674                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2675                    let db_selections = selections
 2676                        .iter()
 2677                        .map(|selection| {
 2678                            (
 2679                                selection.start.to_offset(&snapshot),
 2680                                selection.end.to_offset(&snapshot),
 2681                            )
 2682                        })
 2683                        .collect();
 2684
 2685                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2686                        .await
 2687                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2688                        .log_err();
 2689                });
 2690                    }
 2691                }
 2692            }
 2693        }
 2694
 2695        cx.notify();
 2696    }
 2697
 2698    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2699        use text::ToOffset as _;
 2700        use text::ToPoint as _;
 2701
 2702        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2703            return;
 2704        }
 2705
 2706        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2707            return;
 2708        };
 2709
 2710        let snapshot = singleton.read(cx).snapshot();
 2711        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2712            let display_snapshot = display_map.snapshot(cx);
 2713
 2714            display_snapshot
 2715                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2716                .map(|fold| {
 2717                    fold.range.start.text_anchor.to_point(&snapshot)
 2718                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2719                })
 2720                .collect()
 2721        });
 2722        self.update_restoration_data(cx, |data| {
 2723            data.folds = inmemory_folds;
 2724        });
 2725
 2726        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2727            return;
 2728        };
 2729        let background_executor = cx.background_executor().clone();
 2730        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2731        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2732            display_map
 2733                .snapshot(cx)
 2734                .folds_in_range(0..snapshot.len())
 2735                .map(|fold| {
 2736                    (
 2737                        fold.range.start.text_anchor.to_offset(&snapshot),
 2738                        fold.range.end.text_anchor.to_offset(&snapshot),
 2739                    )
 2740                })
 2741                .collect()
 2742        });
 2743        self.serialize_folds = cx.background_spawn(async move {
 2744            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2745            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2746                .await
 2747                .with_context(|| {
 2748                    format!(
 2749                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2750                    )
 2751                })
 2752                .log_err();
 2753        });
 2754    }
 2755
 2756    pub fn sync_selections(
 2757        &mut self,
 2758        other: Entity<Editor>,
 2759        cx: &mut Context<Self>,
 2760    ) -> gpui::Subscription {
 2761        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2762        self.selections.change_with(cx, |selections| {
 2763            selections.select_anchors(other_selections);
 2764        });
 2765
 2766        let other_subscription =
 2767            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2768                EditorEvent::SelectionsChanged { local: true } => {
 2769                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2770                    if other_selections.is_empty() {
 2771                        return;
 2772                    }
 2773                    this.selections.change_with(cx, |selections| {
 2774                        selections.select_anchors(other_selections);
 2775                    });
 2776                }
 2777                _ => {}
 2778            });
 2779
 2780        let this_subscription =
 2781            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2782                EditorEvent::SelectionsChanged { local: true } => {
 2783                    let these_selections = this.selections.disjoint.to_vec();
 2784                    if these_selections.is_empty() {
 2785                        return;
 2786                    }
 2787                    other.update(cx, |other_editor, cx| {
 2788                        other_editor.selections.change_with(cx, |selections| {
 2789                            selections.select_anchors(these_selections);
 2790                        })
 2791                    });
 2792                }
 2793                _ => {}
 2794            });
 2795
 2796        Subscription::join(other_subscription, this_subscription)
 2797    }
 2798
 2799    pub fn change_selections<R>(
 2800        &mut self,
 2801        autoscroll: Option<Autoscroll>,
 2802        window: &mut Window,
 2803        cx: &mut Context<Self>,
 2804        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2805    ) -> R {
 2806        self.change_selections_inner(autoscroll, true, window, cx, change)
 2807    }
 2808
 2809    fn change_selections_inner<R>(
 2810        &mut self,
 2811        autoscroll: Option<Autoscroll>,
 2812        request_completions: bool,
 2813        window: &mut Window,
 2814        cx: &mut Context<Self>,
 2815        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2816    ) -> R {
 2817        let old_cursor_position = self.selections.newest_anchor().head();
 2818        self.push_to_selection_history();
 2819
 2820        let (changed, result) = self.selections.change_with(cx, change);
 2821
 2822        if changed {
 2823            if let Some(autoscroll) = autoscroll {
 2824                self.request_autoscroll(autoscroll, cx);
 2825            }
 2826            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2827
 2828            if self.should_open_signature_help_automatically(
 2829                &old_cursor_position,
 2830                self.signature_help_state.backspace_pressed(),
 2831                cx,
 2832            ) {
 2833                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2834            }
 2835            self.signature_help_state.set_backspace_pressed(false);
 2836        }
 2837
 2838        result
 2839    }
 2840
 2841    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2842    where
 2843        I: IntoIterator<Item = (Range<S>, T)>,
 2844        S: ToOffset,
 2845        T: Into<Arc<str>>,
 2846    {
 2847        if self.read_only(cx) {
 2848            return;
 2849        }
 2850
 2851        self.buffer
 2852            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2853    }
 2854
 2855    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2856    where
 2857        I: IntoIterator<Item = (Range<S>, T)>,
 2858        S: ToOffset,
 2859        T: Into<Arc<str>>,
 2860    {
 2861        if self.read_only(cx) {
 2862            return;
 2863        }
 2864
 2865        self.buffer.update(cx, |buffer, cx| {
 2866            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2867        });
 2868    }
 2869
 2870    pub fn edit_with_block_indent<I, S, T>(
 2871        &mut self,
 2872        edits: I,
 2873        original_indent_columns: Vec<Option<u32>>,
 2874        cx: &mut Context<Self>,
 2875    ) where
 2876        I: IntoIterator<Item = (Range<S>, T)>,
 2877        S: ToOffset,
 2878        T: Into<Arc<str>>,
 2879    {
 2880        if self.read_only(cx) {
 2881            return;
 2882        }
 2883
 2884        self.buffer.update(cx, |buffer, cx| {
 2885            buffer.edit(
 2886                edits,
 2887                Some(AutoindentMode::Block {
 2888                    original_indent_columns,
 2889                }),
 2890                cx,
 2891            )
 2892        });
 2893    }
 2894
 2895    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2896        self.hide_context_menu(window, cx);
 2897
 2898        match phase {
 2899            SelectPhase::Begin {
 2900                position,
 2901                add,
 2902                click_count,
 2903            } => self.begin_selection(position, add, click_count, window, cx),
 2904            SelectPhase::BeginColumnar {
 2905                position,
 2906                goal_column,
 2907                reset,
 2908            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2909            SelectPhase::Extend {
 2910                position,
 2911                click_count,
 2912            } => self.extend_selection(position, click_count, window, cx),
 2913            SelectPhase::Update {
 2914                position,
 2915                goal_column,
 2916                scroll_delta,
 2917            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2918            SelectPhase::End => self.end_selection(window, cx),
 2919        }
 2920    }
 2921
 2922    fn extend_selection(
 2923        &mut self,
 2924        position: DisplayPoint,
 2925        click_count: usize,
 2926        window: &mut Window,
 2927        cx: &mut Context<Self>,
 2928    ) {
 2929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2930        let tail = self.selections.newest::<usize>(cx).tail();
 2931        self.begin_selection(position, false, click_count, window, cx);
 2932
 2933        let position = position.to_offset(&display_map, Bias::Left);
 2934        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2935
 2936        let mut pending_selection = self
 2937            .selections
 2938            .pending_anchor()
 2939            .expect("extend_selection not called with pending selection");
 2940        if position >= tail {
 2941            pending_selection.start = tail_anchor;
 2942        } else {
 2943            pending_selection.end = tail_anchor;
 2944            pending_selection.reversed = true;
 2945        }
 2946
 2947        let mut pending_mode = self.selections.pending_mode().unwrap();
 2948        match &mut pending_mode {
 2949            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2950            _ => {}
 2951        }
 2952
 2953        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2954            s.set_pending(pending_selection, pending_mode)
 2955        });
 2956    }
 2957
 2958    fn begin_selection(
 2959        &mut self,
 2960        position: DisplayPoint,
 2961        add: bool,
 2962        click_count: usize,
 2963        window: &mut Window,
 2964        cx: &mut Context<Self>,
 2965    ) {
 2966        if !self.focus_handle.is_focused(window) {
 2967            self.last_focused_descendant = None;
 2968            window.focus(&self.focus_handle);
 2969        }
 2970
 2971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2972        let buffer = &display_map.buffer_snapshot;
 2973        let newest_selection = self.selections.newest_anchor().clone();
 2974        let position = display_map.clip_point(position, Bias::Left);
 2975
 2976        let start;
 2977        let end;
 2978        let mode;
 2979        let mut auto_scroll;
 2980        match click_count {
 2981            1 => {
 2982                start = buffer.anchor_before(position.to_point(&display_map));
 2983                end = start;
 2984                mode = SelectMode::Character;
 2985                auto_scroll = true;
 2986            }
 2987            2 => {
 2988                let range = movement::surrounding_word(&display_map, position);
 2989                start = buffer.anchor_before(range.start.to_point(&display_map));
 2990                end = buffer.anchor_before(range.end.to_point(&display_map));
 2991                mode = SelectMode::Word(start..end);
 2992                auto_scroll = true;
 2993            }
 2994            3 => {
 2995                let position = display_map
 2996                    .clip_point(position, Bias::Left)
 2997                    .to_point(&display_map);
 2998                let line_start = display_map.prev_line_boundary(position).0;
 2999                let next_line_start = buffer.clip_point(
 3000                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3001                    Bias::Left,
 3002                );
 3003                start = buffer.anchor_before(line_start);
 3004                end = buffer.anchor_before(next_line_start);
 3005                mode = SelectMode::Line(start..end);
 3006                auto_scroll = true;
 3007            }
 3008            _ => {
 3009                start = buffer.anchor_before(0);
 3010                end = buffer.anchor_before(buffer.len());
 3011                mode = SelectMode::All;
 3012                auto_scroll = false;
 3013            }
 3014        }
 3015        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3016
 3017        let point_to_delete: Option<usize> = {
 3018            let selected_points: Vec<Selection<Point>> =
 3019                self.selections.disjoint_in_range(start..end, cx);
 3020
 3021            if !add || click_count > 1 {
 3022                None
 3023            } else if !selected_points.is_empty() {
 3024                Some(selected_points[0].id)
 3025            } else {
 3026                let clicked_point_already_selected =
 3027                    self.selections.disjoint.iter().find(|selection| {
 3028                        selection.start.to_point(buffer) == start.to_point(buffer)
 3029                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3030                    });
 3031
 3032                clicked_point_already_selected.map(|selection| selection.id)
 3033            }
 3034        };
 3035
 3036        let selections_count = self.selections.count();
 3037
 3038        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3039            if let Some(point_to_delete) = point_to_delete {
 3040                s.delete(point_to_delete);
 3041
 3042                if selections_count == 1 {
 3043                    s.set_pending_anchor_range(start..end, mode);
 3044                }
 3045            } else {
 3046                if !add {
 3047                    s.clear_disjoint();
 3048                } else if click_count > 1 {
 3049                    s.delete(newest_selection.id)
 3050                }
 3051
 3052                s.set_pending_anchor_range(start..end, mode);
 3053            }
 3054        });
 3055    }
 3056
 3057    fn begin_columnar_selection(
 3058        &mut self,
 3059        position: DisplayPoint,
 3060        goal_column: u32,
 3061        reset: bool,
 3062        window: &mut Window,
 3063        cx: &mut Context<Self>,
 3064    ) {
 3065        if !self.focus_handle.is_focused(window) {
 3066            self.last_focused_descendant = None;
 3067            window.focus(&self.focus_handle);
 3068        }
 3069
 3070        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3071
 3072        if reset {
 3073            let pointer_position = display_map
 3074                .buffer_snapshot
 3075                .anchor_before(position.to_point(&display_map));
 3076
 3077            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3078                s.clear_disjoint();
 3079                s.set_pending_anchor_range(
 3080                    pointer_position..pointer_position,
 3081                    SelectMode::Character,
 3082                );
 3083            });
 3084        }
 3085
 3086        let tail = self.selections.newest::<Point>(cx).tail();
 3087        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3088
 3089        if !reset {
 3090            self.select_columns(
 3091                tail.to_display_point(&display_map),
 3092                position,
 3093                goal_column,
 3094                &display_map,
 3095                window,
 3096                cx,
 3097            );
 3098        }
 3099    }
 3100
 3101    fn update_selection(
 3102        &mut self,
 3103        position: DisplayPoint,
 3104        goal_column: u32,
 3105        scroll_delta: gpui::Point<f32>,
 3106        window: &mut Window,
 3107        cx: &mut Context<Self>,
 3108    ) {
 3109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3110
 3111        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3112            let tail = tail.to_display_point(&display_map);
 3113            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3114        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3115            let buffer = self.buffer.read(cx).snapshot(cx);
 3116            let head;
 3117            let tail;
 3118            let mode = self.selections.pending_mode().unwrap();
 3119            match &mode {
 3120                SelectMode::Character => {
 3121                    head = position.to_point(&display_map);
 3122                    tail = pending.tail().to_point(&buffer);
 3123                }
 3124                SelectMode::Word(original_range) => {
 3125                    let original_display_range = original_range.start.to_display_point(&display_map)
 3126                        ..original_range.end.to_display_point(&display_map);
 3127                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3128                        ..original_display_range.end.to_point(&display_map);
 3129                    if movement::is_inside_word(&display_map, position)
 3130                        || original_display_range.contains(&position)
 3131                    {
 3132                        let word_range = movement::surrounding_word(&display_map, position);
 3133                        if word_range.start < original_display_range.start {
 3134                            head = word_range.start.to_point(&display_map);
 3135                        } else {
 3136                            head = word_range.end.to_point(&display_map);
 3137                        }
 3138                    } else {
 3139                        head = position.to_point(&display_map);
 3140                    }
 3141
 3142                    if head <= original_buffer_range.start {
 3143                        tail = original_buffer_range.end;
 3144                    } else {
 3145                        tail = original_buffer_range.start;
 3146                    }
 3147                }
 3148                SelectMode::Line(original_range) => {
 3149                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3150
 3151                    let position = display_map
 3152                        .clip_point(position, Bias::Left)
 3153                        .to_point(&display_map);
 3154                    let line_start = display_map.prev_line_boundary(position).0;
 3155                    let next_line_start = buffer.clip_point(
 3156                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3157                        Bias::Left,
 3158                    );
 3159
 3160                    if line_start < original_range.start {
 3161                        head = line_start
 3162                    } else {
 3163                        head = next_line_start
 3164                    }
 3165
 3166                    if head <= original_range.start {
 3167                        tail = original_range.end;
 3168                    } else {
 3169                        tail = original_range.start;
 3170                    }
 3171                }
 3172                SelectMode::All => {
 3173                    return;
 3174                }
 3175            };
 3176
 3177            if head < tail {
 3178                pending.start = buffer.anchor_before(head);
 3179                pending.end = buffer.anchor_before(tail);
 3180                pending.reversed = true;
 3181            } else {
 3182                pending.start = buffer.anchor_before(tail);
 3183                pending.end = buffer.anchor_before(head);
 3184                pending.reversed = false;
 3185            }
 3186
 3187            self.change_selections(None, window, cx, |s| {
 3188                s.set_pending(pending, mode);
 3189            });
 3190        } else {
 3191            log::error!("update_selection dispatched with no pending selection");
 3192            return;
 3193        }
 3194
 3195        self.apply_scroll_delta(scroll_delta, window, cx);
 3196        cx.notify();
 3197    }
 3198
 3199    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3200        self.columnar_selection_tail.take();
 3201        if self.selections.pending_anchor().is_some() {
 3202            let selections = self.selections.all::<usize>(cx);
 3203            self.change_selections(None, window, cx, |s| {
 3204                s.select(selections);
 3205                s.clear_pending();
 3206            });
 3207        }
 3208    }
 3209
 3210    fn select_columns(
 3211        &mut self,
 3212        tail: DisplayPoint,
 3213        head: DisplayPoint,
 3214        goal_column: u32,
 3215        display_map: &DisplaySnapshot,
 3216        window: &mut Window,
 3217        cx: &mut Context<Self>,
 3218    ) {
 3219        let start_row = cmp::min(tail.row(), head.row());
 3220        let end_row = cmp::max(tail.row(), head.row());
 3221        let start_column = cmp::min(tail.column(), goal_column);
 3222        let end_column = cmp::max(tail.column(), goal_column);
 3223        let reversed = start_column < tail.column();
 3224
 3225        let selection_ranges = (start_row.0..=end_row.0)
 3226            .map(DisplayRow)
 3227            .filter_map(|row| {
 3228                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3229                    let start = display_map
 3230                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3231                        .to_point(display_map);
 3232                    let end = display_map
 3233                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3234                        .to_point(display_map);
 3235                    if reversed {
 3236                        Some(end..start)
 3237                    } else {
 3238                        Some(start..end)
 3239                    }
 3240                } else {
 3241                    None
 3242                }
 3243            })
 3244            .collect::<Vec<_>>();
 3245
 3246        self.change_selections(None, window, cx, |s| {
 3247            s.select_ranges(selection_ranges);
 3248        });
 3249        cx.notify();
 3250    }
 3251
 3252    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3253        self.selections
 3254            .all_adjusted(cx)
 3255            .iter()
 3256            .any(|selection| !selection.is_empty())
 3257    }
 3258
 3259    pub fn has_pending_nonempty_selection(&self) -> bool {
 3260        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3261            Some(Selection { start, end, .. }) => start != end,
 3262            None => false,
 3263        };
 3264
 3265        pending_nonempty_selection
 3266            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3267    }
 3268
 3269    pub fn has_pending_selection(&self) -> bool {
 3270        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3271    }
 3272
 3273    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3274        self.selection_mark_mode = false;
 3275
 3276        if self.clear_expanded_diff_hunks(cx) {
 3277            cx.notify();
 3278            return;
 3279        }
 3280        if self.dismiss_menus_and_popups(true, window, cx) {
 3281            return;
 3282        }
 3283
 3284        if self.mode.is_full()
 3285            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3286        {
 3287            return;
 3288        }
 3289
 3290        cx.propagate();
 3291    }
 3292
 3293    pub fn dismiss_menus_and_popups(
 3294        &mut self,
 3295        is_user_requested: bool,
 3296        window: &mut Window,
 3297        cx: &mut Context<Self>,
 3298    ) -> bool {
 3299        if self.take_rename(false, window, cx).is_some() {
 3300            return true;
 3301        }
 3302
 3303        if hide_hover(self, cx) {
 3304            return true;
 3305        }
 3306
 3307        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3308            return true;
 3309        }
 3310
 3311        if self.hide_context_menu(window, cx).is_some() {
 3312            return true;
 3313        }
 3314
 3315        if self.mouse_context_menu.take().is_some() {
 3316            return true;
 3317        }
 3318
 3319        if is_user_requested && self.discard_inline_completion(true, cx) {
 3320            return true;
 3321        }
 3322
 3323        if self.snippet_stack.pop().is_some() {
 3324            return true;
 3325        }
 3326
 3327        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3328            self.dismiss_diagnostics(cx);
 3329            return true;
 3330        }
 3331
 3332        false
 3333    }
 3334
 3335    fn linked_editing_ranges_for(
 3336        &self,
 3337        selection: Range<text::Anchor>,
 3338        cx: &App,
 3339    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3340        if self.linked_edit_ranges.is_empty() {
 3341            return None;
 3342        }
 3343        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3344            selection.end.buffer_id.and_then(|end_buffer_id| {
 3345                if selection.start.buffer_id != Some(end_buffer_id) {
 3346                    return None;
 3347                }
 3348                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3349                let snapshot = buffer.read(cx).snapshot();
 3350                self.linked_edit_ranges
 3351                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3352                    .map(|ranges| (ranges, snapshot, buffer))
 3353            })?;
 3354        use text::ToOffset as TO;
 3355        // find offset from the start of current range to current cursor position
 3356        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3357
 3358        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3359        let start_difference = start_offset - start_byte_offset;
 3360        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3361        let end_difference = end_offset - start_byte_offset;
 3362        // Current range has associated linked ranges.
 3363        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3364        for range in linked_ranges.iter() {
 3365            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3366            let end_offset = start_offset + end_difference;
 3367            let start_offset = start_offset + start_difference;
 3368            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3369                continue;
 3370            }
 3371            if self.selections.disjoint_anchor_ranges().any(|s| {
 3372                if s.start.buffer_id != selection.start.buffer_id
 3373                    || s.end.buffer_id != selection.end.buffer_id
 3374                {
 3375                    return false;
 3376                }
 3377                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3378                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3379            }) {
 3380                continue;
 3381            }
 3382            let start = buffer_snapshot.anchor_after(start_offset);
 3383            let end = buffer_snapshot.anchor_after(end_offset);
 3384            linked_edits
 3385                .entry(buffer.clone())
 3386                .or_default()
 3387                .push(start..end);
 3388        }
 3389        Some(linked_edits)
 3390    }
 3391
 3392    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3393        let text: Arc<str> = text.into();
 3394
 3395        if self.read_only(cx) {
 3396            return;
 3397        }
 3398
 3399        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3400
 3401        let selections = self.selections.all_adjusted(cx);
 3402        let mut bracket_inserted = false;
 3403        let mut edits = Vec::new();
 3404        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3405        let mut new_selections = Vec::with_capacity(selections.len());
 3406        let mut new_autoclose_regions = Vec::new();
 3407        let snapshot = self.buffer.read(cx).read(cx);
 3408        let mut clear_linked_edit_ranges = false;
 3409
 3410        for (selection, autoclose_region) in
 3411            self.selections_with_autoclose_regions(selections, &snapshot)
 3412        {
 3413            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3414                // Determine if the inserted text matches the opening or closing
 3415                // bracket of any of this language's bracket pairs.
 3416                let mut bracket_pair = None;
 3417                let mut is_bracket_pair_start = false;
 3418                let mut is_bracket_pair_end = false;
 3419                if !text.is_empty() {
 3420                    let mut bracket_pair_matching_end = None;
 3421                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3422                    //  and they are removing the character that triggered IME popup.
 3423                    for (pair, enabled) in scope.brackets() {
 3424                        if !pair.close && !pair.surround {
 3425                            continue;
 3426                        }
 3427
 3428                        if enabled && pair.start.ends_with(text.as_ref()) {
 3429                            let prefix_len = pair.start.len() - text.len();
 3430                            let preceding_text_matches_prefix = prefix_len == 0
 3431                                || (selection.start.column >= (prefix_len as u32)
 3432                                    && snapshot.contains_str_at(
 3433                                        Point::new(
 3434                                            selection.start.row,
 3435                                            selection.start.column - (prefix_len as u32),
 3436                                        ),
 3437                                        &pair.start[..prefix_len],
 3438                                    ));
 3439                            if preceding_text_matches_prefix {
 3440                                bracket_pair = Some(pair.clone());
 3441                                is_bracket_pair_start = true;
 3442                                break;
 3443                            }
 3444                        }
 3445                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3446                        {
 3447                            // take first bracket pair matching end, but don't break in case a later bracket
 3448                            // pair matches start
 3449                            bracket_pair_matching_end = Some(pair.clone());
 3450                        }
 3451                    }
 3452                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3453                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3454                        is_bracket_pair_end = true;
 3455                    }
 3456                }
 3457
 3458                if let Some(bracket_pair) = bracket_pair {
 3459                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3460                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3461                    let auto_surround =
 3462                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3463                    if selection.is_empty() {
 3464                        if is_bracket_pair_start {
 3465                            // If the inserted text is a suffix of an opening bracket and the
 3466                            // selection is preceded by the rest of the opening bracket, then
 3467                            // insert the closing bracket.
 3468                            let following_text_allows_autoclose = snapshot
 3469                                .chars_at(selection.start)
 3470                                .next()
 3471                                .map_or(true, |c| scope.should_autoclose_before(c));
 3472
 3473                            let preceding_text_allows_autoclose = selection.start.column == 0
 3474                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3475                                    true,
 3476                                    |c| {
 3477                                        bracket_pair.start != bracket_pair.end
 3478                                            || !snapshot
 3479                                                .char_classifier_at(selection.start)
 3480                                                .is_word(c)
 3481                                    },
 3482                                );
 3483
 3484                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3485                                && bracket_pair.start.len() == 1
 3486                            {
 3487                                let target = bracket_pair.start.chars().next().unwrap();
 3488                                let current_line_count = snapshot
 3489                                    .reversed_chars_at(selection.start)
 3490                                    .take_while(|&c| c != '\n')
 3491                                    .filter(|&c| c == target)
 3492                                    .count();
 3493                                current_line_count % 2 == 1
 3494                            } else {
 3495                                false
 3496                            };
 3497
 3498                            if autoclose
 3499                                && bracket_pair.close
 3500                                && following_text_allows_autoclose
 3501                                && preceding_text_allows_autoclose
 3502                                && !is_closing_quote
 3503                            {
 3504                                let anchor = snapshot.anchor_before(selection.end);
 3505                                new_selections.push((selection.map(|_| anchor), text.len()));
 3506                                new_autoclose_regions.push((
 3507                                    anchor,
 3508                                    text.len(),
 3509                                    selection.id,
 3510                                    bracket_pair.clone(),
 3511                                ));
 3512                                edits.push((
 3513                                    selection.range(),
 3514                                    format!("{}{}", text, bracket_pair.end).into(),
 3515                                ));
 3516                                bracket_inserted = true;
 3517                                continue;
 3518                            }
 3519                        }
 3520
 3521                        if let Some(region) = autoclose_region {
 3522                            // If the selection is followed by an auto-inserted closing bracket,
 3523                            // then don't insert that closing bracket again; just move the selection
 3524                            // past the closing bracket.
 3525                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3526                                && text.as_ref() == region.pair.end.as_str();
 3527                            if should_skip {
 3528                                let anchor = snapshot.anchor_after(selection.end);
 3529                                new_selections
 3530                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3531                                continue;
 3532                            }
 3533                        }
 3534
 3535                        let always_treat_brackets_as_autoclosed = snapshot
 3536                            .language_settings_at(selection.start, cx)
 3537                            .always_treat_brackets_as_autoclosed;
 3538                        if always_treat_brackets_as_autoclosed
 3539                            && is_bracket_pair_end
 3540                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3541                        {
 3542                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3543                            // and the inserted text is a closing bracket and the selection is followed
 3544                            // by the closing bracket then move the selection past the closing bracket.
 3545                            let anchor = snapshot.anchor_after(selection.end);
 3546                            new_selections.push((selection.map(|_| anchor), text.len()));
 3547                            continue;
 3548                        }
 3549                    }
 3550                    // If an opening bracket is 1 character long and is typed while
 3551                    // text is selected, then surround that text with the bracket pair.
 3552                    else if auto_surround
 3553                        && bracket_pair.surround
 3554                        && is_bracket_pair_start
 3555                        && bracket_pair.start.chars().count() == 1
 3556                    {
 3557                        edits.push((selection.start..selection.start, text.clone()));
 3558                        edits.push((
 3559                            selection.end..selection.end,
 3560                            bracket_pair.end.as_str().into(),
 3561                        ));
 3562                        bracket_inserted = true;
 3563                        new_selections.push((
 3564                            Selection {
 3565                                id: selection.id,
 3566                                start: snapshot.anchor_after(selection.start),
 3567                                end: snapshot.anchor_before(selection.end),
 3568                                reversed: selection.reversed,
 3569                                goal: selection.goal,
 3570                            },
 3571                            0,
 3572                        ));
 3573                        continue;
 3574                    }
 3575                }
 3576            }
 3577
 3578            if self.auto_replace_emoji_shortcode
 3579                && selection.is_empty()
 3580                && text.as_ref().ends_with(':')
 3581            {
 3582                if let Some(possible_emoji_short_code) =
 3583                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3584                {
 3585                    if !possible_emoji_short_code.is_empty() {
 3586                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3587                            let emoji_shortcode_start = Point::new(
 3588                                selection.start.row,
 3589                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3590                            );
 3591
 3592                            // Remove shortcode from buffer
 3593                            edits.push((
 3594                                emoji_shortcode_start..selection.start,
 3595                                "".to_string().into(),
 3596                            ));
 3597                            new_selections.push((
 3598                                Selection {
 3599                                    id: selection.id,
 3600                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3601                                    end: snapshot.anchor_before(selection.start),
 3602                                    reversed: selection.reversed,
 3603                                    goal: selection.goal,
 3604                                },
 3605                                0,
 3606                            ));
 3607
 3608                            // Insert emoji
 3609                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3610                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3611                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3612
 3613                            continue;
 3614                        }
 3615                    }
 3616                }
 3617            }
 3618
 3619            // If not handling any auto-close operation, then just replace the selected
 3620            // text with the given input and move the selection to the end of the
 3621            // newly inserted text.
 3622            let anchor = snapshot.anchor_after(selection.end);
 3623            if !self.linked_edit_ranges.is_empty() {
 3624                let start_anchor = snapshot.anchor_before(selection.start);
 3625
 3626                let is_word_char = text.chars().next().map_or(true, |char| {
 3627                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3628                    classifier.is_word(char)
 3629                });
 3630
 3631                if is_word_char {
 3632                    if let Some(ranges) = self
 3633                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3634                    {
 3635                        for (buffer, edits) in ranges {
 3636                            linked_edits
 3637                                .entry(buffer.clone())
 3638                                .or_default()
 3639                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3640                        }
 3641                    }
 3642                } else {
 3643                    clear_linked_edit_ranges = true;
 3644                }
 3645            }
 3646
 3647            new_selections.push((selection.map(|_| anchor), 0));
 3648            edits.push((selection.start..selection.end, text.clone()));
 3649        }
 3650
 3651        drop(snapshot);
 3652
 3653        self.transact(window, cx, |this, window, cx| {
 3654            if clear_linked_edit_ranges {
 3655                this.linked_edit_ranges.clear();
 3656            }
 3657            let initial_buffer_versions =
 3658                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3659
 3660            this.buffer.update(cx, |buffer, cx| {
 3661                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3662            });
 3663            for (buffer, edits) in linked_edits {
 3664                buffer.update(cx, |buffer, cx| {
 3665                    let snapshot = buffer.snapshot();
 3666                    let edits = edits
 3667                        .into_iter()
 3668                        .map(|(range, text)| {
 3669                            use text::ToPoint as TP;
 3670                            let end_point = TP::to_point(&range.end, &snapshot);
 3671                            let start_point = TP::to_point(&range.start, &snapshot);
 3672                            (start_point..end_point, text)
 3673                        })
 3674                        .sorted_by_key(|(range, _)| range.start);
 3675                    buffer.edit(edits, None, cx);
 3676                })
 3677            }
 3678            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3679            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3680            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3681            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3682                .zip(new_selection_deltas)
 3683                .map(|(selection, delta)| Selection {
 3684                    id: selection.id,
 3685                    start: selection.start + delta,
 3686                    end: selection.end + delta,
 3687                    reversed: selection.reversed,
 3688                    goal: SelectionGoal::None,
 3689                })
 3690                .collect::<Vec<_>>();
 3691
 3692            let mut i = 0;
 3693            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3694                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3695                let start = map.buffer_snapshot.anchor_before(position);
 3696                let end = map.buffer_snapshot.anchor_after(position);
 3697                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3698                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3699                        Ordering::Less => i += 1,
 3700                        Ordering::Greater => break,
 3701                        Ordering::Equal => {
 3702                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3703                                Ordering::Less => i += 1,
 3704                                Ordering::Equal => break,
 3705                                Ordering::Greater => break,
 3706                            }
 3707                        }
 3708                    }
 3709                }
 3710                this.autoclose_regions.insert(
 3711                    i,
 3712                    AutocloseRegion {
 3713                        selection_id,
 3714                        range: start..end,
 3715                        pair,
 3716                    },
 3717                );
 3718            }
 3719
 3720            let had_active_inline_completion = this.has_active_inline_completion();
 3721            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3722                s.select(new_selections)
 3723            });
 3724
 3725            if !bracket_inserted {
 3726                if let Some(on_type_format_task) =
 3727                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3728                {
 3729                    on_type_format_task.detach_and_log_err(cx);
 3730                }
 3731            }
 3732
 3733            let editor_settings = EditorSettings::get_global(cx);
 3734            if bracket_inserted
 3735                && (editor_settings.auto_signature_help
 3736                    || editor_settings.show_signature_help_after_edits)
 3737            {
 3738                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3739            }
 3740
 3741            let trigger_in_words =
 3742                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3743            if this.hard_wrap.is_some() {
 3744                let latest: Range<Point> = this.selections.newest(cx).range();
 3745                if latest.is_empty()
 3746                    && this
 3747                        .buffer()
 3748                        .read(cx)
 3749                        .snapshot(cx)
 3750                        .line_len(MultiBufferRow(latest.start.row))
 3751                        == latest.start.column
 3752                {
 3753                    this.rewrap_impl(
 3754                        RewrapOptions {
 3755                            override_language_settings: true,
 3756                            preserve_existing_whitespace: true,
 3757                        },
 3758                        cx,
 3759                    )
 3760                }
 3761            }
 3762            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3763            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3764            this.refresh_inline_completion(true, false, window, cx);
 3765            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3766        });
 3767    }
 3768
 3769    fn find_possible_emoji_shortcode_at_position(
 3770        snapshot: &MultiBufferSnapshot,
 3771        position: Point,
 3772    ) -> Option<String> {
 3773        let mut chars = Vec::new();
 3774        let mut found_colon = false;
 3775        for char in snapshot.reversed_chars_at(position).take(100) {
 3776            // Found a possible emoji shortcode in the middle of the buffer
 3777            if found_colon {
 3778                if char.is_whitespace() {
 3779                    chars.reverse();
 3780                    return Some(chars.iter().collect());
 3781                }
 3782                // If the previous character is not a whitespace, we are in the middle of a word
 3783                // and we only want to complete the shortcode if the word is made up of other emojis
 3784                let mut containing_word = String::new();
 3785                for ch in snapshot
 3786                    .reversed_chars_at(position)
 3787                    .skip(chars.len() + 1)
 3788                    .take(100)
 3789                {
 3790                    if ch.is_whitespace() {
 3791                        break;
 3792                    }
 3793                    containing_word.push(ch);
 3794                }
 3795                let containing_word = containing_word.chars().rev().collect::<String>();
 3796                if util::word_consists_of_emojis(containing_word.as_str()) {
 3797                    chars.reverse();
 3798                    return Some(chars.iter().collect());
 3799                }
 3800            }
 3801
 3802            if char.is_whitespace() || !char.is_ascii() {
 3803                return None;
 3804            }
 3805            if char == ':' {
 3806                found_colon = true;
 3807            } else {
 3808                chars.push(char);
 3809            }
 3810        }
 3811        // Found a possible emoji shortcode at the beginning of the buffer
 3812        chars.reverse();
 3813        Some(chars.iter().collect())
 3814    }
 3815
 3816    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3817        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3818        self.transact(window, cx, |this, window, cx| {
 3819            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3820                let selections = this.selections.all::<usize>(cx);
 3821                let multi_buffer = this.buffer.read(cx);
 3822                let buffer = multi_buffer.snapshot(cx);
 3823                selections
 3824                    .iter()
 3825                    .map(|selection| {
 3826                        let start_point = selection.start.to_point(&buffer);
 3827                        let mut indent =
 3828                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3829                        indent.len = cmp::min(indent.len, start_point.column);
 3830                        let start = selection.start;
 3831                        let end = selection.end;
 3832                        let selection_is_empty = start == end;
 3833                        let language_scope = buffer.language_scope_at(start);
 3834                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3835                            &language_scope
 3836                        {
 3837                            let insert_extra_newline =
 3838                                insert_extra_newline_brackets(&buffer, start..end, language)
 3839                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3840
 3841                            // Comment extension on newline is allowed only for cursor selections
 3842                            let comment_delimiter = maybe!({
 3843                                if !selection_is_empty {
 3844                                    return None;
 3845                                }
 3846
 3847                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3848                                    return None;
 3849                                }
 3850
 3851                                let delimiters = language.line_comment_prefixes();
 3852                                let max_len_of_delimiter =
 3853                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3854                                let (snapshot, range) =
 3855                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3856
 3857                                let mut index_of_first_non_whitespace = 0;
 3858                                let comment_candidate = snapshot
 3859                                    .chars_for_range(range)
 3860                                    .skip_while(|c| {
 3861                                        let should_skip = c.is_whitespace();
 3862                                        if should_skip {
 3863                                            index_of_first_non_whitespace += 1;
 3864                                        }
 3865                                        should_skip
 3866                                    })
 3867                                    .take(max_len_of_delimiter)
 3868                                    .collect::<String>();
 3869                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3870                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3871                                })?;
 3872                                let cursor_is_placed_after_comment_marker =
 3873                                    index_of_first_non_whitespace + comment_prefix.len()
 3874                                        <= start_point.column as usize;
 3875                                if cursor_is_placed_after_comment_marker {
 3876                                    Some(comment_prefix.clone())
 3877                                } else {
 3878                                    None
 3879                                }
 3880                            });
 3881                            (comment_delimiter, insert_extra_newline)
 3882                        } else {
 3883                            (None, false)
 3884                        };
 3885
 3886                        let capacity_for_delimiter = comment_delimiter
 3887                            .as_deref()
 3888                            .map(str::len)
 3889                            .unwrap_or_default();
 3890                        let mut new_text =
 3891                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3892                        new_text.push('\n');
 3893                        new_text.extend(indent.chars());
 3894                        if let Some(delimiter) = &comment_delimiter {
 3895                            new_text.push_str(delimiter);
 3896                        }
 3897                        if insert_extra_newline {
 3898                            new_text = new_text.repeat(2);
 3899                        }
 3900
 3901                        let anchor = buffer.anchor_after(end);
 3902                        let new_selection = selection.map(|_| anchor);
 3903                        (
 3904                            (start..end, new_text),
 3905                            (insert_extra_newline, new_selection),
 3906                        )
 3907                    })
 3908                    .unzip()
 3909            };
 3910
 3911            this.edit_with_autoindent(edits, cx);
 3912            let buffer = this.buffer.read(cx).snapshot(cx);
 3913            let new_selections = selection_fixup_info
 3914                .into_iter()
 3915                .map(|(extra_newline_inserted, new_selection)| {
 3916                    let mut cursor = new_selection.end.to_point(&buffer);
 3917                    if extra_newline_inserted {
 3918                        cursor.row -= 1;
 3919                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3920                    }
 3921                    new_selection.map(|_| cursor)
 3922                })
 3923                .collect();
 3924
 3925            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3926                s.select(new_selections)
 3927            });
 3928            this.refresh_inline_completion(true, false, window, cx);
 3929        });
 3930    }
 3931
 3932    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3933        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3934
 3935        let buffer = self.buffer.read(cx);
 3936        let snapshot = buffer.snapshot(cx);
 3937
 3938        let mut edits = Vec::new();
 3939        let mut rows = Vec::new();
 3940
 3941        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3942            let cursor = selection.head();
 3943            let row = cursor.row;
 3944
 3945            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3946
 3947            let newline = "\n".to_string();
 3948            edits.push((start_of_line..start_of_line, newline));
 3949
 3950            rows.push(row + rows_inserted as u32);
 3951        }
 3952
 3953        self.transact(window, cx, |editor, window, cx| {
 3954            editor.edit(edits, cx);
 3955
 3956            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3957                let mut index = 0;
 3958                s.move_cursors_with(|map, _, _| {
 3959                    let row = rows[index];
 3960                    index += 1;
 3961
 3962                    let point = Point::new(row, 0);
 3963                    let boundary = map.next_line_boundary(point).1;
 3964                    let clipped = map.clip_point(boundary, Bias::Left);
 3965
 3966                    (clipped, SelectionGoal::None)
 3967                });
 3968            });
 3969
 3970            let mut indent_edits = Vec::new();
 3971            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3972            for row in rows {
 3973                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3974                for (row, indent) in indents {
 3975                    if indent.len == 0 {
 3976                        continue;
 3977                    }
 3978
 3979                    let text = match indent.kind {
 3980                        IndentKind::Space => " ".repeat(indent.len as usize),
 3981                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3982                    };
 3983                    let point = Point::new(row.0, 0);
 3984                    indent_edits.push((point..point, text));
 3985                }
 3986            }
 3987            editor.edit(indent_edits, cx);
 3988        });
 3989    }
 3990
 3991    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3992        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3993
 3994        let buffer = self.buffer.read(cx);
 3995        let snapshot = buffer.snapshot(cx);
 3996
 3997        let mut edits = Vec::new();
 3998        let mut rows = Vec::new();
 3999        let mut rows_inserted = 0;
 4000
 4001        for selection in self.selections.all_adjusted(cx) {
 4002            let cursor = selection.head();
 4003            let row = cursor.row;
 4004
 4005            let point = Point::new(row + 1, 0);
 4006            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4007
 4008            let newline = "\n".to_string();
 4009            edits.push((start_of_line..start_of_line, newline));
 4010
 4011            rows_inserted += 1;
 4012            rows.push(row + rows_inserted);
 4013        }
 4014
 4015        self.transact(window, cx, |editor, window, cx| {
 4016            editor.edit(edits, cx);
 4017
 4018            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4019                let mut index = 0;
 4020                s.move_cursors_with(|map, _, _| {
 4021                    let row = rows[index];
 4022                    index += 1;
 4023
 4024                    let point = Point::new(row, 0);
 4025                    let boundary = map.next_line_boundary(point).1;
 4026                    let clipped = map.clip_point(boundary, Bias::Left);
 4027
 4028                    (clipped, SelectionGoal::None)
 4029                });
 4030            });
 4031
 4032            let mut indent_edits = Vec::new();
 4033            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4034            for row in rows {
 4035                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4036                for (row, indent) in indents {
 4037                    if indent.len == 0 {
 4038                        continue;
 4039                    }
 4040
 4041                    let text = match indent.kind {
 4042                        IndentKind::Space => " ".repeat(indent.len as usize),
 4043                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4044                    };
 4045                    let point = Point::new(row.0, 0);
 4046                    indent_edits.push((point..point, text));
 4047                }
 4048            }
 4049            editor.edit(indent_edits, cx);
 4050        });
 4051    }
 4052
 4053    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4054        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4055            original_indent_columns: Vec::new(),
 4056        });
 4057        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4058    }
 4059
 4060    fn insert_with_autoindent_mode(
 4061        &mut self,
 4062        text: &str,
 4063        autoindent_mode: Option<AutoindentMode>,
 4064        window: &mut Window,
 4065        cx: &mut Context<Self>,
 4066    ) {
 4067        if self.read_only(cx) {
 4068            return;
 4069        }
 4070
 4071        let text: Arc<str> = text.into();
 4072        self.transact(window, cx, |this, window, cx| {
 4073            let old_selections = this.selections.all_adjusted(cx);
 4074            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4075                let anchors = {
 4076                    let snapshot = buffer.read(cx);
 4077                    old_selections
 4078                        .iter()
 4079                        .map(|s| {
 4080                            let anchor = snapshot.anchor_after(s.head());
 4081                            s.map(|_| anchor)
 4082                        })
 4083                        .collect::<Vec<_>>()
 4084                };
 4085                buffer.edit(
 4086                    old_selections
 4087                        .iter()
 4088                        .map(|s| (s.start..s.end, text.clone())),
 4089                    autoindent_mode,
 4090                    cx,
 4091                );
 4092                anchors
 4093            });
 4094
 4095            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4096                s.select_anchors(selection_anchors);
 4097            });
 4098
 4099            cx.notify();
 4100        });
 4101    }
 4102
 4103    fn trigger_completion_on_input(
 4104        &mut self,
 4105        text: &str,
 4106        trigger_in_words: bool,
 4107        window: &mut Window,
 4108        cx: &mut Context<Self>,
 4109    ) {
 4110        let ignore_completion_provider = self
 4111            .context_menu
 4112            .borrow()
 4113            .as_ref()
 4114            .map(|menu| match menu {
 4115                CodeContextMenu::Completions(completions_menu) => {
 4116                    completions_menu.ignore_completion_provider
 4117                }
 4118                CodeContextMenu::CodeActions(_) => false,
 4119            })
 4120            .unwrap_or(false);
 4121
 4122        if ignore_completion_provider {
 4123            self.show_word_completions(&ShowWordCompletions, window, cx);
 4124        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4125            self.show_completions(
 4126                &ShowCompletions {
 4127                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4128                },
 4129                window,
 4130                cx,
 4131            );
 4132        } else {
 4133            self.hide_context_menu(window, cx);
 4134        }
 4135    }
 4136
 4137    fn is_completion_trigger(
 4138        &self,
 4139        text: &str,
 4140        trigger_in_words: bool,
 4141        cx: &mut Context<Self>,
 4142    ) -> bool {
 4143        let position = self.selections.newest_anchor().head();
 4144        let multibuffer = self.buffer.read(cx);
 4145        let Some(buffer) = position
 4146            .buffer_id
 4147            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4148        else {
 4149            return false;
 4150        };
 4151
 4152        if let Some(completion_provider) = &self.completion_provider {
 4153            completion_provider.is_completion_trigger(
 4154                &buffer,
 4155                position.text_anchor,
 4156                text,
 4157                trigger_in_words,
 4158                cx,
 4159            )
 4160        } else {
 4161            false
 4162        }
 4163    }
 4164
 4165    /// If any empty selections is touching the start of its innermost containing autoclose
 4166    /// region, expand it to select the brackets.
 4167    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4168        let selections = self.selections.all::<usize>(cx);
 4169        let buffer = self.buffer.read(cx).read(cx);
 4170        let new_selections = self
 4171            .selections_with_autoclose_regions(selections, &buffer)
 4172            .map(|(mut selection, region)| {
 4173                if !selection.is_empty() {
 4174                    return selection;
 4175                }
 4176
 4177                if let Some(region) = region {
 4178                    let mut range = region.range.to_offset(&buffer);
 4179                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4180                        range.start -= region.pair.start.len();
 4181                        if buffer.contains_str_at(range.start, &region.pair.start)
 4182                            && buffer.contains_str_at(range.end, &region.pair.end)
 4183                        {
 4184                            range.end += region.pair.end.len();
 4185                            selection.start = range.start;
 4186                            selection.end = range.end;
 4187
 4188                            return selection;
 4189                        }
 4190                    }
 4191                }
 4192
 4193                let always_treat_brackets_as_autoclosed = buffer
 4194                    .language_settings_at(selection.start, cx)
 4195                    .always_treat_brackets_as_autoclosed;
 4196
 4197                if !always_treat_brackets_as_autoclosed {
 4198                    return selection;
 4199                }
 4200
 4201                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4202                    for (pair, enabled) in scope.brackets() {
 4203                        if !enabled || !pair.close {
 4204                            continue;
 4205                        }
 4206
 4207                        if buffer.contains_str_at(selection.start, &pair.end) {
 4208                            let pair_start_len = pair.start.len();
 4209                            if buffer.contains_str_at(
 4210                                selection.start.saturating_sub(pair_start_len),
 4211                                &pair.start,
 4212                            ) {
 4213                                selection.start -= pair_start_len;
 4214                                selection.end += pair.end.len();
 4215
 4216                                return selection;
 4217                            }
 4218                        }
 4219                    }
 4220                }
 4221
 4222                selection
 4223            })
 4224            .collect();
 4225
 4226        drop(buffer);
 4227        self.change_selections(None, window, cx, |selections| {
 4228            selections.select(new_selections)
 4229        });
 4230    }
 4231
 4232    /// Iterate the given selections, and for each one, find the smallest surrounding
 4233    /// autoclose region. This uses the ordering of the selections and the autoclose
 4234    /// regions to avoid repeated comparisons.
 4235    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4236        &'a self,
 4237        selections: impl IntoIterator<Item = Selection<D>>,
 4238        buffer: &'a MultiBufferSnapshot,
 4239    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4240        let mut i = 0;
 4241        let mut regions = self.autoclose_regions.as_slice();
 4242        selections.into_iter().map(move |selection| {
 4243            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4244
 4245            let mut enclosing = None;
 4246            while let Some(pair_state) = regions.get(i) {
 4247                if pair_state.range.end.to_offset(buffer) < range.start {
 4248                    regions = &regions[i + 1..];
 4249                    i = 0;
 4250                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4251                    break;
 4252                } else {
 4253                    if pair_state.selection_id == selection.id {
 4254                        enclosing = Some(pair_state);
 4255                    }
 4256                    i += 1;
 4257                }
 4258            }
 4259
 4260            (selection, enclosing)
 4261        })
 4262    }
 4263
 4264    /// Remove any autoclose regions that no longer contain their selection.
 4265    fn invalidate_autoclose_regions(
 4266        &mut self,
 4267        mut selections: &[Selection<Anchor>],
 4268        buffer: &MultiBufferSnapshot,
 4269    ) {
 4270        self.autoclose_regions.retain(|state| {
 4271            let mut i = 0;
 4272            while let Some(selection) = selections.get(i) {
 4273                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4274                    selections = &selections[1..];
 4275                    continue;
 4276                }
 4277                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4278                    break;
 4279                }
 4280                if selection.id == state.selection_id {
 4281                    return true;
 4282                } else {
 4283                    i += 1;
 4284                }
 4285            }
 4286            false
 4287        });
 4288    }
 4289
 4290    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4291        let offset = position.to_offset(buffer);
 4292        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4293        if offset > word_range.start && kind == Some(CharKind::Word) {
 4294            Some(
 4295                buffer
 4296                    .text_for_range(word_range.start..offset)
 4297                    .collect::<String>(),
 4298            )
 4299        } else {
 4300            None
 4301        }
 4302    }
 4303
 4304    pub fn toggle_inline_values(
 4305        &mut self,
 4306        _: &ToggleInlineValues,
 4307        _: &mut Window,
 4308        cx: &mut Context<Self>,
 4309    ) {
 4310        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4311
 4312        self.refresh_inline_values(cx);
 4313    }
 4314
 4315    pub fn toggle_inlay_hints(
 4316        &mut self,
 4317        _: &ToggleInlayHints,
 4318        _: &mut Window,
 4319        cx: &mut Context<Self>,
 4320    ) {
 4321        self.refresh_inlay_hints(
 4322            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4323            cx,
 4324        );
 4325    }
 4326
 4327    pub fn inlay_hints_enabled(&self) -> bool {
 4328        self.inlay_hint_cache.enabled
 4329    }
 4330
 4331    pub fn inline_values_enabled(&self) -> bool {
 4332        self.inline_value_cache.enabled
 4333    }
 4334
 4335    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4336        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4337            return;
 4338        }
 4339
 4340        let reason_description = reason.description();
 4341        let ignore_debounce = matches!(
 4342            reason,
 4343            InlayHintRefreshReason::SettingsChange(_)
 4344                | InlayHintRefreshReason::Toggle(_)
 4345                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4346                | InlayHintRefreshReason::ModifiersChanged(_)
 4347        );
 4348        let (invalidate_cache, required_languages) = match reason {
 4349            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4350                match self.inlay_hint_cache.modifiers_override(enabled) {
 4351                    Some(enabled) => {
 4352                        if enabled {
 4353                            (InvalidationStrategy::RefreshRequested, None)
 4354                        } else {
 4355                            self.splice_inlays(
 4356                                &self
 4357                                    .visible_inlay_hints(cx)
 4358                                    .iter()
 4359                                    .map(|inlay| inlay.id)
 4360                                    .collect::<Vec<InlayId>>(),
 4361                                Vec::new(),
 4362                                cx,
 4363                            );
 4364                            return;
 4365                        }
 4366                    }
 4367                    None => return,
 4368                }
 4369            }
 4370            InlayHintRefreshReason::Toggle(enabled) => {
 4371                if self.inlay_hint_cache.toggle(enabled) {
 4372                    if enabled {
 4373                        (InvalidationStrategy::RefreshRequested, None)
 4374                    } else {
 4375                        self.splice_inlays(
 4376                            &self
 4377                                .visible_inlay_hints(cx)
 4378                                .iter()
 4379                                .map(|inlay| inlay.id)
 4380                                .collect::<Vec<InlayId>>(),
 4381                            Vec::new(),
 4382                            cx,
 4383                        );
 4384                        return;
 4385                    }
 4386                } else {
 4387                    return;
 4388                }
 4389            }
 4390            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4391                match self.inlay_hint_cache.update_settings(
 4392                    &self.buffer,
 4393                    new_settings,
 4394                    self.visible_inlay_hints(cx),
 4395                    cx,
 4396                ) {
 4397                    ControlFlow::Break(Some(InlaySplice {
 4398                        to_remove,
 4399                        to_insert,
 4400                    })) => {
 4401                        self.splice_inlays(&to_remove, to_insert, cx);
 4402                        return;
 4403                    }
 4404                    ControlFlow::Break(None) => return,
 4405                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4406                }
 4407            }
 4408            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4409                if let Some(InlaySplice {
 4410                    to_remove,
 4411                    to_insert,
 4412                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4413                {
 4414                    self.splice_inlays(&to_remove, to_insert, cx);
 4415                }
 4416                self.display_map.update(cx, |display_map, _| {
 4417                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4418                });
 4419                return;
 4420            }
 4421            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4422            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4423                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4424            }
 4425            InlayHintRefreshReason::RefreshRequested => {
 4426                (InvalidationStrategy::RefreshRequested, None)
 4427            }
 4428        };
 4429
 4430        if let Some(InlaySplice {
 4431            to_remove,
 4432            to_insert,
 4433        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4434            reason_description,
 4435            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4436            invalidate_cache,
 4437            ignore_debounce,
 4438            cx,
 4439        ) {
 4440            self.splice_inlays(&to_remove, to_insert, cx);
 4441        }
 4442    }
 4443
 4444    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4445        self.display_map
 4446            .read(cx)
 4447            .current_inlays()
 4448            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4449            .cloned()
 4450            .collect()
 4451    }
 4452
 4453    pub fn excerpts_for_inlay_hints_query(
 4454        &self,
 4455        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4456        cx: &mut Context<Editor>,
 4457    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4458        let Some(project) = self.project.as_ref() else {
 4459            return HashMap::default();
 4460        };
 4461        let project = project.read(cx);
 4462        let multi_buffer = self.buffer().read(cx);
 4463        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4464        let multi_buffer_visible_start = self
 4465            .scroll_manager
 4466            .anchor()
 4467            .anchor
 4468            .to_point(&multi_buffer_snapshot);
 4469        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4470            multi_buffer_visible_start
 4471                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4472            Bias::Left,
 4473        );
 4474        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4475        multi_buffer_snapshot
 4476            .range_to_buffer_ranges(multi_buffer_visible_range)
 4477            .into_iter()
 4478            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4479            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4480                let buffer_file = project::File::from_dyn(buffer.file())?;
 4481                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4482                let worktree_entry = buffer_worktree
 4483                    .read(cx)
 4484                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4485                if worktree_entry.is_ignored {
 4486                    return None;
 4487                }
 4488
 4489                let language = buffer.language()?;
 4490                if let Some(restrict_to_languages) = restrict_to_languages {
 4491                    if !restrict_to_languages.contains(language) {
 4492                        return None;
 4493                    }
 4494                }
 4495                Some((
 4496                    excerpt_id,
 4497                    (
 4498                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4499                        buffer.version().clone(),
 4500                        excerpt_visible_range,
 4501                    ),
 4502                ))
 4503            })
 4504            .collect()
 4505    }
 4506
 4507    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4508        TextLayoutDetails {
 4509            text_system: window.text_system().clone(),
 4510            editor_style: self.style.clone().unwrap(),
 4511            rem_size: window.rem_size(),
 4512            scroll_anchor: self.scroll_manager.anchor(),
 4513            visible_rows: self.visible_line_count(),
 4514            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4515        }
 4516    }
 4517
 4518    pub fn splice_inlays(
 4519        &self,
 4520        to_remove: &[InlayId],
 4521        to_insert: Vec<Inlay>,
 4522        cx: &mut Context<Self>,
 4523    ) {
 4524        self.display_map.update(cx, |display_map, cx| {
 4525            display_map.splice_inlays(to_remove, to_insert, cx)
 4526        });
 4527        cx.notify();
 4528    }
 4529
 4530    fn trigger_on_type_formatting(
 4531        &self,
 4532        input: String,
 4533        window: &mut Window,
 4534        cx: &mut Context<Self>,
 4535    ) -> Option<Task<Result<()>>> {
 4536        if input.len() != 1 {
 4537            return None;
 4538        }
 4539
 4540        let project = self.project.as_ref()?;
 4541        let position = self.selections.newest_anchor().head();
 4542        let (buffer, buffer_position) = self
 4543            .buffer
 4544            .read(cx)
 4545            .text_anchor_for_position(position, cx)?;
 4546
 4547        let settings = language_settings::language_settings(
 4548            buffer
 4549                .read(cx)
 4550                .language_at(buffer_position)
 4551                .map(|l| l.name()),
 4552            buffer.read(cx).file(),
 4553            cx,
 4554        );
 4555        if !settings.use_on_type_format {
 4556            return None;
 4557        }
 4558
 4559        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4560        // hence we do LSP request & edit on host side only — add formats to host's history.
 4561        let push_to_lsp_host_history = true;
 4562        // If this is not the host, append its history with new edits.
 4563        let push_to_client_history = project.read(cx).is_via_collab();
 4564
 4565        let on_type_formatting = project.update(cx, |project, cx| {
 4566            project.on_type_format(
 4567                buffer.clone(),
 4568                buffer_position,
 4569                input,
 4570                push_to_lsp_host_history,
 4571                cx,
 4572            )
 4573        });
 4574        Some(cx.spawn_in(window, async move |editor, cx| {
 4575            if let Some(transaction) = on_type_formatting.await? {
 4576                if push_to_client_history {
 4577                    buffer
 4578                        .update(cx, |buffer, _| {
 4579                            buffer.push_transaction(transaction, Instant::now());
 4580                            buffer.finalize_last_transaction();
 4581                        })
 4582                        .ok();
 4583                }
 4584                editor.update(cx, |editor, cx| {
 4585                    editor.refresh_document_highlights(cx);
 4586                })?;
 4587            }
 4588            Ok(())
 4589        }))
 4590    }
 4591
 4592    pub fn show_word_completions(
 4593        &mut self,
 4594        _: &ShowWordCompletions,
 4595        window: &mut Window,
 4596        cx: &mut Context<Self>,
 4597    ) {
 4598        self.open_completions_menu(true, None, window, cx);
 4599    }
 4600
 4601    pub fn show_completions(
 4602        &mut self,
 4603        options: &ShowCompletions,
 4604        window: &mut Window,
 4605        cx: &mut Context<Self>,
 4606    ) {
 4607        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4608    }
 4609
 4610    fn open_completions_menu(
 4611        &mut self,
 4612        ignore_completion_provider: bool,
 4613        trigger: Option<&str>,
 4614        window: &mut Window,
 4615        cx: &mut Context<Self>,
 4616    ) {
 4617        if self.pending_rename.is_some() {
 4618            return;
 4619        }
 4620        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4621            return;
 4622        }
 4623
 4624        let position = self.selections.newest_anchor().head();
 4625        if position.diff_base_anchor.is_some() {
 4626            return;
 4627        }
 4628        let (buffer, buffer_position) =
 4629            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4630                output
 4631            } else {
 4632                return;
 4633            };
 4634        let buffer_snapshot = buffer.read(cx).snapshot();
 4635        let show_completion_documentation = buffer_snapshot
 4636            .settings_at(buffer_position, cx)
 4637            .show_completion_documentation;
 4638
 4639        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4640
 4641        let trigger_kind = match trigger {
 4642            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4643                CompletionTriggerKind::TRIGGER_CHARACTER
 4644            }
 4645            _ => CompletionTriggerKind::INVOKED,
 4646        };
 4647        let completion_context = CompletionContext {
 4648            trigger_character: trigger.and_then(|trigger| {
 4649                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4650                    Some(String::from(trigger))
 4651                } else {
 4652                    None
 4653                }
 4654            }),
 4655            trigger_kind,
 4656        };
 4657
 4658        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4659        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4660            let word_to_exclude = buffer_snapshot
 4661                .text_for_range(old_range.clone())
 4662                .collect::<String>();
 4663            (
 4664                buffer_snapshot.anchor_before(old_range.start)
 4665                    ..buffer_snapshot.anchor_after(old_range.end),
 4666                Some(word_to_exclude),
 4667            )
 4668        } else {
 4669            (buffer_position..buffer_position, None)
 4670        };
 4671
 4672        let completion_settings = language_settings(
 4673            buffer_snapshot
 4674                .language_at(buffer_position)
 4675                .map(|language| language.name()),
 4676            buffer_snapshot.file(),
 4677            cx,
 4678        )
 4679        .completions;
 4680
 4681        // The document can be large, so stay in reasonable bounds when searching for words,
 4682        // otherwise completion pop-up might be slow to appear.
 4683        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4684        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4685        let min_word_search = buffer_snapshot.clip_point(
 4686            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4687            Bias::Left,
 4688        );
 4689        let max_word_search = buffer_snapshot.clip_point(
 4690            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4691            Bias::Right,
 4692        );
 4693        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4694            ..buffer_snapshot.point_to_offset(max_word_search);
 4695
 4696        let provider = self
 4697            .completion_provider
 4698            .as_ref()
 4699            .filter(|_| !ignore_completion_provider);
 4700        let skip_digits = query
 4701            .as_ref()
 4702            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4703
 4704        let (mut words, provided_completions) = match provider {
 4705            Some(provider) => {
 4706                let completions = provider.completions(
 4707                    position.excerpt_id,
 4708                    &buffer,
 4709                    buffer_position,
 4710                    completion_context,
 4711                    window,
 4712                    cx,
 4713                );
 4714
 4715                let words = match completion_settings.words {
 4716                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4717                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4718                        .background_spawn(async move {
 4719                            buffer_snapshot.words_in_range(WordsQuery {
 4720                                fuzzy_contents: None,
 4721                                range: word_search_range,
 4722                                skip_digits,
 4723                            })
 4724                        }),
 4725                };
 4726
 4727                (words, completions)
 4728            }
 4729            None => (
 4730                cx.background_spawn(async move {
 4731                    buffer_snapshot.words_in_range(WordsQuery {
 4732                        fuzzy_contents: None,
 4733                        range: word_search_range,
 4734                        skip_digits,
 4735                    })
 4736                }),
 4737                Task::ready(Ok(None)),
 4738            ),
 4739        };
 4740
 4741        let sort_completions = provider
 4742            .as_ref()
 4743            .map_or(false, |provider| provider.sort_completions());
 4744
 4745        let filter_completions = provider
 4746            .as_ref()
 4747            .map_or(true, |provider| provider.filter_completions());
 4748
 4749        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4750
 4751        let id = post_inc(&mut self.next_completion_id);
 4752        let task = cx.spawn_in(window, async move |editor, cx| {
 4753            async move {
 4754                editor.update(cx, |this, _| {
 4755                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4756                })?;
 4757
 4758                let mut completions = Vec::new();
 4759                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4760                    completions.extend(provided_completions);
 4761                    if completion_settings.words == WordsCompletionMode::Fallback {
 4762                        words = Task::ready(BTreeMap::default());
 4763                    }
 4764                }
 4765
 4766                let mut words = words.await;
 4767                if let Some(word_to_exclude) = &word_to_exclude {
 4768                    words.remove(word_to_exclude);
 4769                }
 4770                for lsp_completion in &completions {
 4771                    words.remove(&lsp_completion.new_text);
 4772                }
 4773                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4774                    replace_range: old_range.clone(),
 4775                    new_text: word.clone(),
 4776                    label: CodeLabel::plain(word, None),
 4777                    icon_path: None,
 4778                    documentation: None,
 4779                    source: CompletionSource::BufferWord {
 4780                        word_range,
 4781                        resolved: false,
 4782                    },
 4783                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4784                    confirm: None,
 4785                }));
 4786
 4787                let menu = if completions.is_empty() {
 4788                    None
 4789                } else {
 4790                    let mut menu = CompletionsMenu::new(
 4791                        id,
 4792                        sort_completions,
 4793                        show_completion_documentation,
 4794                        ignore_completion_provider,
 4795                        position,
 4796                        buffer.clone(),
 4797                        completions.into(),
 4798                        snippet_sort_order,
 4799                    );
 4800
 4801                    menu.filter(
 4802                        if filter_completions {
 4803                            query.as_deref()
 4804                        } else {
 4805                            None
 4806                        },
 4807                        cx.background_executor().clone(),
 4808                    )
 4809                    .await;
 4810
 4811                    menu.visible().then_some(menu)
 4812                };
 4813
 4814                editor.update_in(cx, |editor, window, cx| {
 4815                    match editor.context_menu.borrow().as_ref() {
 4816                        None => {}
 4817                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4818                            if prev_menu.id > id {
 4819                                return;
 4820                            }
 4821                        }
 4822                        _ => return,
 4823                    }
 4824
 4825                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4826                        let mut menu = menu.unwrap();
 4827                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4828
 4829                        *editor.context_menu.borrow_mut() =
 4830                            Some(CodeContextMenu::Completions(menu));
 4831
 4832                        if editor.show_edit_predictions_in_menu() {
 4833                            editor.update_visible_inline_completion(window, cx);
 4834                        } else {
 4835                            editor.discard_inline_completion(false, cx);
 4836                        }
 4837
 4838                        cx.notify();
 4839                    } else if editor.completion_tasks.len() <= 1 {
 4840                        // If there are no more completion tasks and the last menu was
 4841                        // empty, we should hide it.
 4842                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4843                        // If it was already hidden and we don't show inline
 4844                        // completions in the menu, we should also show the
 4845                        // inline-completion when available.
 4846                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4847                            editor.update_visible_inline_completion(window, cx);
 4848                        }
 4849                    }
 4850                })?;
 4851
 4852                anyhow::Ok(())
 4853            }
 4854            .log_err()
 4855            .await
 4856        });
 4857
 4858        self.completion_tasks.push((id, task));
 4859    }
 4860
 4861    #[cfg(feature = "test-support")]
 4862    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4863        let menu = self.context_menu.borrow();
 4864        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4865            let completions = menu.completions.borrow();
 4866            Some(completions.to_vec())
 4867        } else {
 4868            None
 4869        }
 4870    }
 4871
 4872    pub fn confirm_completion(
 4873        &mut self,
 4874        action: &ConfirmCompletion,
 4875        window: &mut Window,
 4876        cx: &mut Context<Self>,
 4877    ) -> Option<Task<Result<()>>> {
 4878        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4879        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4880    }
 4881
 4882    pub fn confirm_completion_insert(
 4883        &mut self,
 4884        _: &ConfirmCompletionInsert,
 4885        window: &mut Window,
 4886        cx: &mut Context<Self>,
 4887    ) -> Option<Task<Result<()>>> {
 4888        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4889        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4890    }
 4891
 4892    pub fn confirm_completion_replace(
 4893        &mut self,
 4894        _: &ConfirmCompletionReplace,
 4895        window: &mut Window,
 4896        cx: &mut Context<Self>,
 4897    ) -> Option<Task<Result<()>>> {
 4898        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4899        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4900    }
 4901
 4902    pub fn compose_completion(
 4903        &mut self,
 4904        action: &ComposeCompletion,
 4905        window: &mut Window,
 4906        cx: &mut Context<Self>,
 4907    ) -> Option<Task<Result<()>>> {
 4908        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4909        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4910    }
 4911
 4912    fn do_completion(
 4913        &mut self,
 4914        item_ix: Option<usize>,
 4915        intent: CompletionIntent,
 4916        window: &mut Window,
 4917        cx: &mut Context<Editor>,
 4918    ) -> Option<Task<Result<()>>> {
 4919        use language::ToOffset as _;
 4920
 4921        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4922        else {
 4923            return None;
 4924        };
 4925
 4926        let candidate_id = {
 4927            let entries = completions_menu.entries.borrow();
 4928            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4929            if self.show_edit_predictions_in_menu() {
 4930                self.discard_inline_completion(true, cx);
 4931            }
 4932            mat.candidate_id
 4933        };
 4934
 4935        let buffer_handle = completions_menu.buffer;
 4936        let completion = completions_menu
 4937            .completions
 4938            .borrow()
 4939            .get(candidate_id)?
 4940            .clone();
 4941        cx.stop_propagation();
 4942
 4943        let snippet;
 4944        let new_text;
 4945        if completion.is_snippet() {
 4946            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4947            new_text = snippet.as_ref().unwrap().text.clone();
 4948        } else {
 4949            snippet = None;
 4950            new_text = completion.new_text.clone();
 4951        };
 4952
 4953        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4954        let buffer = buffer_handle.read(cx);
 4955        let snapshot = self.buffer.read(cx).snapshot(cx);
 4956        let replace_range_multibuffer = {
 4957            let excerpt = snapshot
 4958                .excerpt_containing(self.selections.newest_anchor().range())
 4959                .unwrap();
 4960            let multibuffer_anchor = snapshot
 4961                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4962                .unwrap()
 4963                ..snapshot
 4964                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4965                    .unwrap();
 4966            multibuffer_anchor.start.to_offset(&snapshot)
 4967                ..multibuffer_anchor.end.to_offset(&snapshot)
 4968        };
 4969        let newest_anchor = self.selections.newest_anchor();
 4970        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4971            return None;
 4972        }
 4973
 4974        let old_text = buffer
 4975            .text_for_range(replace_range.clone())
 4976            .collect::<String>();
 4977        let lookbehind = newest_anchor
 4978            .start
 4979            .text_anchor
 4980            .to_offset(buffer)
 4981            .saturating_sub(replace_range.start);
 4982        let lookahead = replace_range
 4983            .end
 4984            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4985        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4986        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4987
 4988        let selections = self.selections.all::<usize>(cx);
 4989        let mut ranges = Vec::new();
 4990        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4991
 4992        for selection in &selections {
 4993            let range = if selection.id == newest_anchor.id {
 4994                replace_range_multibuffer.clone()
 4995            } else {
 4996                let mut range = selection.range();
 4997
 4998                // if prefix is present, don't duplicate it
 4999                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5000                    range.start = range.start.saturating_sub(lookbehind);
 5001
 5002                    // if suffix is also present, mimic the newest cursor and replace it
 5003                    if selection.id != newest_anchor.id
 5004                        && snapshot.contains_str_at(range.end, suffix)
 5005                    {
 5006                        range.end += lookahead;
 5007                    }
 5008                }
 5009                range
 5010            };
 5011
 5012            ranges.push(range.clone());
 5013
 5014            if !self.linked_edit_ranges.is_empty() {
 5015                let start_anchor = snapshot.anchor_before(range.start);
 5016                let end_anchor = snapshot.anchor_after(range.end);
 5017                if let Some(ranges) = self
 5018                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5019                {
 5020                    for (buffer, edits) in ranges {
 5021                        linked_edits
 5022                            .entry(buffer.clone())
 5023                            .or_default()
 5024                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5025                    }
 5026                }
 5027            }
 5028        }
 5029
 5030        cx.emit(EditorEvent::InputHandled {
 5031            utf16_range_to_replace: None,
 5032            text: new_text.clone().into(),
 5033        });
 5034
 5035        self.transact(window, cx, |this, window, cx| {
 5036            if let Some(mut snippet) = snippet {
 5037                snippet.text = new_text.to_string();
 5038                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5039            } else {
 5040                this.buffer.update(cx, |buffer, cx| {
 5041                    let auto_indent = match completion.insert_text_mode {
 5042                        Some(InsertTextMode::AS_IS) => None,
 5043                        _ => this.autoindent_mode.clone(),
 5044                    };
 5045                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5046                    buffer.edit(edits, auto_indent, cx);
 5047                });
 5048            }
 5049            for (buffer, edits) in linked_edits {
 5050                buffer.update(cx, |buffer, cx| {
 5051                    let snapshot = buffer.snapshot();
 5052                    let edits = edits
 5053                        .into_iter()
 5054                        .map(|(range, text)| {
 5055                            use text::ToPoint as TP;
 5056                            let end_point = TP::to_point(&range.end, &snapshot);
 5057                            let start_point = TP::to_point(&range.start, &snapshot);
 5058                            (start_point..end_point, text)
 5059                        })
 5060                        .sorted_by_key(|(range, _)| range.start);
 5061                    buffer.edit(edits, None, cx);
 5062                })
 5063            }
 5064
 5065            this.refresh_inline_completion(true, false, window, cx);
 5066        });
 5067
 5068        let show_new_completions_on_confirm = completion
 5069            .confirm
 5070            .as_ref()
 5071            .map_or(false, |confirm| confirm(intent, window, cx));
 5072        if show_new_completions_on_confirm {
 5073            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5074        }
 5075
 5076        let provider = self.completion_provider.as_ref()?;
 5077        drop(completion);
 5078        let apply_edits = provider.apply_additional_edits_for_completion(
 5079            buffer_handle,
 5080            completions_menu.completions.clone(),
 5081            candidate_id,
 5082            true,
 5083            cx,
 5084        );
 5085
 5086        let editor_settings = EditorSettings::get_global(cx);
 5087        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5088            // After the code completion is finished, users often want to know what signatures are needed.
 5089            // so we should automatically call signature_help
 5090            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5091        }
 5092
 5093        Some(cx.foreground_executor().spawn(async move {
 5094            apply_edits.await?;
 5095            Ok(())
 5096        }))
 5097    }
 5098
 5099    pub fn toggle_code_actions(
 5100        &mut self,
 5101        action: &ToggleCodeActions,
 5102        window: &mut Window,
 5103        cx: &mut Context<Self>,
 5104    ) {
 5105        let quick_launch = action.quick_launch;
 5106        let mut context_menu = self.context_menu.borrow_mut();
 5107        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5108            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5109                // Toggle if we're selecting the same one
 5110                *context_menu = None;
 5111                cx.notify();
 5112                return;
 5113            } else {
 5114                // Otherwise, clear it and start a new one
 5115                *context_menu = None;
 5116                cx.notify();
 5117            }
 5118        }
 5119        drop(context_menu);
 5120        let snapshot = self.snapshot(window, cx);
 5121        let deployed_from_indicator = action.deployed_from_indicator;
 5122        let mut task = self.code_actions_task.take();
 5123        let action = action.clone();
 5124        cx.spawn_in(window, async move |editor, cx| {
 5125            while let Some(prev_task) = task {
 5126                prev_task.await.log_err();
 5127                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5128            }
 5129
 5130            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5131                if editor.focus_handle.is_focused(window) {
 5132                    let multibuffer_point = action
 5133                        .deployed_from_indicator
 5134                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5135                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5136                    let (buffer, buffer_row) = snapshot
 5137                        .buffer_snapshot
 5138                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5139                        .and_then(|(buffer_snapshot, range)| {
 5140                            editor
 5141                                .buffer
 5142                                .read(cx)
 5143                                .buffer(buffer_snapshot.remote_id())
 5144                                .map(|buffer| (buffer, range.start.row))
 5145                        })?;
 5146                    let (_, code_actions) = editor
 5147                        .available_code_actions
 5148                        .clone()
 5149                        .and_then(|(location, code_actions)| {
 5150                            let snapshot = location.buffer.read(cx).snapshot();
 5151                            let point_range = location.range.to_point(&snapshot);
 5152                            let point_range = point_range.start.row..=point_range.end.row;
 5153                            if point_range.contains(&buffer_row) {
 5154                                Some((location, code_actions))
 5155                            } else {
 5156                                None
 5157                            }
 5158                        })
 5159                        .unzip();
 5160                    let buffer_id = buffer.read(cx).remote_id();
 5161                    let tasks = editor
 5162                        .tasks
 5163                        .get(&(buffer_id, buffer_row))
 5164                        .map(|t| Arc::new(t.to_owned()));
 5165                    if tasks.is_none() && code_actions.is_none() {
 5166                        return None;
 5167                    }
 5168
 5169                    editor.completion_tasks.clear();
 5170                    editor.discard_inline_completion(false, cx);
 5171                    let task_context =
 5172                        tasks
 5173                            .as_ref()
 5174                            .zip(editor.project.clone())
 5175                            .map(|(tasks, project)| {
 5176                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5177                            });
 5178
 5179                    Some(cx.spawn_in(window, async move |editor, cx| {
 5180                        let task_context = match task_context {
 5181                            Some(task_context) => task_context.await,
 5182                            None => None,
 5183                        };
 5184                        let resolved_tasks =
 5185                            tasks
 5186                                .zip(task_context.clone())
 5187                                .map(|(tasks, task_context)| ResolvedTasks {
 5188                                    templates: tasks.resolve(&task_context).collect(),
 5189                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5190                                        multibuffer_point.row,
 5191                                        tasks.column,
 5192                                    )),
 5193                                });
 5194                        let spawn_straight_away = quick_launch
 5195                            && resolved_tasks
 5196                                .as_ref()
 5197                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5198                            && code_actions
 5199                                .as_ref()
 5200                                .map_or(true, |actions| actions.is_empty());
 5201                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5202                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5203                                maybe!({
 5204                                    let project = editor.project.as_ref()?;
 5205                                    let dap_store = project.read(cx).dap_store();
 5206                                    let mut scenarios = vec![];
 5207                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5208                                    let debug_adapter: SharedString = buffer
 5209                                        .read(cx)
 5210                                        .language()?
 5211                                        .context_provider()?
 5212                                        .debug_adapter()?
 5213                                        .into();
 5214                                    dap_store.update(cx, |this, cx| {
 5215                                        for (_, task) in &resolved_tasks.templates {
 5216                                            if let Some(scenario) = this
 5217                                                .debug_scenario_for_build_task(
 5218                                                    task.resolved.clone(),
 5219                                                    SharedString::from(
 5220                                                        task.original_task().label.clone(),
 5221                                                    ),
 5222                                                    debug_adapter.clone(),
 5223                                                    cx,
 5224                                                )
 5225                                            {
 5226                                                scenarios.push(scenario);
 5227                                            }
 5228                                        }
 5229                                    });
 5230                                    Some(scenarios)
 5231                                })
 5232                                .unwrap_or_default()
 5233                            } else {
 5234                                vec![]
 5235                            }
 5236                        })?;
 5237                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5238                            *editor.context_menu.borrow_mut() =
 5239                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5240                                    buffer,
 5241                                    actions: CodeActionContents::new(
 5242                                        resolved_tasks,
 5243                                        code_actions,
 5244                                        debug_scenarios,
 5245                                        task_context.unwrap_or_default(),
 5246                                    ),
 5247                                    selected_item: Default::default(),
 5248                                    scroll_handle: UniformListScrollHandle::default(),
 5249                                    deployed_from_indicator,
 5250                                }));
 5251                            if spawn_straight_away {
 5252                                if let Some(task) = editor.confirm_code_action(
 5253                                    &ConfirmCodeAction { item_ix: Some(0) },
 5254                                    window,
 5255                                    cx,
 5256                                ) {
 5257                                    cx.notify();
 5258                                    return task;
 5259                                }
 5260                            }
 5261                            cx.notify();
 5262                            Task::ready(Ok(()))
 5263                        }) {
 5264                            task.await
 5265                        } else {
 5266                            Ok(())
 5267                        }
 5268                    }))
 5269                } else {
 5270                    Some(Task::ready(Ok(())))
 5271                }
 5272            })?;
 5273            if let Some(task) = spawned_test_task {
 5274                task.await?;
 5275            }
 5276
 5277            Ok::<_, anyhow::Error>(())
 5278        })
 5279        .detach_and_log_err(cx);
 5280    }
 5281
 5282    pub fn confirm_code_action(
 5283        &mut self,
 5284        action: &ConfirmCodeAction,
 5285        window: &mut Window,
 5286        cx: &mut Context<Self>,
 5287    ) -> Option<Task<Result<()>>> {
 5288        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5289
 5290        let actions_menu =
 5291            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5292                menu
 5293            } else {
 5294                return None;
 5295            };
 5296
 5297        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5298        let action = actions_menu.actions.get(action_ix)?;
 5299        let title = action.label();
 5300        let buffer = actions_menu.buffer;
 5301        let workspace = self.workspace()?;
 5302
 5303        match action {
 5304            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5305                workspace.update(cx, |workspace, cx| {
 5306                    workspace.schedule_resolved_task(
 5307                        task_source_kind,
 5308                        resolved_task,
 5309                        false,
 5310                        window,
 5311                        cx,
 5312                    );
 5313
 5314                    Some(Task::ready(Ok(())))
 5315                })
 5316            }
 5317            CodeActionsItem::CodeAction {
 5318                excerpt_id,
 5319                action,
 5320                provider,
 5321            } => {
 5322                let apply_code_action =
 5323                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5324                let workspace = workspace.downgrade();
 5325                Some(cx.spawn_in(window, async move |editor, cx| {
 5326                    let project_transaction = apply_code_action.await?;
 5327                    Self::open_project_transaction(
 5328                        &editor,
 5329                        workspace,
 5330                        project_transaction,
 5331                        title,
 5332                        cx,
 5333                    )
 5334                    .await
 5335                }))
 5336            }
 5337            CodeActionsItem::DebugScenario(scenario) => {
 5338                let context = actions_menu.actions.context.clone();
 5339
 5340                workspace.update(cx, |workspace, cx| {
 5341                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5342                });
 5343                Some(Task::ready(Ok(())))
 5344            }
 5345        }
 5346    }
 5347
 5348    pub async fn open_project_transaction(
 5349        this: &WeakEntity<Editor>,
 5350        workspace: WeakEntity<Workspace>,
 5351        transaction: ProjectTransaction,
 5352        title: String,
 5353        cx: &mut AsyncWindowContext,
 5354    ) -> Result<()> {
 5355        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5356        cx.update(|_, cx| {
 5357            entries.sort_unstable_by_key(|(buffer, _)| {
 5358                buffer.read(cx).file().map(|f| f.path().clone())
 5359            });
 5360        })?;
 5361
 5362        // If the project transaction's edits are all contained within this editor, then
 5363        // avoid opening a new editor to display them.
 5364
 5365        if let Some((buffer, transaction)) = entries.first() {
 5366            if entries.len() == 1 {
 5367                let excerpt = this.update(cx, |editor, cx| {
 5368                    editor
 5369                        .buffer()
 5370                        .read(cx)
 5371                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5372                })?;
 5373                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5374                    if excerpted_buffer == *buffer {
 5375                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5376                            let excerpt_range = excerpt_range.to_offset(buffer);
 5377                            buffer
 5378                                .edited_ranges_for_transaction::<usize>(transaction)
 5379                                .all(|range| {
 5380                                    excerpt_range.start <= range.start
 5381                                        && excerpt_range.end >= range.end
 5382                                })
 5383                        })?;
 5384
 5385                        if all_edits_within_excerpt {
 5386                            return Ok(());
 5387                        }
 5388                    }
 5389                }
 5390            }
 5391        } else {
 5392            return Ok(());
 5393        }
 5394
 5395        let mut ranges_to_highlight = Vec::new();
 5396        let excerpt_buffer = cx.new(|cx| {
 5397            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5398            for (buffer_handle, transaction) in &entries {
 5399                let edited_ranges = buffer_handle
 5400                    .read(cx)
 5401                    .edited_ranges_for_transaction::<Point>(transaction)
 5402                    .collect::<Vec<_>>();
 5403                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5404                    PathKey::for_buffer(buffer_handle, cx),
 5405                    buffer_handle.clone(),
 5406                    edited_ranges,
 5407                    DEFAULT_MULTIBUFFER_CONTEXT,
 5408                    cx,
 5409                );
 5410
 5411                ranges_to_highlight.extend(ranges);
 5412            }
 5413            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5414            multibuffer
 5415        })?;
 5416
 5417        workspace.update_in(cx, |workspace, window, cx| {
 5418            let project = workspace.project().clone();
 5419            let editor =
 5420                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5421            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5422            editor.update(cx, |editor, cx| {
 5423                editor.highlight_background::<Self>(
 5424                    &ranges_to_highlight,
 5425                    |theme| theme.editor_highlighted_line_background,
 5426                    cx,
 5427                );
 5428            });
 5429        })?;
 5430
 5431        Ok(())
 5432    }
 5433
 5434    pub fn clear_code_action_providers(&mut self) {
 5435        self.code_action_providers.clear();
 5436        self.available_code_actions.take();
 5437    }
 5438
 5439    pub fn add_code_action_provider(
 5440        &mut self,
 5441        provider: Rc<dyn CodeActionProvider>,
 5442        window: &mut Window,
 5443        cx: &mut Context<Self>,
 5444    ) {
 5445        if self
 5446            .code_action_providers
 5447            .iter()
 5448            .any(|existing_provider| existing_provider.id() == provider.id())
 5449        {
 5450            return;
 5451        }
 5452
 5453        self.code_action_providers.push(provider);
 5454        self.refresh_code_actions(window, cx);
 5455    }
 5456
 5457    pub fn remove_code_action_provider(
 5458        &mut self,
 5459        id: Arc<str>,
 5460        window: &mut Window,
 5461        cx: &mut Context<Self>,
 5462    ) {
 5463        self.code_action_providers
 5464            .retain(|provider| provider.id() != id);
 5465        self.refresh_code_actions(window, cx);
 5466    }
 5467
 5468    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5469        let newest_selection = self.selections.newest_anchor().clone();
 5470        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5471        let buffer = self.buffer.read(cx);
 5472        if newest_selection.head().diff_base_anchor.is_some() {
 5473            return None;
 5474        }
 5475        let (start_buffer, start) =
 5476            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5477        let (end_buffer, end) =
 5478            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5479        if start_buffer != end_buffer {
 5480            return None;
 5481        }
 5482
 5483        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5484            cx.background_executor()
 5485                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5486                .await;
 5487
 5488            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5489                let providers = this.code_action_providers.clone();
 5490                let tasks = this
 5491                    .code_action_providers
 5492                    .iter()
 5493                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5494                    .collect::<Vec<_>>();
 5495                (providers, tasks)
 5496            })?;
 5497
 5498            let mut actions = Vec::new();
 5499            for (provider, provider_actions) in
 5500                providers.into_iter().zip(future::join_all(tasks).await)
 5501            {
 5502                if let Some(provider_actions) = provider_actions.log_err() {
 5503                    actions.extend(provider_actions.into_iter().map(|action| {
 5504                        AvailableCodeAction {
 5505                            excerpt_id: newest_selection.start.excerpt_id,
 5506                            action,
 5507                            provider: provider.clone(),
 5508                        }
 5509                    }));
 5510                }
 5511            }
 5512
 5513            this.update(cx, |this, cx| {
 5514                this.available_code_actions = if actions.is_empty() {
 5515                    None
 5516                } else {
 5517                    Some((
 5518                        Location {
 5519                            buffer: start_buffer,
 5520                            range: start..end,
 5521                        },
 5522                        actions.into(),
 5523                    ))
 5524                };
 5525                cx.notify();
 5526            })
 5527        }));
 5528        None
 5529    }
 5530
 5531    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5532        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5533            self.show_git_blame_inline = false;
 5534
 5535            self.show_git_blame_inline_delay_task =
 5536                Some(cx.spawn_in(window, async move |this, cx| {
 5537                    cx.background_executor().timer(delay).await;
 5538
 5539                    this.update(cx, |this, cx| {
 5540                        this.show_git_blame_inline = true;
 5541                        cx.notify();
 5542                    })
 5543                    .log_err();
 5544                }));
 5545        }
 5546    }
 5547
 5548    fn show_blame_popover(
 5549        &mut self,
 5550        blame_entry: &BlameEntry,
 5551        position: gpui::Point<Pixels>,
 5552        cx: &mut Context<Self>,
 5553    ) {
 5554        if let Some(state) = &mut self.inline_blame_popover {
 5555            state.hide_task.take();
 5556            cx.notify();
 5557        } else {
 5558            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5559            let show_task = cx.spawn(async move |editor, cx| {
 5560                cx.background_executor()
 5561                    .timer(std::time::Duration::from_millis(delay))
 5562                    .await;
 5563                editor
 5564                    .update(cx, |editor, cx| {
 5565                        if let Some(state) = &mut editor.inline_blame_popover {
 5566                            state.show_task = None;
 5567                            cx.notify();
 5568                        }
 5569                    })
 5570                    .ok();
 5571            });
 5572            let Some(blame) = self.blame.as_ref() else {
 5573                return;
 5574            };
 5575            let blame = blame.read(cx);
 5576            let details = blame.details_for_entry(&blame_entry);
 5577            let markdown = cx.new(|cx| {
 5578                Markdown::new(
 5579                    details
 5580                        .as_ref()
 5581                        .map(|message| message.message.clone())
 5582                        .unwrap_or_default(),
 5583                    None,
 5584                    None,
 5585                    cx,
 5586                )
 5587            });
 5588            self.inline_blame_popover = Some(InlineBlamePopover {
 5589                position,
 5590                show_task: Some(show_task),
 5591                hide_task: None,
 5592                popover_bounds: None,
 5593                popover_state: InlineBlamePopoverState {
 5594                    scroll_handle: ScrollHandle::new(),
 5595                    commit_message: details,
 5596                    markdown,
 5597                },
 5598            });
 5599        }
 5600    }
 5601
 5602    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5603        if let Some(state) = &mut self.inline_blame_popover {
 5604            if state.show_task.is_some() {
 5605                self.inline_blame_popover.take();
 5606                cx.notify();
 5607            } else {
 5608                let hide_task = cx.spawn(async move |editor, cx| {
 5609                    cx.background_executor()
 5610                        .timer(std::time::Duration::from_millis(100))
 5611                        .await;
 5612                    editor
 5613                        .update(cx, |editor, cx| {
 5614                            editor.inline_blame_popover.take();
 5615                            cx.notify();
 5616                        })
 5617                        .ok();
 5618                });
 5619                state.hide_task = Some(hide_task);
 5620            }
 5621        }
 5622    }
 5623
 5624    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5625        if self.pending_rename.is_some() {
 5626            return None;
 5627        }
 5628
 5629        let provider = self.semantics_provider.clone()?;
 5630        let buffer = self.buffer.read(cx);
 5631        let newest_selection = self.selections.newest_anchor().clone();
 5632        let cursor_position = newest_selection.head();
 5633        let (cursor_buffer, cursor_buffer_position) =
 5634            buffer.text_anchor_for_position(cursor_position, cx)?;
 5635        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5636        if cursor_buffer != tail_buffer {
 5637            return None;
 5638        }
 5639        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5640        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5641            cx.background_executor()
 5642                .timer(Duration::from_millis(debounce))
 5643                .await;
 5644
 5645            let highlights = if let Some(highlights) = cx
 5646                .update(|cx| {
 5647                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5648                })
 5649                .ok()
 5650                .flatten()
 5651            {
 5652                highlights.await.log_err()
 5653            } else {
 5654                None
 5655            };
 5656
 5657            if let Some(highlights) = highlights {
 5658                this.update(cx, |this, cx| {
 5659                    if this.pending_rename.is_some() {
 5660                        return;
 5661                    }
 5662
 5663                    let buffer_id = cursor_position.buffer_id;
 5664                    let buffer = this.buffer.read(cx);
 5665                    if !buffer
 5666                        .text_anchor_for_position(cursor_position, cx)
 5667                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5668                    {
 5669                        return;
 5670                    }
 5671
 5672                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5673                    let mut write_ranges = Vec::new();
 5674                    let mut read_ranges = Vec::new();
 5675                    for highlight in highlights {
 5676                        for (excerpt_id, excerpt_range) in
 5677                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5678                        {
 5679                            let start = highlight
 5680                                .range
 5681                                .start
 5682                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5683                            let end = highlight
 5684                                .range
 5685                                .end
 5686                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5687                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5688                                continue;
 5689                            }
 5690
 5691                            let range = Anchor {
 5692                                buffer_id,
 5693                                excerpt_id,
 5694                                text_anchor: start,
 5695                                diff_base_anchor: None,
 5696                            }..Anchor {
 5697                                buffer_id,
 5698                                excerpt_id,
 5699                                text_anchor: end,
 5700                                diff_base_anchor: None,
 5701                            };
 5702                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5703                                write_ranges.push(range);
 5704                            } else {
 5705                                read_ranges.push(range);
 5706                            }
 5707                        }
 5708                    }
 5709
 5710                    this.highlight_background::<DocumentHighlightRead>(
 5711                        &read_ranges,
 5712                        |theme| theme.editor_document_highlight_read_background,
 5713                        cx,
 5714                    );
 5715                    this.highlight_background::<DocumentHighlightWrite>(
 5716                        &write_ranges,
 5717                        |theme| theme.editor_document_highlight_write_background,
 5718                        cx,
 5719                    );
 5720                    cx.notify();
 5721                })
 5722                .log_err();
 5723            }
 5724        }));
 5725        None
 5726    }
 5727
 5728    fn prepare_highlight_query_from_selection(
 5729        &mut self,
 5730        cx: &mut Context<Editor>,
 5731    ) -> Option<(String, Range<Anchor>)> {
 5732        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5733            return None;
 5734        }
 5735        if !EditorSettings::get_global(cx).selection_highlight {
 5736            return None;
 5737        }
 5738        if self.selections.count() != 1 || self.selections.line_mode {
 5739            return None;
 5740        }
 5741        let selection = self.selections.newest::<Point>(cx);
 5742        if selection.is_empty() || selection.start.row != selection.end.row {
 5743            return None;
 5744        }
 5745        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5746        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5747        let query = multi_buffer_snapshot
 5748            .text_for_range(selection_anchor_range.clone())
 5749            .collect::<String>();
 5750        if query.trim().is_empty() {
 5751            return None;
 5752        }
 5753        Some((query, selection_anchor_range))
 5754    }
 5755
 5756    fn update_selection_occurrence_highlights(
 5757        &mut self,
 5758        query_text: String,
 5759        query_range: Range<Anchor>,
 5760        multi_buffer_range_to_query: Range<Point>,
 5761        use_debounce: bool,
 5762        window: &mut Window,
 5763        cx: &mut Context<Editor>,
 5764    ) -> Task<()> {
 5765        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5766        cx.spawn_in(window, async move |editor, cx| {
 5767            if use_debounce {
 5768                cx.background_executor()
 5769                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5770                    .await;
 5771            }
 5772            let match_task = cx.background_spawn(async move {
 5773                let buffer_ranges = multi_buffer_snapshot
 5774                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5775                    .into_iter()
 5776                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5777                let mut match_ranges = Vec::new();
 5778                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5779                    match_ranges.extend(
 5780                        project::search::SearchQuery::text(
 5781                            query_text.clone(),
 5782                            false,
 5783                            false,
 5784                            false,
 5785                            Default::default(),
 5786                            Default::default(),
 5787                            false,
 5788                            None,
 5789                        )
 5790                        .unwrap()
 5791                        .search(&buffer_snapshot, Some(search_range.clone()))
 5792                        .await
 5793                        .into_iter()
 5794                        .filter_map(|match_range| {
 5795                            let match_start = buffer_snapshot
 5796                                .anchor_after(search_range.start + match_range.start);
 5797                            let match_end =
 5798                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5799                            let match_anchor_range = Anchor::range_in_buffer(
 5800                                excerpt_id,
 5801                                buffer_snapshot.remote_id(),
 5802                                match_start..match_end,
 5803                            );
 5804                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5805                        }),
 5806                    );
 5807                }
 5808                match_ranges
 5809            });
 5810            let match_ranges = match_task.await;
 5811            editor
 5812                .update_in(cx, |editor, _, cx| {
 5813                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5814                    if !match_ranges.is_empty() {
 5815                        editor.highlight_background::<SelectedTextHighlight>(
 5816                            &match_ranges,
 5817                            |theme| theme.editor_document_highlight_bracket_background,
 5818                            cx,
 5819                        )
 5820                    }
 5821                })
 5822                .log_err();
 5823        })
 5824    }
 5825
 5826    fn refresh_selected_text_highlights(
 5827        &mut self,
 5828        on_buffer_edit: bool,
 5829        window: &mut Window,
 5830        cx: &mut Context<Editor>,
 5831    ) {
 5832        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5833        else {
 5834            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5835            self.quick_selection_highlight_task.take();
 5836            self.debounced_selection_highlight_task.take();
 5837            return;
 5838        };
 5839        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5840        if on_buffer_edit
 5841            || self
 5842                .quick_selection_highlight_task
 5843                .as_ref()
 5844                .map_or(true, |(prev_anchor_range, _)| {
 5845                    prev_anchor_range != &query_range
 5846                })
 5847        {
 5848            let multi_buffer_visible_start = self
 5849                .scroll_manager
 5850                .anchor()
 5851                .anchor
 5852                .to_point(&multi_buffer_snapshot);
 5853            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5854                multi_buffer_visible_start
 5855                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5856                Bias::Left,
 5857            );
 5858            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5859            self.quick_selection_highlight_task = Some((
 5860                query_range.clone(),
 5861                self.update_selection_occurrence_highlights(
 5862                    query_text.clone(),
 5863                    query_range.clone(),
 5864                    multi_buffer_visible_range,
 5865                    false,
 5866                    window,
 5867                    cx,
 5868                ),
 5869            ));
 5870        }
 5871        if on_buffer_edit
 5872            || self
 5873                .debounced_selection_highlight_task
 5874                .as_ref()
 5875                .map_or(true, |(prev_anchor_range, _)| {
 5876                    prev_anchor_range != &query_range
 5877                })
 5878        {
 5879            let multi_buffer_start = multi_buffer_snapshot
 5880                .anchor_before(0)
 5881                .to_point(&multi_buffer_snapshot);
 5882            let multi_buffer_end = multi_buffer_snapshot
 5883                .anchor_after(multi_buffer_snapshot.len())
 5884                .to_point(&multi_buffer_snapshot);
 5885            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5886            self.debounced_selection_highlight_task = Some((
 5887                query_range.clone(),
 5888                self.update_selection_occurrence_highlights(
 5889                    query_text,
 5890                    query_range,
 5891                    multi_buffer_full_range,
 5892                    true,
 5893                    window,
 5894                    cx,
 5895                ),
 5896            ));
 5897        }
 5898    }
 5899
 5900    pub fn refresh_inline_completion(
 5901        &mut self,
 5902        debounce: bool,
 5903        user_requested: bool,
 5904        window: &mut Window,
 5905        cx: &mut Context<Self>,
 5906    ) -> Option<()> {
 5907        let provider = self.edit_prediction_provider()?;
 5908        let cursor = self.selections.newest_anchor().head();
 5909        let (buffer, cursor_buffer_position) =
 5910            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5911
 5912        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5913            self.discard_inline_completion(false, cx);
 5914            return None;
 5915        }
 5916
 5917        if !user_requested
 5918            && (!self.should_show_edit_predictions()
 5919                || !self.is_focused(window)
 5920                || buffer.read(cx).is_empty())
 5921        {
 5922            self.discard_inline_completion(false, cx);
 5923            return None;
 5924        }
 5925
 5926        self.update_visible_inline_completion(window, cx);
 5927        provider.refresh(
 5928            self.project.clone(),
 5929            buffer,
 5930            cursor_buffer_position,
 5931            debounce,
 5932            cx,
 5933        );
 5934        Some(())
 5935    }
 5936
 5937    fn show_edit_predictions_in_menu(&self) -> bool {
 5938        match self.edit_prediction_settings {
 5939            EditPredictionSettings::Disabled => false,
 5940            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5941        }
 5942    }
 5943
 5944    pub fn edit_predictions_enabled(&self) -> bool {
 5945        match self.edit_prediction_settings {
 5946            EditPredictionSettings::Disabled => false,
 5947            EditPredictionSettings::Enabled { .. } => true,
 5948        }
 5949    }
 5950
 5951    fn edit_prediction_requires_modifier(&self) -> bool {
 5952        match self.edit_prediction_settings {
 5953            EditPredictionSettings::Disabled => false,
 5954            EditPredictionSettings::Enabled {
 5955                preview_requires_modifier,
 5956                ..
 5957            } => preview_requires_modifier,
 5958        }
 5959    }
 5960
 5961    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5962        if self.edit_prediction_provider.is_none() {
 5963            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5964        } else {
 5965            let selection = self.selections.newest_anchor();
 5966            let cursor = selection.head();
 5967
 5968            if let Some((buffer, cursor_buffer_position)) =
 5969                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5970            {
 5971                self.edit_prediction_settings =
 5972                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5973            }
 5974        }
 5975    }
 5976
 5977    fn edit_prediction_settings_at_position(
 5978        &self,
 5979        buffer: &Entity<Buffer>,
 5980        buffer_position: language::Anchor,
 5981        cx: &App,
 5982    ) -> EditPredictionSettings {
 5983        if !self.mode.is_full()
 5984            || !self.show_inline_completions_override.unwrap_or(true)
 5985            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5986        {
 5987            return EditPredictionSettings::Disabled;
 5988        }
 5989
 5990        let buffer = buffer.read(cx);
 5991
 5992        let file = buffer.file();
 5993
 5994        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5995            return EditPredictionSettings::Disabled;
 5996        };
 5997
 5998        let by_provider = matches!(
 5999            self.menu_inline_completions_policy,
 6000            MenuInlineCompletionsPolicy::ByProvider
 6001        );
 6002
 6003        let show_in_menu = by_provider
 6004            && self
 6005                .edit_prediction_provider
 6006                .as_ref()
 6007                .map_or(false, |provider| {
 6008                    provider.provider.show_completions_in_menu()
 6009                });
 6010
 6011        let preview_requires_modifier =
 6012            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6013
 6014        EditPredictionSettings::Enabled {
 6015            show_in_menu,
 6016            preview_requires_modifier,
 6017        }
 6018    }
 6019
 6020    fn should_show_edit_predictions(&self) -> bool {
 6021        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6022    }
 6023
 6024    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6025        matches!(
 6026            self.edit_prediction_preview,
 6027            EditPredictionPreview::Active { .. }
 6028        )
 6029    }
 6030
 6031    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6032        let cursor = self.selections.newest_anchor().head();
 6033        if let Some((buffer, cursor_position)) =
 6034            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6035        {
 6036            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6037        } else {
 6038            false
 6039        }
 6040    }
 6041
 6042    fn edit_predictions_enabled_in_buffer(
 6043        &self,
 6044        buffer: &Entity<Buffer>,
 6045        buffer_position: language::Anchor,
 6046        cx: &App,
 6047    ) -> bool {
 6048        maybe!({
 6049            if self.read_only(cx) {
 6050                return Some(false);
 6051            }
 6052            let provider = self.edit_prediction_provider()?;
 6053            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6054                return Some(false);
 6055            }
 6056            let buffer = buffer.read(cx);
 6057            let Some(file) = buffer.file() else {
 6058                return Some(true);
 6059            };
 6060            let settings = all_language_settings(Some(file), cx);
 6061            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6062        })
 6063        .unwrap_or(false)
 6064    }
 6065
 6066    fn cycle_inline_completion(
 6067        &mut self,
 6068        direction: Direction,
 6069        window: &mut Window,
 6070        cx: &mut Context<Self>,
 6071    ) -> Option<()> {
 6072        let provider = self.edit_prediction_provider()?;
 6073        let cursor = self.selections.newest_anchor().head();
 6074        let (buffer, cursor_buffer_position) =
 6075            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6076        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6077            return None;
 6078        }
 6079
 6080        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6081        self.update_visible_inline_completion(window, cx);
 6082
 6083        Some(())
 6084    }
 6085
 6086    pub fn show_inline_completion(
 6087        &mut self,
 6088        _: &ShowEditPrediction,
 6089        window: &mut Window,
 6090        cx: &mut Context<Self>,
 6091    ) {
 6092        if !self.has_active_inline_completion() {
 6093            self.refresh_inline_completion(false, true, window, cx);
 6094            return;
 6095        }
 6096
 6097        self.update_visible_inline_completion(window, cx);
 6098    }
 6099
 6100    pub fn display_cursor_names(
 6101        &mut self,
 6102        _: &DisplayCursorNames,
 6103        window: &mut Window,
 6104        cx: &mut Context<Self>,
 6105    ) {
 6106        self.show_cursor_names(window, cx);
 6107    }
 6108
 6109    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6110        self.show_cursor_names = true;
 6111        cx.notify();
 6112        cx.spawn_in(window, async move |this, cx| {
 6113            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6114            this.update(cx, |this, cx| {
 6115                this.show_cursor_names = false;
 6116                cx.notify()
 6117            })
 6118            .ok()
 6119        })
 6120        .detach();
 6121    }
 6122
 6123    pub fn next_edit_prediction(
 6124        &mut self,
 6125        _: &NextEditPrediction,
 6126        window: &mut Window,
 6127        cx: &mut Context<Self>,
 6128    ) {
 6129        if self.has_active_inline_completion() {
 6130            self.cycle_inline_completion(Direction::Next, window, cx);
 6131        } else {
 6132            let is_copilot_disabled = self
 6133                .refresh_inline_completion(false, true, window, cx)
 6134                .is_none();
 6135            if is_copilot_disabled {
 6136                cx.propagate();
 6137            }
 6138        }
 6139    }
 6140
 6141    pub fn previous_edit_prediction(
 6142        &mut self,
 6143        _: &PreviousEditPrediction,
 6144        window: &mut Window,
 6145        cx: &mut Context<Self>,
 6146    ) {
 6147        if self.has_active_inline_completion() {
 6148            self.cycle_inline_completion(Direction::Prev, window, cx);
 6149        } else {
 6150            let is_copilot_disabled = self
 6151                .refresh_inline_completion(false, true, window, cx)
 6152                .is_none();
 6153            if is_copilot_disabled {
 6154                cx.propagate();
 6155            }
 6156        }
 6157    }
 6158
 6159    pub fn accept_edit_prediction(
 6160        &mut self,
 6161        _: &AcceptEditPrediction,
 6162        window: &mut Window,
 6163        cx: &mut Context<Self>,
 6164    ) {
 6165        if self.show_edit_predictions_in_menu() {
 6166            self.hide_context_menu(window, cx);
 6167        }
 6168
 6169        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6170            return;
 6171        };
 6172
 6173        self.report_inline_completion_event(
 6174            active_inline_completion.completion_id.clone(),
 6175            true,
 6176            cx,
 6177        );
 6178
 6179        match &active_inline_completion.completion {
 6180            InlineCompletion::Move { target, .. } => {
 6181                let target = *target;
 6182
 6183                if let Some(position_map) = &self.last_position_map {
 6184                    if position_map
 6185                        .visible_row_range
 6186                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6187                        || !self.edit_prediction_requires_modifier()
 6188                    {
 6189                        self.unfold_ranges(&[target..target], true, false, cx);
 6190                        // Note that this is also done in vim's handler of the Tab action.
 6191                        self.change_selections(
 6192                            Some(Autoscroll::newest()),
 6193                            window,
 6194                            cx,
 6195                            |selections| {
 6196                                selections.select_anchor_ranges([target..target]);
 6197                            },
 6198                        );
 6199                        self.clear_row_highlights::<EditPredictionPreview>();
 6200
 6201                        self.edit_prediction_preview
 6202                            .set_previous_scroll_position(None);
 6203                    } else {
 6204                        self.edit_prediction_preview
 6205                            .set_previous_scroll_position(Some(
 6206                                position_map.snapshot.scroll_anchor,
 6207                            ));
 6208
 6209                        self.highlight_rows::<EditPredictionPreview>(
 6210                            target..target,
 6211                            cx.theme().colors().editor_highlighted_line_background,
 6212                            RowHighlightOptions {
 6213                                autoscroll: true,
 6214                                ..Default::default()
 6215                            },
 6216                            cx,
 6217                        );
 6218                        self.request_autoscroll(Autoscroll::fit(), cx);
 6219                    }
 6220                }
 6221            }
 6222            InlineCompletion::Edit { edits, .. } => {
 6223                if let Some(provider) = self.edit_prediction_provider() {
 6224                    provider.accept(cx);
 6225                }
 6226
 6227                let snapshot = self.buffer.read(cx).snapshot(cx);
 6228                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6229
 6230                self.buffer.update(cx, |buffer, cx| {
 6231                    buffer.edit(edits.iter().cloned(), None, cx)
 6232                });
 6233
 6234                self.change_selections(None, window, cx, |s| {
 6235                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6236                });
 6237
 6238                self.update_visible_inline_completion(window, cx);
 6239                if self.active_inline_completion.is_none() {
 6240                    self.refresh_inline_completion(true, true, window, cx);
 6241                }
 6242
 6243                cx.notify();
 6244            }
 6245        }
 6246
 6247        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6248    }
 6249
 6250    pub fn accept_partial_inline_completion(
 6251        &mut self,
 6252        _: &AcceptPartialEditPrediction,
 6253        window: &mut Window,
 6254        cx: &mut Context<Self>,
 6255    ) {
 6256        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6257            return;
 6258        };
 6259        if self.selections.count() != 1 {
 6260            return;
 6261        }
 6262
 6263        self.report_inline_completion_event(
 6264            active_inline_completion.completion_id.clone(),
 6265            true,
 6266            cx,
 6267        );
 6268
 6269        match &active_inline_completion.completion {
 6270            InlineCompletion::Move { target, .. } => {
 6271                let target = *target;
 6272                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6273                    selections.select_anchor_ranges([target..target]);
 6274                });
 6275            }
 6276            InlineCompletion::Edit { edits, .. } => {
 6277                // Find an insertion that starts at the cursor position.
 6278                let snapshot = self.buffer.read(cx).snapshot(cx);
 6279                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6280                let insertion = edits.iter().find_map(|(range, text)| {
 6281                    let range = range.to_offset(&snapshot);
 6282                    if range.is_empty() && range.start == cursor_offset {
 6283                        Some(text)
 6284                    } else {
 6285                        None
 6286                    }
 6287                });
 6288
 6289                if let Some(text) = insertion {
 6290                    let mut partial_completion = text
 6291                        .chars()
 6292                        .by_ref()
 6293                        .take_while(|c| c.is_alphabetic())
 6294                        .collect::<String>();
 6295                    if partial_completion.is_empty() {
 6296                        partial_completion = text
 6297                            .chars()
 6298                            .by_ref()
 6299                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6300                            .collect::<String>();
 6301                    }
 6302
 6303                    cx.emit(EditorEvent::InputHandled {
 6304                        utf16_range_to_replace: None,
 6305                        text: partial_completion.clone().into(),
 6306                    });
 6307
 6308                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6309
 6310                    self.refresh_inline_completion(true, true, window, cx);
 6311                    cx.notify();
 6312                } else {
 6313                    self.accept_edit_prediction(&Default::default(), window, cx);
 6314                }
 6315            }
 6316        }
 6317    }
 6318
 6319    fn discard_inline_completion(
 6320        &mut self,
 6321        should_report_inline_completion_event: bool,
 6322        cx: &mut Context<Self>,
 6323    ) -> bool {
 6324        if should_report_inline_completion_event {
 6325            let completion_id = self
 6326                .active_inline_completion
 6327                .as_ref()
 6328                .and_then(|active_completion| active_completion.completion_id.clone());
 6329
 6330            self.report_inline_completion_event(completion_id, false, cx);
 6331        }
 6332
 6333        if let Some(provider) = self.edit_prediction_provider() {
 6334            provider.discard(cx);
 6335        }
 6336
 6337        self.take_active_inline_completion(cx)
 6338    }
 6339
 6340    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6341        let Some(provider) = self.edit_prediction_provider() else {
 6342            return;
 6343        };
 6344
 6345        let Some((_, buffer, _)) = self
 6346            .buffer
 6347            .read(cx)
 6348            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6349        else {
 6350            return;
 6351        };
 6352
 6353        let extension = buffer
 6354            .read(cx)
 6355            .file()
 6356            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6357
 6358        let event_type = match accepted {
 6359            true => "Edit Prediction Accepted",
 6360            false => "Edit Prediction Discarded",
 6361        };
 6362        telemetry::event!(
 6363            event_type,
 6364            provider = provider.name(),
 6365            prediction_id = id,
 6366            suggestion_accepted = accepted,
 6367            file_extension = extension,
 6368        );
 6369    }
 6370
 6371    pub fn has_active_inline_completion(&self) -> bool {
 6372        self.active_inline_completion.is_some()
 6373    }
 6374
 6375    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6376        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6377            return false;
 6378        };
 6379
 6380        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6381        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6382        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6383        true
 6384    }
 6385
 6386    /// Returns true when we're displaying the edit prediction popover below the cursor
 6387    /// like we are not previewing and the LSP autocomplete menu is visible
 6388    /// or we are in `when_holding_modifier` mode.
 6389    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6390        if self.edit_prediction_preview_is_active()
 6391            || !self.show_edit_predictions_in_menu()
 6392            || !self.edit_predictions_enabled()
 6393        {
 6394            return false;
 6395        }
 6396
 6397        if self.has_visible_completions_menu() {
 6398            return true;
 6399        }
 6400
 6401        has_completion && self.edit_prediction_requires_modifier()
 6402    }
 6403
 6404    fn handle_modifiers_changed(
 6405        &mut self,
 6406        modifiers: Modifiers,
 6407        position_map: &PositionMap,
 6408        window: &mut Window,
 6409        cx: &mut Context<Self>,
 6410    ) {
 6411        if self.show_edit_predictions_in_menu() {
 6412            self.update_edit_prediction_preview(&modifiers, window, cx);
 6413        }
 6414
 6415        self.update_selection_mode(&modifiers, position_map, window, cx);
 6416
 6417        let mouse_position = window.mouse_position();
 6418        if !position_map.text_hitbox.is_hovered(window) {
 6419            return;
 6420        }
 6421
 6422        self.update_hovered_link(
 6423            position_map.point_for_position(mouse_position),
 6424            &position_map.snapshot,
 6425            modifiers,
 6426            window,
 6427            cx,
 6428        )
 6429    }
 6430
 6431    fn update_selection_mode(
 6432        &mut self,
 6433        modifiers: &Modifiers,
 6434        position_map: &PositionMap,
 6435        window: &mut Window,
 6436        cx: &mut Context<Self>,
 6437    ) {
 6438        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6439            return;
 6440        }
 6441
 6442        let mouse_position = window.mouse_position();
 6443        let point_for_position = position_map.point_for_position(mouse_position);
 6444        let position = point_for_position.previous_valid;
 6445
 6446        self.select(
 6447            SelectPhase::BeginColumnar {
 6448                position,
 6449                reset: false,
 6450                goal_column: point_for_position.exact_unclipped.column(),
 6451            },
 6452            window,
 6453            cx,
 6454        );
 6455    }
 6456
 6457    fn update_edit_prediction_preview(
 6458        &mut self,
 6459        modifiers: &Modifiers,
 6460        window: &mut Window,
 6461        cx: &mut Context<Self>,
 6462    ) {
 6463        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6464        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6465            return;
 6466        };
 6467
 6468        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6469            if matches!(
 6470                self.edit_prediction_preview,
 6471                EditPredictionPreview::Inactive { .. }
 6472            ) {
 6473                self.edit_prediction_preview = EditPredictionPreview::Active {
 6474                    previous_scroll_position: None,
 6475                    since: Instant::now(),
 6476                };
 6477
 6478                self.update_visible_inline_completion(window, cx);
 6479                cx.notify();
 6480            }
 6481        } else if let EditPredictionPreview::Active {
 6482            previous_scroll_position,
 6483            since,
 6484        } = self.edit_prediction_preview
 6485        {
 6486            if let (Some(previous_scroll_position), Some(position_map)) =
 6487                (previous_scroll_position, self.last_position_map.as_ref())
 6488            {
 6489                self.set_scroll_position(
 6490                    previous_scroll_position
 6491                        .scroll_position(&position_map.snapshot.display_snapshot),
 6492                    window,
 6493                    cx,
 6494                );
 6495            }
 6496
 6497            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6498                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6499            };
 6500            self.clear_row_highlights::<EditPredictionPreview>();
 6501            self.update_visible_inline_completion(window, cx);
 6502            cx.notify();
 6503        }
 6504    }
 6505
 6506    fn update_visible_inline_completion(
 6507        &mut self,
 6508        _window: &mut Window,
 6509        cx: &mut Context<Self>,
 6510    ) -> Option<()> {
 6511        let selection = self.selections.newest_anchor();
 6512        let cursor = selection.head();
 6513        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6514        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6515        let excerpt_id = cursor.excerpt_id;
 6516
 6517        let show_in_menu = self.show_edit_predictions_in_menu();
 6518        let completions_menu_has_precedence = !show_in_menu
 6519            && (self.context_menu.borrow().is_some()
 6520                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6521
 6522        if completions_menu_has_precedence
 6523            || !offset_selection.is_empty()
 6524            || self
 6525                .active_inline_completion
 6526                .as_ref()
 6527                .map_or(false, |completion| {
 6528                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6529                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6530                    !invalidation_range.contains(&offset_selection.head())
 6531                })
 6532        {
 6533            self.discard_inline_completion(false, cx);
 6534            return None;
 6535        }
 6536
 6537        self.take_active_inline_completion(cx);
 6538        let Some(provider) = self.edit_prediction_provider() else {
 6539            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6540            return None;
 6541        };
 6542
 6543        let (buffer, cursor_buffer_position) =
 6544            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6545
 6546        self.edit_prediction_settings =
 6547            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6548
 6549        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6550
 6551        if self.edit_prediction_indent_conflict {
 6552            let cursor_point = cursor.to_point(&multibuffer);
 6553
 6554            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6555
 6556            if let Some((_, indent)) = indents.iter().next() {
 6557                if indent.len == cursor_point.column {
 6558                    self.edit_prediction_indent_conflict = false;
 6559                }
 6560            }
 6561        }
 6562
 6563        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6564        let edits = inline_completion
 6565            .edits
 6566            .into_iter()
 6567            .flat_map(|(range, new_text)| {
 6568                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6569                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6570                Some((start..end, new_text))
 6571            })
 6572            .collect::<Vec<_>>();
 6573        if edits.is_empty() {
 6574            return None;
 6575        }
 6576
 6577        let first_edit_start = edits.first().unwrap().0.start;
 6578        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6579        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6580
 6581        let last_edit_end = edits.last().unwrap().0.end;
 6582        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6583        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6584
 6585        let cursor_row = cursor.to_point(&multibuffer).row;
 6586
 6587        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6588
 6589        let mut inlay_ids = Vec::new();
 6590        let invalidation_row_range;
 6591        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6592            Some(cursor_row..edit_end_row)
 6593        } else if cursor_row > edit_end_row {
 6594            Some(edit_start_row..cursor_row)
 6595        } else {
 6596            None
 6597        };
 6598        let is_move =
 6599            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6600        let completion = if is_move {
 6601            invalidation_row_range =
 6602                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6603            let target = first_edit_start;
 6604            InlineCompletion::Move { target, snapshot }
 6605        } else {
 6606            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6607                && !self.inline_completions_hidden_for_vim_mode;
 6608
 6609            if show_completions_in_buffer {
 6610                if edits
 6611                    .iter()
 6612                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6613                {
 6614                    let mut inlays = Vec::new();
 6615                    for (range, new_text) in &edits {
 6616                        let inlay = Inlay::inline_completion(
 6617                            post_inc(&mut self.next_inlay_id),
 6618                            range.start,
 6619                            new_text.as_str(),
 6620                        );
 6621                        inlay_ids.push(inlay.id);
 6622                        inlays.push(inlay);
 6623                    }
 6624
 6625                    self.splice_inlays(&[], inlays, cx);
 6626                } else {
 6627                    let background_color = cx.theme().status().deleted_background;
 6628                    self.highlight_text::<InlineCompletionHighlight>(
 6629                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6630                        HighlightStyle {
 6631                            background_color: Some(background_color),
 6632                            ..Default::default()
 6633                        },
 6634                        cx,
 6635                    );
 6636                }
 6637            }
 6638
 6639            invalidation_row_range = edit_start_row..edit_end_row;
 6640
 6641            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6642                if provider.show_tab_accept_marker() {
 6643                    EditDisplayMode::TabAccept
 6644                } else {
 6645                    EditDisplayMode::Inline
 6646                }
 6647            } else {
 6648                EditDisplayMode::DiffPopover
 6649            };
 6650
 6651            InlineCompletion::Edit {
 6652                edits,
 6653                edit_preview: inline_completion.edit_preview,
 6654                display_mode,
 6655                snapshot,
 6656            }
 6657        };
 6658
 6659        let invalidation_range = multibuffer
 6660            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6661            ..multibuffer.anchor_after(Point::new(
 6662                invalidation_row_range.end,
 6663                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6664            ));
 6665
 6666        self.stale_inline_completion_in_menu = None;
 6667        self.active_inline_completion = Some(InlineCompletionState {
 6668            inlay_ids,
 6669            completion,
 6670            completion_id: inline_completion.id,
 6671            invalidation_range,
 6672        });
 6673
 6674        cx.notify();
 6675
 6676        Some(())
 6677    }
 6678
 6679    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6680        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6681    }
 6682
 6683    fn render_code_actions_indicator(
 6684        &self,
 6685        _style: &EditorStyle,
 6686        row: DisplayRow,
 6687        is_active: bool,
 6688        breakpoint: Option<&(Anchor, Breakpoint)>,
 6689        cx: &mut Context<Self>,
 6690    ) -> Option<IconButton> {
 6691        let color = Color::Muted;
 6692        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6693        let show_tooltip = !self.context_menu_visible();
 6694
 6695        if self.available_code_actions.is_some() {
 6696            Some(
 6697                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6698                    .shape(ui::IconButtonShape::Square)
 6699                    .icon_size(IconSize::XSmall)
 6700                    .icon_color(color)
 6701                    .toggle_state(is_active)
 6702                    .when(show_tooltip, |this| {
 6703                        this.tooltip({
 6704                            let focus_handle = self.focus_handle.clone();
 6705                            move |window, cx| {
 6706                                Tooltip::for_action_in(
 6707                                    "Toggle Code Actions",
 6708                                    &ToggleCodeActions {
 6709                                        deployed_from_indicator: None,
 6710                                        quick_launch: false,
 6711                                    },
 6712                                    &focus_handle,
 6713                                    window,
 6714                                    cx,
 6715                                )
 6716                            }
 6717                        })
 6718                    })
 6719                    .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 6720                        let quick_launch = e.down.button == MouseButton::Left;
 6721                        window.focus(&editor.focus_handle(cx));
 6722                        editor.toggle_code_actions(
 6723                            &ToggleCodeActions {
 6724                                deployed_from_indicator: Some(row),
 6725                                quick_launch,
 6726                            },
 6727                            window,
 6728                            cx,
 6729                        );
 6730                    }))
 6731                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6732                        editor.set_breakpoint_context_menu(
 6733                            row,
 6734                            position,
 6735                            event.down.position,
 6736                            window,
 6737                            cx,
 6738                        );
 6739                    })),
 6740            )
 6741        } else {
 6742            None
 6743        }
 6744    }
 6745
 6746    fn clear_tasks(&mut self) {
 6747        self.tasks.clear()
 6748    }
 6749
 6750    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6751        if self.tasks.insert(key, value).is_some() {
 6752            // This case should hopefully be rare, but just in case...
 6753            log::error!(
 6754                "multiple different run targets found on a single line, only the last target will be rendered"
 6755            )
 6756        }
 6757    }
 6758
 6759    /// Get all display points of breakpoints that will be rendered within editor
 6760    ///
 6761    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6762    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6763    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6764    fn active_breakpoints(
 6765        &self,
 6766        range: Range<DisplayRow>,
 6767        window: &mut Window,
 6768        cx: &mut Context<Self>,
 6769    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6770        let mut breakpoint_display_points = HashMap::default();
 6771
 6772        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6773            return breakpoint_display_points;
 6774        };
 6775
 6776        let snapshot = self.snapshot(window, cx);
 6777
 6778        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6779        let Some(project) = self.project.as_ref() else {
 6780            return breakpoint_display_points;
 6781        };
 6782
 6783        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6784            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6785
 6786        for (buffer_snapshot, range, excerpt_id) in
 6787            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6788        {
 6789            let Some(buffer) = project.read_with(cx, |this, cx| {
 6790                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6791            }) else {
 6792                continue;
 6793            };
 6794            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6795                &buffer,
 6796                Some(
 6797                    buffer_snapshot.anchor_before(range.start)
 6798                        ..buffer_snapshot.anchor_after(range.end),
 6799                ),
 6800                buffer_snapshot,
 6801                cx,
 6802            );
 6803            for (anchor, breakpoint) in breakpoints {
 6804                let multi_buffer_anchor =
 6805                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6806                let position = multi_buffer_anchor
 6807                    .to_point(&multi_buffer_snapshot)
 6808                    .to_display_point(&snapshot);
 6809
 6810                breakpoint_display_points
 6811                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6812            }
 6813        }
 6814
 6815        breakpoint_display_points
 6816    }
 6817
 6818    fn breakpoint_context_menu(
 6819        &self,
 6820        anchor: Anchor,
 6821        window: &mut Window,
 6822        cx: &mut Context<Self>,
 6823    ) -> Entity<ui::ContextMenu> {
 6824        let weak_editor = cx.weak_entity();
 6825        let focus_handle = self.focus_handle(cx);
 6826
 6827        let row = self
 6828            .buffer
 6829            .read(cx)
 6830            .snapshot(cx)
 6831            .summary_for_anchor::<Point>(&anchor)
 6832            .row;
 6833
 6834        let breakpoint = self
 6835            .breakpoint_at_row(row, window, cx)
 6836            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6837
 6838        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6839            "Edit Log Breakpoint"
 6840        } else {
 6841            "Set Log Breakpoint"
 6842        };
 6843
 6844        let condition_breakpoint_msg = if breakpoint
 6845            .as_ref()
 6846            .is_some_and(|bp| bp.1.condition.is_some())
 6847        {
 6848            "Edit Condition Breakpoint"
 6849        } else {
 6850            "Set Condition Breakpoint"
 6851        };
 6852
 6853        let hit_condition_breakpoint_msg = if breakpoint
 6854            .as_ref()
 6855            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6856        {
 6857            "Edit Hit Condition Breakpoint"
 6858        } else {
 6859            "Set Hit Condition Breakpoint"
 6860        };
 6861
 6862        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6863            "Unset Breakpoint"
 6864        } else {
 6865            "Set Breakpoint"
 6866        };
 6867
 6868        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6869            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6870
 6871        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6872            BreakpointState::Enabled => Some("Disable"),
 6873            BreakpointState::Disabled => Some("Enable"),
 6874        });
 6875
 6876        let (anchor, breakpoint) =
 6877            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6878
 6879        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6880            menu.on_blur_subscription(Subscription::new(|| {}))
 6881                .context(focus_handle)
 6882                .when(run_to_cursor, |this| {
 6883                    let weak_editor = weak_editor.clone();
 6884                    this.entry("Run to cursor", None, move |window, cx| {
 6885                        weak_editor
 6886                            .update(cx, |editor, cx| {
 6887                                editor.change_selections(None, window, cx, |s| {
 6888                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6889                                });
 6890                            })
 6891                            .ok();
 6892
 6893                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6894                    })
 6895                    .separator()
 6896                })
 6897                .when_some(toggle_state_msg, |this, msg| {
 6898                    this.entry(msg, None, {
 6899                        let weak_editor = weak_editor.clone();
 6900                        let breakpoint = breakpoint.clone();
 6901                        move |_window, cx| {
 6902                            weak_editor
 6903                                .update(cx, |this, cx| {
 6904                                    this.edit_breakpoint_at_anchor(
 6905                                        anchor,
 6906                                        breakpoint.as_ref().clone(),
 6907                                        BreakpointEditAction::InvertState,
 6908                                        cx,
 6909                                    );
 6910                                })
 6911                                .log_err();
 6912                        }
 6913                    })
 6914                })
 6915                .entry(set_breakpoint_msg, None, {
 6916                    let weak_editor = weak_editor.clone();
 6917                    let breakpoint = breakpoint.clone();
 6918                    move |_window, cx| {
 6919                        weak_editor
 6920                            .update(cx, |this, cx| {
 6921                                this.edit_breakpoint_at_anchor(
 6922                                    anchor,
 6923                                    breakpoint.as_ref().clone(),
 6924                                    BreakpointEditAction::Toggle,
 6925                                    cx,
 6926                                );
 6927                            })
 6928                            .log_err();
 6929                    }
 6930                })
 6931                .entry(log_breakpoint_msg, None, {
 6932                    let breakpoint = breakpoint.clone();
 6933                    let weak_editor = weak_editor.clone();
 6934                    move |window, cx| {
 6935                        weak_editor
 6936                            .update(cx, |this, cx| {
 6937                                this.add_edit_breakpoint_block(
 6938                                    anchor,
 6939                                    breakpoint.as_ref(),
 6940                                    BreakpointPromptEditAction::Log,
 6941                                    window,
 6942                                    cx,
 6943                                );
 6944                            })
 6945                            .log_err();
 6946                    }
 6947                })
 6948                .entry(condition_breakpoint_msg, None, {
 6949                    let breakpoint = breakpoint.clone();
 6950                    let weak_editor = weak_editor.clone();
 6951                    move |window, cx| {
 6952                        weak_editor
 6953                            .update(cx, |this, cx| {
 6954                                this.add_edit_breakpoint_block(
 6955                                    anchor,
 6956                                    breakpoint.as_ref(),
 6957                                    BreakpointPromptEditAction::Condition,
 6958                                    window,
 6959                                    cx,
 6960                                );
 6961                            })
 6962                            .log_err();
 6963                    }
 6964                })
 6965                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6966                    weak_editor
 6967                        .update(cx, |this, cx| {
 6968                            this.add_edit_breakpoint_block(
 6969                                anchor,
 6970                                breakpoint.as_ref(),
 6971                                BreakpointPromptEditAction::HitCondition,
 6972                                window,
 6973                                cx,
 6974                            );
 6975                        })
 6976                        .log_err();
 6977                })
 6978        })
 6979    }
 6980
 6981    fn render_breakpoint(
 6982        &self,
 6983        position: Anchor,
 6984        row: DisplayRow,
 6985        breakpoint: &Breakpoint,
 6986        cx: &mut Context<Self>,
 6987    ) -> IconButton {
 6988        // Is it a breakpoint that shows up when hovering over gutter?
 6989        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 6990            (false, false),
 6991            |PhantomBreakpointIndicator {
 6992                 is_active,
 6993                 display_row,
 6994                 collides_with_existing_breakpoint,
 6995             }| {
 6996                (
 6997                    is_active && display_row == row,
 6998                    collides_with_existing_breakpoint,
 6999                )
 7000            },
 7001        );
 7002
 7003        let (color, icon) = {
 7004            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 7005                (false, false) => ui::IconName::DebugBreakpoint,
 7006                (true, false) => ui::IconName::DebugLogBreakpoint,
 7007                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 7008                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 7009            };
 7010
 7011            let color = if is_phantom {
 7012                Color::Hint
 7013            } else {
 7014                Color::Debugger
 7015            };
 7016
 7017            (color, icon)
 7018        };
 7019
 7020        let breakpoint = Arc::from(breakpoint.clone());
 7021
 7022        let alt_as_text = gpui::Keystroke {
 7023            modifiers: Modifiers::secondary_key(),
 7024            ..Default::default()
 7025        };
 7026        let primary_action_text = if breakpoint.is_disabled() {
 7027            "enable"
 7028        } else if is_phantom && !collides_with_existing {
 7029            "set"
 7030        } else {
 7031            "unset"
 7032        };
 7033        let mut primary_text = format!("Click to {primary_action_text}");
 7034        if collides_with_existing && !breakpoint.is_disabled() {
 7035            use std::fmt::Write;
 7036            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7037        }
 7038        let primary_text = SharedString::from(primary_text);
 7039        let focus_handle = self.focus_handle.clone();
 7040        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7041            .icon_size(IconSize::XSmall)
 7042            .size(ui::ButtonSize::None)
 7043            .icon_color(color)
 7044            .style(ButtonStyle::Transparent)
 7045            .on_click(cx.listener({
 7046                let breakpoint = breakpoint.clone();
 7047
 7048                move |editor, event: &ClickEvent, window, cx| {
 7049                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7050                        BreakpointEditAction::InvertState
 7051                    } else {
 7052                        BreakpointEditAction::Toggle
 7053                    };
 7054
 7055                    window.focus(&editor.focus_handle(cx));
 7056                    editor.edit_breakpoint_at_anchor(
 7057                        position,
 7058                        breakpoint.as_ref().clone(),
 7059                        edit_action,
 7060                        cx,
 7061                    );
 7062                }
 7063            }))
 7064            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7065                editor.set_breakpoint_context_menu(
 7066                    row,
 7067                    Some(position),
 7068                    event.down.position,
 7069                    window,
 7070                    cx,
 7071                );
 7072            }))
 7073            .tooltip(move |window, cx| {
 7074                Tooltip::with_meta_in(
 7075                    primary_text.clone(),
 7076                    None,
 7077                    "Right-click for more options",
 7078                    &focus_handle,
 7079                    window,
 7080                    cx,
 7081                )
 7082            })
 7083    }
 7084
 7085    fn build_tasks_context(
 7086        project: &Entity<Project>,
 7087        buffer: &Entity<Buffer>,
 7088        buffer_row: u32,
 7089        tasks: &Arc<RunnableTasks>,
 7090        cx: &mut Context<Self>,
 7091    ) -> Task<Option<task::TaskContext>> {
 7092        let position = Point::new(buffer_row, tasks.column);
 7093        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7094        let location = Location {
 7095            buffer: buffer.clone(),
 7096            range: range_start..range_start,
 7097        };
 7098        // Fill in the environmental variables from the tree-sitter captures
 7099        let mut captured_task_variables = TaskVariables::default();
 7100        for (capture_name, value) in tasks.extra_variables.clone() {
 7101            captured_task_variables.insert(
 7102                task::VariableName::Custom(capture_name.into()),
 7103                value.clone(),
 7104            );
 7105        }
 7106        project.update(cx, |project, cx| {
 7107            project.task_store().update(cx, |task_store, cx| {
 7108                task_store.task_context_for_location(captured_task_variables, location, cx)
 7109            })
 7110        })
 7111    }
 7112
 7113    pub fn spawn_nearest_task(
 7114        &mut self,
 7115        action: &SpawnNearestTask,
 7116        window: &mut Window,
 7117        cx: &mut Context<Self>,
 7118    ) {
 7119        let Some((workspace, _)) = self.workspace.clone() else {
 7120            return;
 7121        };
 7122        let Some(project) = self.project.clone() else {
 7123            return;
 7124        };
 7125
 7126        // Try to find a closest, enclosing node using tree-sitter that has a
 7127        // task
 7128        let Some((buffer, buffer_row, tasks)) = self
 7129            .find_enclosing_node_task(cx)
 7130            // Or find the task that's closest in row-distance.
 7131            .or_else(|| self.find_closest_task(cx))
 7132        else {
 7133            return;
 7134        };
 7135
 7136        let reveal_strategy = action.reveal;
 7137        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7138        cx.spawn_in(window, async move |_, cx| {
 7139            let context = task_context.await?;
 7140            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7141
 7142            let resolved = &mut resolved_task.resolved;
 7143            resolved.reveal = reveal_strategy;
 7144
 7145            workspace
 7146                .update_in(cx, |workspace, window, cx| {
 7147                    workspace.schedule_resolved_task(
 7148                        task_source_kind,
 7149                        resolved_task,
 7150                        false,
 7151                        window,
 7152                        cx,
 7153                    );
 7154                })
 7155                .ok()
 7156        })
 7157        .detach();
 7158    }
 7159
 7160    fn find_closest_task(
 7161        &mut self,
 7162        cx: &mut Context<Self>,
 7163    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7164        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7165
 7166        let ((buffer_id, row), tasks) = self
 7167            .tasks
 7168            .iter()
 7169            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7170
 7171        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7172        let tasks = Arc::new(tasks.to_owned());
 7173        Some((buffer, *row, tasks))
 7174    }
 7175
 7176    fn find_enclosing_node_task(
 7177        &mut self,
 7178        cx: &mut Context<Self>,
 7179    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7180        let snapshot = self.buffer.read(cx).snapshot(cx);
 7181        let offset = self.selections.newest::<usize>(cx).head();
 7182        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7183        let buffer_id = excerpt.buffer().remote_id();
 7184
 7185        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7186        let mut cursor = layer.node().walk();
 7187
 7188        while cursor.goto_first_child_for_byte(offset).is_some() {
 7189            if cursor.node().end_byte() == offset {
 7190                cursor.goto_next_sibling();
 7191            }
 7192        }
 7193
 7194        // Ascend to the smallest ancestor that contains the range and has a task.
 7195        loop {
 7196            let node = cursor.node();
 7197            let node_range = node.byte_range();
 7198            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7199
 7200            // Check if this node contains our offset
 7201            if node_range.start <= offset && node_range.end >= offset {
 7202                // If it contains offset, check for task
 7203                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7204                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7205                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7206                }
 7207            }
 7208
 7209            if !cursor.goto_parent() {
 7210                break;
 7211            }
 7212        }
 7213        None
 7214    }
 7215
 7216    fn render_run_indicator(
 7217        &self,
 7218        _style: &EditorStyle,
 7219        is_active: bool,
 7220        row: DisplayRow,
 7221        breakpoint: Option<(Anchor, Breakpoint)>,
 7222        cx: &mut Context<Self>,
 7223    ) -> IconButton {
 7224        let color = Color::Muted;
 7225        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7226
 7227        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7228            .shape(ui::IconButtonShape::Square)
 7229            .icon_size(IconSize::XSmall)
 7230            .icon_color(color)
 7231            .toggle_state(is_active)
 7232            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7233                let quick_launch = e.down.button == MouseButton::Left;
 7234                window.focus(&editor.focus_handle(cx));
 7235                editor.toggle_code_actions(
 7236                    &ToggleCodeActions {
 7237                        deployed_from_indicator: Some(row),
 7238                        quick_launch,
 7239                    },
 7240                    window,
 7241                    cx,
 7242                );
 7243            }))
 7244            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7245                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7246            }))
 7247    }
 7248
 7249    pub fn context_menu_visible(&self) -> bool {
 7250        !self.edit_prediction_preview_is_active()
 7251            && self
 7252                .context_menu
 7253                .borrow()
 7254                .as_ref()
 7255                .map_or(false, |menu| menu.visible())
 7256    }
 7257
 7258    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7259        self.context_menu
 7260            .borrow()
 7261            .as_ref()
 7262            .map(|menu| menu.origin())
 7263    }
 7264
 7265    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7266        self.context_menu_options = Some(options);
 7267    }
 7268
 7269    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7270    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7271
 7272    fn render_edit_prediction_popover(
 7273        &mut self,
 7274        text_bounds: &Bounds<Pixels>,
 7275        content_origin: gpui::Point<Pixels>,
 7276        editor_snapshot: &EditorSnapshot,
 7277        visible_row_range: Range<DisplayRow>,
 7278        scroll_top: f32,
 7279        scroll_bottom: f32,
 7280        line_layouts: &[LineWithInvisibles],
 7281        line_height: Pixels,
 7282        scroll_pixel_position: gpui::Point<Pixels>,
 7283        newest_selection_head: Option<DisplayPoint>,
 7284        editor_width: Pixels,
 7285        style: &EditorStyle,
 7286        window: &mut Window,
 7287        cx: &mut App,
 7288    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7289        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7290
 7291        if self.edit_prediction_visible_in_cursor_popover(true) {
 7292            return None;
 7293        }
 7294
 7295        match &active_inline_completion.completion {
 7296            InlineCompletion::Move { target, .. } => {
 7297                let target_display_point = target.to_display_point(editor_snapshot);
 7298
 7299                if self.edit_prediction_requires_modifier() {
 7300                    if !self.edit_prediction_preview_is_active() {
 7301                        return None;
 7302                    }
 7303
 7304                    self.render_edit_prediction_modifier_jump_popover(
 7305                        text_bounds,
 7306                        content_origin,
 7307                        visible_row_range,
 7308                        line_layouts,
 7309                        line_height,
 7310                        scroll_pixel_position,
 7311                        newest_selection_head,
 7312                        target_display_point,
 7313                        window,
 7314                        cx,
 7315                    )
 7316                } else {
 7317                    self.render_edit_prediction_eager_jump_popover(
 7318                        text_bounds,
 7319                        content_origin,
 7320                        editor_snapshot,
 7321                        visible_row_range,
 7322                        scroll_top,
 7323                        scroll_bottom,
 7324                        line_height,
 7325                        scroll_pixel_position,
 7326                        target_display_point,
 7327                        editor_width,
 7328                        window,
 7329                        cx,
 7330                    )
 7331                }
 7332            }
 7333            InlineCompletion::Edit {
 7334                display_mode: EditDisplayMode::Inline,
 7335                ..
 7336            } => None,
 7337            InlineCompletion::Edit {
 7338                display_mode: EditDisplayMode::TabAccept,
 7339                edits,
 7340                ..
 7341            } => {
 7342                let range = &edits.first()?.0;
 7343                let target_display_point = range.end.to_display_point(editor_snapshot);
 7344
 7345                self.render_edit_prediction_end_of_line_popover(
 7346                    "Accept",
 7347                    editor_snapshot,
 7348                    visible_row_range,
 7349                    target_display_point,
 7350                    line_height,
 7351                    scroll_pixel_position,
 7352                    content_origin,
 7353                    editor_width,
 7354                    window,
 7355                    cx,
 7356                )
 7357            }
 7358            InlineCompletion::Edit {
 7359                edits,
 7360                edit_preview,
 7361                display_mode: EditDisplayMode::DiffPopover,
 7362                snapshot,
 7363            } => self.render_edit_prediction_diff_popover(
 7364                text_bounds,
 7365                content_origin,
 7366                editor_snapshot,
 7367                visible_row_range,
 7368                line_layouts,
 7369                line_height,
 7370                scroll_pixel_position,
 7371                newest_selection_head,
 7372                editor_width,
 7373                style,
 7374                edits,
 7375                edit_preview,
 7376                snapshot,
 7377                window,
 7378                cx,
 7379            ),
 7380        }
 7381    }
 7382
 7383    fn render_edit_prediction_modifier_jump_popover(
 7384        &mut self,
 7385        text_bounds: &Bounds<Pixels>,
 7386        content_origin: gpui::Point<Pixels>,
 7387        visible_row_range: Range<DisplayRow>,
 7388        line_layouts: &[LineWithInvisibles],
 7389        line_height: Pixels,
 7390        scroll_pixel_position: gpui::Point<Pixels>,
 7391        newest_selection_head: Option<DisplayPoint>,
 7392        target_display_point: DisplayPoint,
 7393        window: &mut Window,
 7394        cx: &mut App,
 7395    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7396        let scrolled_content_origin =
 7397            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7398
 7399        const SCROLL_PADDING_Y: Pixels = px(12.);
 7400
 7401        if target_display_point.row() < visible_row_range.start {
 7402            return self.render_edit_prediction_scroll_popover(
 7403                |_| SCROLL_PADDING_Y,
 7404                IconName::ArrowUp,
 7405                visible_row_range,
 7406                line_layouts,
 7407                newest_selection_head,
 7408                scrolled_content_origin,
 7409                window,
 7410                cx,
 7411            );
 7412        } else if target_display_point.row() >= visible_row_range.end {
 7413            return self.render_edit_prediction_scroll_popover(
 7414                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7415                IconName::ArrowDown,
 7416                visible_row_range,
 7417                line_layouts,
 7418                newest_selection_head,
 7419                scrolled_content_origin,
 7420                window,
 7421                cx,
 7422            );
 7423        }
 7424
 7425        const POLE_WIDTH: Pixels = px(2.);
 7426
 7427        let line_layout =
 7428            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7429        let target_column = target_display_point.column() as usize;
 7430
 7431        let target_x = line_layout.x_for_index(target_column);
 7432        let target_y =
 7433            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7434
 7435        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7436
 7437        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7438        border_color.l += 0.001;
 7439
 7440        let mut element = v_flex()
 7441            .items_end()
 7442            .when(flag_on_right, |el| el.items_start())
 7443            .child(if flag_on_right {
 7444                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7445                    .rounded_bl(px(0.))
 7446                    .rounded_tl(px(0.))
 7447                    .border_l_2()
 7448                    .border_color(border_color)
 7449            } else {
 7450                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7451                    .rounded_br(px(0.))
 7452                    .rounded_tr(px(0.))
 7453                    .border_r_2()
 7454                    .border_color(border_color)
 7455            })
 7456            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7457            .into_any();
 7458
 7459        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7460
 7461        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7462            - point(
 7463                if flag_on_right {
 7464                    POLE_WIDTH
 7465                } else {
 7466                    size.width - POLE_WIDTH
 7467                },
 7468                size.height - line_height,
 7469            );
 7470
 7471        origin.x = origin.x.max(content_origin.x);
 7472
 7473        element.prepaint_at(origin, window, cx);
 7474
 7475        Some((element, origin))
 7476    }
 7477
 7478    fn render_edit_prediction_scroll_popover(
 7479        &mut self,
 7480        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7481        scroll_icon: IconName,
 7482        visible_row_range: Range<DisplayRow>,
 7483        line_layouts: &[LineWithInvisibles],
 7484        newest_selection_head: Option<DisplayPoint>,
 7485        scrolled_content_origin: gpui::Point<Pixels>,
 7486        window: &mut Window,
 7487        cx: &mut App,
 7488    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7489        let mut element = self
 7490            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7491            .into_any();
 7492
 7493        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7494
 7495        let cursor = newest_selection_head?;
 7496        let cursor_row_layout =
 7497            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7498        let cursor_column = cursor.column() as usize;
 7499
 7500        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7501
 7502        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7503
 7504        element.prepaint_at(origin, window, cx);
 7505        Some((element, origin))
 7506    }
 7507
 7508    fn render_edit_prediction_eager_jump_popover(
 7509        &mut self,
 7510        text_bounds: &Bounds<Pixels>,
 7511        content_origin: gpui::Point<Pixels>,
 7512        editor_snapshot: &EditorSnapshot,
 7513        visible_row_range: Range<DisplayRow>,
 7514        scroll_top: f32,
 7515        scroll_bottom: f32,
 7516        line_height: Pixels,
 7517        scroll_pixel_position: gpui::Point<Pixels>,
 7518        target_display_point: DisplayPoint,
 7519        editor_width: Pixels,
 7520        window: &mut Window,
 7521        cx: &mut App,
 7522    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7523        if target_display_point.row().as_f32() < scroll_top {
 7524            let mut element = self
 7525                .render_edit_prediction_line_popover(
 7526                    "Jump to Edit",
 7527                    Some(IconName::ArrowUp),
 7528                    window,
 7529                    cx,
 7530                )?
 7531                .into_any();
 7532
 7533            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7534            let offset = point(
 7535                (text_bounds.size.width - size.width) / 2.,
 7536                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7537            );
 7538
 7539            let origin = text_bounds.origin + offset;
 7540            element.prepaint_at(origin, window, cx);
 7541            Some((element, origin))
 7542        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7543            let mut element = self
 7544                .render_edit_prediction_line_popover(
 7545                    "Jump to Edit",
 7546                    Some(IconName::ArrowDown),
 7547                    window,
 7548                    cx,
 7549                )?
 7550                .into_any();
 7551
 7552            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7553            let offset = point(
 7554                (text_bounds.size.width - size.width) / 2.,
 7555                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7556            );
 7557
 7558            let origin = text_bounds.origin + offset;
 7559            element.prepaint_at(origin, window, cx);
 7560            Some((element, origin))
 7561        } else {
 7562            self.render_edit_prediction_end_of_line_popover(
 7563                "Jump to Edit",
 7564                editor_snapshot,
 7565                visible_row_range,
 7566                target_display_point,
 7567                line_height,
 7568                scroll_pixel_position,
 7569                content_origin,
 7570                editor_width,
 7571                window,
 7572                cx,
 7573            )
 7574        }
 7575    }
 7576
 7577    fn render_edit_prediction_end_of_line_popover(
 7578        self: &mut Editor,
 7579        label: &'static str,
 7580        editor_snapshot: &EditorSnapshot,
 7581        visible_row_range: Range<DisplayRow>,
 7582        target_display_point: DisplayPoint,
 7583        line_height: Pixels,
 7584        scroll_pixel_position: gpui::Point<Pixels>,
 7585        content_origin: gpui::Point<Pixels>,
 7586        editor_width: Pixels,
 7587        window: &mut Window,
 7588        cx: &mut App,
 7589    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7590        let target_line_end = DisplayPoint::new(
 7591            target_display_point.row(),
 7592            editor_snapshot.line_len(target_display_point.row()),
 7593        );
 7594
 7595        let mut element = self
 7596            .render_edit_prediction_line_popover(label, None, window, cx)?
 7597            .into_any();
 7598
 7599        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7600
 7601        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7602
 7603        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7604        let mut origin = start_point
 7605            + line_origin
 7606            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7607        origin.x = origin.x.max(content_origin.x);
 7608
 7609        let max_x = content_origin.x + editor_width - size.width;
 7610
 7611        if origin.x > max_x {
 7612            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7613
 7614            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7615                origin.y += offset;
 7616                IconName::ArrowUp
 7617            } else {
 7618                origin.y -= offset;
 7619                IconName::ArrowDown
 7620            };
 7621
 7622            element = self
 7623                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7624                .into_any();
 7625
 7626            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7627
 7628            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7629        }
 7630
 7631        element.prepaint_at(origin, window, cx);
 7632        Some((element, origin))
 7633    }
 7634
 7635    fn render_edit_prediction_diff_popover(
 7636        self: &Editor,
 7637        text_bounds: &Bounds<Pixels>,
 7638        content_origin: gpui::Point<Pixels>,
 7639        editor_snapshot: &EditorSnapshot,
 7640        visible_row_range: Range<DisplayRow>,
 7641        line_layouts: &[LineWithInvisibles],
 7642        line_height: Pixels,
 7643        scroll_pixel_position: gpui::Point<Pixels>,
 7644        newest_selection_head: Option<DisplayPoint>,
 7645        editor_width: Pixels,
 7646        style: &EditorStyle,
 7647        edits: &Vec<(Range<Anchor>, String)>,
 7648        edit_preview: &Option<language::EditPreview>,
 7649        snapshot: &language::BufferSnapshot,
 7650        window: &mut Window,
 7651        cx: &mut App,
 7652    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7653        let edit_start = edits
 7654            .first()
 7655            .unwrap()
 7656            .0
 7657            .start
 7658            .to_display_point(editor_snapshot);
 7659        let edit_end = edits
 7660            .last()
 7661            .unwrap()
 7662            .0
 7663            .end
 7664            .to_display_point(editor_snapshot);
 7665
 7666        let is_visible = visible_row_range.contains(&edit_start.row())
 7667            || visible_row_range.contains(&edit_end.row());
 7668        if !is_visible {
 7669            return None;
 7670        }
 7671
 7672        let highlighted_edits =
 7673            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7674
 7675        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7676        let line_count = highlighted_edits.text.lines().count();
 7677
 7678        const BORDER_WIDTH: Pixels = px(1.);
 7679
 7680        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7681        let has_keybind = keybind.is_some();
 7682
 7683        let mut element = h_flex()
 7684            .items_start()
 7685            .child(
 7686                h_flex()
 7687                    .bg(cx.theme().colors().editor_background)
 7688                    .border(BORDER_WIDTH)
 7689                    .shadow_sm()
 7690                    .border_color(cx.theme().colors().border)
 7691                    .rounded_l_lg()
 7692                    .when(line_count > 1, |el| el.rounded_br_lg())
 7693                    .pr_1()
 7694                    .child(styled_text),
 7695            )
 7696            .child(
 7697                h_flex()
 7698                    .h(line_height + BORDER_WIDTH * 2.)
 7699                    .px_1p5()
 7700                    .gap_1()
 7701                    // Workaround: For some reason, there's a gap if we don't do this
 7702                    .ml(-BORDER_WIDTH)
 7703                    .shadow(smallvec![gpui::BoxShadow {
 7704                        color: gpui::black().opacity(0.05),
 7705                        offset: point(px(1.), px(1.)),
 7706                        blur_radius: px(2.),
 7707                        spread_radius: px(0.),
 7708                    }])
 7709                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7710                    .border(BORDER_WIDTH)
 7711                    .border_color(cx.theme().colors().border)
 7712                    .rounded_r_lg()
 7713                    .id("edit_prediction_diff_popover_keybind")
 7714                    .when(!has_keybind, |el| {
 7715                        let status_colors = cx.theme().status();
 7716
 7717                        el.bg(status_colors.error_background)
 7718                            .border_color(status_colors.error.opacity(0.6))
 7719                            .child(Icon::new(IconName::Info).color(Color::Error))
 7720                            .cursor_default()
 7721                            .hoverable_tooltip(move |_window, cx| {
 7722                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7723                            })
 7724                    })
 7725                    .children(keybind),
 7726            )
 7727            .into_any();
 7728
 7729        let longest_row =
 7730            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7731        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7732            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7733        } else {
 7734            layout_line(
 7735                longest_row,
 7736                editor_snapshot,
 7737                style,
 7738                editor_width,
 7739                |_| false,
 7740                window,
 7741                cx,
 7742            )
 7743            .width
 7744        };
 7745
 7746        let viewport_bounds =
 7747            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7748                right: -EditorElement::SCROLLBAR_WIDTH,
 7749                ..Default::default()
 7750            });
 7751
 7752        let x_after_longest =
 7753            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7754                - scroll_pixel_position.x;
 7755
 7756        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7757
 7758        // Fully visible if it can be displayed within the window (allow overlapping other
 7759        // panes). However, this is only allowed if the popover starts within text_bounds.
 7760        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7761            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7762
 7763        let mut origin = if can_position_to_the_right {
 7764            point(
 7765                x_after_longest,
 7766                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7767                    - scroll_pixel_position.y,
 7768            )
 7769        } else {
 7770            let cursor_row = newest_selection_head.map(|head| head.row());
 7771            let above_edit = edit_start
 7772                .row()
 7773                .0
 7774                .checked_sub(line_count as u32)
 7775                .map(DisplayRow);
 7776            let below_edit = Some(edit_end.row() + 1);
 7777            let above_cursor =
 7778                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7779            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7780
 7781            // Place the edit popover adjacent to the edit if there is a location
 7782            // available that is onscreen and does not obscure the cursor. Otherwise,
 7783            // place it adjacent to the cursor.
 7784            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7785                .into_iter()
 7786                .flatten()
 7787                .find(|&start_row| {
 7788                    let end_row = start_row + line_count as u32;
 7789                    visible_row_range.contains(&start_row)
 7790                        && visible_row_range.contains(&end_row)
 7791                        && cursor_row.map_or(true, |cursor_row| {
 7792                            !((start_row..end_row).contains(&cursor_row))
 7793                        })
 7794                })?;
 7795
 7796            content_origin
 7797                + point(
 7798                    -scroll_pixel_position.x,
 7799                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7800                )
 7801        };
 7802
 7803        origin.x -= BORDER_WIDTH;
 7804
 7805        window.defer_draw(element, origin, 1);
 7806
 7807        // Do not return an element, since it will already be drawn due to defer_draw.
 7808        None
 7809    }
 7810
 7811    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7812        px(30.)
 7813    }
 7814
 7815    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7816        if self.read_only(cx) {
 7817            cx.theme().players().read_only()
 7818        } else {
 7819            self.style.as_ref().unwrap().local_player
 7820        }
 7821    }
 7822
 7823    fn render_edit_prediction_accept_keybind(
 7824        &self,
 7825        window: &mut Window,
 7826        cx: &App,
 7827    ) -> Option<AnyElement> {
 7828        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7829        let accept_keystroke = accept_binding.keystroke()?;
 7830
 7831        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7832
 7833        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7834            Color::Accent
 7835        } else {
 7836            Color::Muted
 7837        };
 7838
 7839        h_flex()
 7840            .px_0p5()
 7841            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7842            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7843            .text_size(TextSize::XSmall.rems(cx))
 7844            .child(h_flex().children(ui::render_modifiers(
 7845                &accept_keystroke.modifiers,
 7846                PlatformStyle::platform(),
 7847                Some(modifiers_color),
 7848                Some(IconSize::XSmall.rems().into()),
 7849                true,
 7850            )))
 7851            .when(is_platform_style_mac, |parent| {
 7852                parent.child(accept_keystroke.key.clone())
 7853            })
 7854            .when(!is_platform_style_mac, |parent| {
 7855                parent.child(
 7856                    Key::new(
 7857                        util::capitalize(&accept_keystroke.key),
 7858                        Some(Color::Default),
 7859                    )
 7860                    .size(Some(IconSize::XSmall.rems().into())),
 7861                )
 7862            })
 7863            .into_any()
 7864            .into()
 7865    }
 7866
 7867    fn render_edit_prediction_line_popover(
 7868        &self,
 7869        label: impl Into<SharedString>,
 7870        icon: Option<IconName>,
 7871        window: &mut Window,
 7872        cx: &App,
 7873    ) -> Option<Stateful<Div>> {
 7874        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7875
 7876        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7877        let has_keybind = keybind.is_some();
 7878
 7879        let result = h_flex()
 7880            .id("ep-line-popover")
 7881            .py_0p5()
 7882            .pl_1()
 7883            .pr(padding_right)
 7884            .gap_1()
 7885            .rounded_md()
 7886            .border_1()
 7887            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7888            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7889            .shadow_sm()
 7890            .when(!has_keybind, |el| {
 7891                let status_colors = cx.theme().status();
 7892
 7893                el.bg(status_colors.error_background)
 7894                    .border_color(status_colors.error.opacity(0.6))
 7895                    .pl_2()
 7896                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7897                    .cursor_default()
 7898                    .hoverable_tooltip(move |_window, cx| {
 7899                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7900                    })
 7901            })
 7902            .children(keybind)
 7903            .child(
 7904                Label::new(label)
 7905                    .size(LabelSize::Small)
 7906                    .when(!has_keybind, |el| {
 7907                        el.color(cx.theme().status().error.into()).strikethrough()
 7908                    }),
 7909            )
 7910            .when(!has_keybind, |el| {
 7911                el.child(
 7912                    h_flex().ml_1().child(
 7913                        Icon::new(IconName::Info)
 7914                            .size(IconSize::Small)
 7915                            .color(cx.theme().status().error.into()),
 7916                    ),
 7917                )
 7918            })
 7919            .when_some(icon, |element, icon| {
 7920                element.child(
 7921                    div()
 7922                        .mt(px(1.5))
 7923                        .child(Icon::new(icon).size(IconSize::Small)),
 7924                )
 7925            });
 7926
 7927        Some(result)
 7928    }
 7929
 7930    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7931        let accent_color = cx.theme().colors().text_accent;
 7932        let editor_bg_color = cx.theme().colors().editor_background;
 7933        editor_bg_color.blend(accent_color.opacity(0.1))
 7934    }
 7935
 7936    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7937        let accent_color = cx.theme().colors().text_accent;
 7938        let editor_bg_color = cx.theme().colors().editor_background;
 7939        editor_bg_color.blend(accent_color.opacity(0.6))
 7940    }
 7941
 7942    fn render_edit_prediction_cursor_popover(
 7943        &self,
 7944        min_width: Pixels,
 7945        max_width: Pixels,
 7946        cursor_point: Point,
 7947        style: &EditorStyle,
 7948        accept_keystroke: Option<&gpui::Keystroke>,
 7949        _window: &Window,
 7950        cx: &mut Context<Editor>,
 7951    ) -> Option<AnyElement> {
 7952        let provider = self.edit_prediction_provider.as_ref()?;
 7953
 7954        if provider.provider.needs_terms_acceptance(cx) {
 7955            return Some(
 7956                h_flex()
 7957                    .min_w(min_width)
 7958                    .flex_1()
 7959                    .px_2()
 7960                    .py_1()
 7961                    .gap_3()
 7962                    .elevation_2(cx)
 7963                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7964                    .id("accept-terms")
 7965                    .cursor_pointer()
 7966                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7967                    .on_click(cx.listener(|this, _event, window, cx| {
 7968                        cx.stop_propagation();
 7969                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7970                        window.dispatch_action(
 7971                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7972                            cx,
 7973                        );
 7974                    }))
 7975                    .child(
 7976                        h_flex()
 7977                            .flex_1()
 7978                            .gap_2()
 7979                            .child(Icon::new(IconName::ZedPredict))
 7980                            .child(Label::new("Accept Terms of Service"))
 7981                            .child(div().w_full())
 7982                            .child(
 7983                                Icon::new(IconName::ArrowUpRight)
 7984                                    .color(Color::Muted)
 7985                                    .size(IconSize::Small),
 7986                            )
 7987                            .into_any_element(),
 7988                    )
 7989                    .into_any(),
 7990            );
 7991        }
 7992
 7993        let is_refreshing = provider.provider.is_refreshing(cx);
 7994
 7995        fn pending_completion_container() -> Div {
 7996            h_flex()
 7997                .h_full()
 7998                .flex_1()
 7999                .gap_2()
 8000                .child(Icon::new(IconName::ZedPredict))
 8001        }
 8002
 8003        let completion = match &self.active_inline_completion {
 8004            Some(prediction) => {
 8005                if !self.has_visible_completions_menu() {
 8006                    const RADIUS: Pixels = px(6.);
 8007                    const BORDER_WIDTH: Pixels = px(1.);
 8008
 8009                    return Some(
 8010                        h_flex()
 8011                            .elevation_2(cx)
 8012                            .border(BORDER_WIDTH)
 8013                            .border_color(cx.theme().colors().border)
 8014                            .when(accept_keystroke.is_none(), |el| {
 8015                                el.border_color(cx.theme().status().error)
 8016                            })
 8017                            .rounded(RADIUS)
 8018                            .rounded_tl(px(0.))
 8019                            .overflow_hidden()
 8020                            .child(div().px_1p5().child(match &prediction.completion {
 8021                                InlineCompletion::Move { target, snapshot } => {
 8022                                    use text::ToPoint as _;
 8023                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 8024                                    {
 8025                                        Icon::new(IconName::ZedPredictDown)
 8026                                    } else {
 8027                                        Icon::new(IconName::ZedPredictUp)
 8028                                    }
 8029                                }
 8030                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 8031                            }))
 8032                            .child(
 8033                                h_flex()
 8034                                    .gap_1()
 8035                                    .py_1()
 8036                                    .px_2()
 8037                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8038                                    .border_l_1()
 8039                                    .border_color(cx.theme().colors().border)
 8040                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8041                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8042                                        el.child(
 8043                                            Label::new("Hold")
 8044                                                .size(LabelSize::Small)
 8045                                                .when(accept_keystroke.is_none(), |el| {
 8046                                                    el.strikethrough()
 8047                                                })
 8048                                                .line_height_style(LineHeightStyle::UiLabel),
 8049                                        )
 8050                                    })
 8051                                    .id("edit_prediction_cursor_popover_keybind")
 8052                                    .when(accept_keystroke.is_none(), |el| {
 8053                                        let status_colors = cx.theme().status();
 8054
 8055                                        el.bg(status_colors.error_background)
 8056                                            .border_color(status_colors.error.opacity(0.6))
 8057                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8058                                            .cursor_default()
 8059                                            .hoverable_tooltip(move |_window, cx| {
 8060                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8061                                                    .into()
 8062                                            })
 8063                                    })
 8064                                    .when_some(
 8065                                        accept_keystroke.as_ref(),
 8066                                        |el, accept_keystroke| {
 8067                                            el.child(h_flex().children(ui::render_modifiers(
 8068                                                &accept_keystroke.modifiers,
 8069                                                PlatformStyle::platform(),
 8070                                                Some(Color::Default),
 8071                                                Some(IconSize::XSmall.rems().into()),
 8072                                                false,
 8073                                            )))
 8074                                        },
 8075                                    ),
 8076                            )
 8077                            .into_any(),
 8078                    );
 8079                }
 8080
 8081                self.render_edit_prediction_cursor_popover_preview(
 8082                    prediction,
 8083                    cursor_point,
 8084                    style,
 8085                    cx,
 8086                )?
 8087            }
 8088
 8089            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8090                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8091                    stale_completion,
 8092                    cursor_point,
 8093                    style,
 8094                    cx,
 8095                )?,
 8096
 8097                None => {
 8098                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8099                }
 8100            },
 8101
 8102            None => pending_completion_container().child(Label::new("No Prediction")),
 8103        };
 8104
 8105        let completion = if is_refreshing {
 8106            completion
 8107                .with_animation(
 8108                    "loading-completion",
 8109                    Animation::new(Duration::from_secs(2))
 8110                        .repeat()
 8111                        .with_easing(pulsating_between(0.4, 0.8)),
 8112                    |label, delta| label.opacity(delta),
 8113                )
 8114                .into_any_element()
 8115        } else {
 8116            completion.into_any_element()
 8117        };
 8118
 8119        let has_completion = self.active_inline_completion.is_some();
 8120
 8121        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8122        Some(
 8123            h_flex()
 8124                .min_w(min_width)
 8125                .max_w(max_width)
 8126                .flex_1()
 8127                .elevation_2(cx)
 8128                .border_color(cx.theme().colors().border)
 8129                .child(
 8130                    div()
 8131                        .flex_1()
 8132                        .py_1()
 8133                        .px_2()
 8134                        .overflow_hidden()
 8135                        .child(completion),
 8136                )
 8137                .when_some(accept_keystroke, |el, accept_keystroke| {
 8138                    if !accept_keystroke.modifiers.modified() {
 8139                        return el;
 8140                    }
 8141
 8142                    el.child(
 8143                        h_flex()
 8144                            .h_full()
 8145                            .border_l_1()
 8146                            .rounded_r_lg()
 8147                            .border_color(cx.theme().colors().border)
 8148                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8149                            .gap_1()
 8150                            .py_1()
 8151                            .px_2()
 8152                            .child(
 8153                                h_flex()
 8154                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8155                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8156                                    .child(h_flex().children(ui::render_modifiers(
 8157                                        &accept_keystroke.modifiers,
 8158                                        PlatformStyle::platform(),
 8159                                        Some(if !has_completion {
 8160                                            Color::Muted
 8161                                        } else {
 8162                                            Color::Default
 8163                                        }),
 8164                                        None,
 8165                                        false,
 8166                                    ))),
 8167                            )
 8168                            .child(Label::new("Preview").into_any_element())
 8169                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8170                    )
 8171                })
 8172                .into_any(),
 8173        )
 8174    }
 8175
 8176    fn render_edit_prediction_cursor_popover_preview(
 8177        &self,
 8178        completion: &InlineCompletionState,
 8179        cursor_point: Point,
 8180        style: &EditorStyle,
 8181        cx: &mut Context<Editor>,
 8182    ) -> Option<Div> {
 8183        use text::ToPoint as _;
 8184
 8185        fn render_relative_row_jump(
 8186            prefix: impl Into<String>,
 8187            current_row: u32,
 8188            target_row: u32,
 8189        ) -> Div {
 8190            let (row_diff, arrow) = if target_row < current_row {
 8191                (current_row - target_row, IconName::ArrowUp)
 8192            } else {
 8193                (target_row - current_row, IconName::ArrowDown)
 8194            };
 8195
 8196            h_flex()
 8197                .child(
 8198                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8199                        .color(Color::Muted)
 8200                        .size(LabelSize::Small),
 8201                )
 8202                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8203        }
 8204
 8205        match &completion.completion {
 8206            InlineCompletion::Move {
 8207                target, snapshot, ..
 8208            } => Some(
 8209                h_flex()
 8210                    .px_2()
 8211                    .gap_2()
 8212                    .flex_1()
 8213                    .child(
 8214                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8215                            Icon::new(IconName::ZedPredictDown)
 8216                        } else {
 8217                            Icon::new(IconName::ZedPredictUp)
 8218                        },
 8219                    )
 8220                    .child(Label::new("Jump to Edit")),
 8221            ),
 8222
 8223            InlineCompletion::Edit {
 8224                edits,
 8225                edit_preview,
 8226                snapshot,
 8227                display_mode: _,
 8228            } => {
 8229                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8230
 8231                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8232                    &snapshot,
 8233                    &edits,
 8234                    edit_preview.as_ref()?,
 8235                    true,
 8236                    cx,
 8237                )
 8238                .first_line_preview();
 8239
 8240                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8241                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8242
 8243                let preview = h_flex()
 8244                    .gap_1()
 8245                    .min_w_16()
 8246                    .child(styled_text)
 8247                    .when(has_more_lines, |parent| parent.child(""));
 8248
 8249                let left = if first_edit_row != cursor_point.row {
 8250                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8251                        .into_any_element()
 8252                } else {
 8253                    Icon::new(IconName::ZedPredict).into_any_element()
 8254                };
 8255
 8256                Some(
 8257                    h_flex()
 8258                        .h_full()
 8259                        .flex_1()
 8260                        .gap_2()
 8261                        .pr_1()
 8262                        .overflow_x_hidden()
 8263                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8264                        .child(left)
 8265                        .child(preview),
 8266                )
 8267            }
 8268        }
 8269    }
 8270
 8271    fn render_context_menu(
 8272        &self,
 8273        style: &EditorStyle,
 8274        max_height_in_lines: u32,
 8275        window: &mut Window,
 8276        cx: &mut Context<Editor>,
 8277    ) -> Option<AnyElement> {
 8278        let menu = self.context_menu.borrow();
 8279        let menu = menu.as_ref()?;
 8280        if !menu.visible() {
 8281            return None;
 8282        };
 8283        Some(menu.render(style, max_height_in_lines, window, cx))
 8284    }
 8285
 8286    fn render_context_menu_aside(
 8287        &mut self,
 8288        max_size: Size<Pixels>,
 8289        window: &mut Window,
 8290        cx: &mut Context<Editor>,
 8291    ) -> Option<AnyElement> {
 8292        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8293            if menu.visible() {
 8294                menu.render_aside(self, max_size, window, cx)
 8295            } else {
 8296                None
 8297            }
 8298        })
 8299    }
 8300
 8301    fn hide_context_menu(
 8302        &mut self,
 8303        window: &mut Window,
 8304        cx: &mut Context<Self>,
 8305    ) -> Option<CodeContextMenu> {
 8306        cx.notify();
 8307        self.completion_tasks.clear();
 8308        let context_menu = self.context_menu.borrow_mut().take();
 8309        self.stale_inline_completion_in_menu.take();
 8310        self.update_visible_inline_completion(window, cx);
 8311        context_menu
 8312    }
 8313
 8314    fn show_snippet_choices(
 8315        &mut self,
 8316        choices: &Vec<String>,
 8317        selection: Range<Anchor>,
 8318        cx: &mut Context<Self>,
 8319    ) {
 8320        if selection.start.buffer_id.is_none() {
 8321            return;
 8322        }
 8323        let buffer_id = selection.start.buffer_id.unwrap();
 8324        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8325        let id = post_inc(&mut self.next_completion_id);
 8326        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8327
 8328        if let Some(buffer) = buffer {
 8329            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8330                CompletionsMenu::new_snippet_choices(
 8331                    id,
 8332                    true,
 8333                    choices,
 8334                    selection,
 8335                    buffer,
 8336                    snippet_sort_order,
 8337                ),
 8338            ));
 8339        }
 8340    }
 8341
 8342    pub fn insert_snippet(
 8343        &mut self,
 8344        insertion_ranges: &[Range<usize>],
 8345        snippet: Snippet,
 8346        window: &mut Window,
 8347        cx: &mut Context<Self>,
 8348    ) -> Result<()> {
 8349        struct Tabstop<T> {
 8350            is_end_tabstop: bool,
 8351            ranges: Vec<Range<T>>,
 8352            choices: Option<Vec<String>>,
 8353        }
 8354
 8355        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8356            let snippet_text: Arc<str> = snippet.text.clone().into();
 8357            let edits = insertion_ranges
 8358                .iter()
 8359                .cloned()
 8360                .map(|range| (range, snippet_text.clone()));
 8361            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8362
 8363            let snapshot = &*buffer.read(cx);
 8364            let snippet = &snippet;
 8365            snippet
 8366                .tabstops
 8367                .iter()
 8368                .map(|tabstop| {
 8369                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8370                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8371                    });
 8372                    let mut tabstop_ranges = tabstop
 8373                        .ranges
 8374                        .iter()
 8375                        .flat_map(|tabstop_range| {
 8376                            let mut delta = 0_isize;
 8377                            insertion_ranges.iter().map(move |insertion_range| {
 8378                                let insertion_start = insertion_range.start as isize + delta;
 8379                                delta +=
 8380                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8381
 8382                                let start = ((insertion_start + tabstop_range.start) as usize)
 8383                                    .min(snapshot.len());
 8384                                let end = ((insertion_start + tabstop_range.end) as usize)
 8385                                    .min(snapshot.len());
 8386                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8387                            })
 8388                        })
 8389                        .collect::<Vec<_>>();
 8390                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8391
 8392                    Tabstop {
 8393                        is_end_tabstop,
 8394                        ranges: tabstop_ranges,
 8395                        choices: tabstop.choices.clone(),
 8396                    }
 8397                })
 8398                .collect::<Vec<_>>()
 8399        });
 8400        if let Some(tabstop) = tabstops.first() {
 8401            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8402                s.select_ranges(tabstop.ranges.iter().cloned());
 8403            });
 8404
 8405            if let Some(choices) = &tabstop.choices {
 8406                if let Some(selection) = tabstop.ranges.first() {
 8407                    self.show_snippet_choices(choices, selection.clone(), cx)
 8408                }
 8409            }
 8410
 8411            // If we're already at the last tabstop and it's at the end of the snippet,
 8412            // we're done, we don't need to keep the state around.
 8413            if !tabstop.is_end_tabstop {
 8414                let choices = tabstops
 8415                    .iter()
 8416                    .map(|tabstop| tabstop.choices.clone())
 8417                    .collect();
 8418
 8419                let ranges = tabstops
 8420                    .into_iter()
 8421                    .map(|tabstop| tabstop.ranges)
 8422                    .collect::<Vec<_>>();
 8423
 8424                self.snippet_stack.push(SnippetState {
 8425                    active_index: 0,
 8426                    ranges,
 8427                    choices,
 8428                });
 8429            }
 8430
 8431            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8432            if self.autoclose_regions.is_empty() {
 8433                let snapshot = self.buffer.read(cx).snapshot(cx);
 8434                for selection in &mut self.selections.all::<Point>(cx) {
 8435                    let selection_head = selection.head();
 8436                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8437                        continue;
 8438                    };
 8439
 8440                    let mut bracket_pair = None;
 8441                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8442                    let prev_chars = snapshot
 8443                        .reversed_chars_at(selection_head)
 8444                        .collect::<String>();
 8445                    for (pair, enabled) in scope.brackets() {
 8446                        if enabled
 8447                            && pair.close
 8448                            && prev_chars.starts_with(pair.start.as_str())
 8449                            && next_chars.starts_with(pair.end.as_str())
 8450                        {
 8451                            bracket_pair = Some(pair.clone());
 8452                            break;
 8453                        }
 8454                    }
 8455                    if let Some(pair) = bracket_pair {
 8456                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8457                        let autoclose_enabled =
 8458                            self.use_autoclose && snapshot_settings.use_autoclose;
 8459                        if autoclose_enabled {
 8460                            let start = snapshot.anchor_after(selection_head);
 8461                            let end = snapshot.anchor_after(selection_head);
 8462                            self.autoclose_regions.push(AutocloseRegion {
 8463                                selection_id: selection.id,
 8464                                range: start..end,
 8465                                pair,
 8466                            });
 8467                        }
 8468                    }
 8469                }
 8470            }
 8471        }
 8472        Ok(())
 8473    }
 8474
 8475    pub fn move_to_next_snippet_tabstop(
 8476        &mut self,
 8477        window: &mut Window,
 8478        cx: &mut Context<Self>,
 8479    ) -> bool {
 8480        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8481    }
 8482
 8483    pub fn move_to_prev_snippet_tabstop(
 8484        &mut self,
 8485        window: &mut Window,
 8486        cx: &mut Context<Self>,
 8487    ) -> bool {
 8488        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8489    }
 8490
 8491    pub fn move_to_snippet_tabstop(
 8492        &mut self,
 8493        bias: Bias,
 8494        window: &mut Window,
 8495        cx: &mut Context<Self>,
 8496    ) -> bool {
 8497        if let Some(mut snippet) = self.snippet_stack.pop() {
 8498            match bias {
 8499                Bias::Left => {
 8500                    if snippet.active_index > 0 {
 8501                        snippet.active_index -= 1;
 8502                    } else {
 8503                        self.snippet_stack.push(snippet);
 8504                        return false;
 8505                    }
 8506                }
 8507                Bias::Right => {
 8508                    if snippet.active_index + 1 < snippet.ranges.len() {
 8509                        snippet.active_index += 1;
 8510                    } else {
 8511                        self.snippet_stack.push(snippet);
 8512                        return false;
 8513                    }
 8514                }
 8515            }
 8516            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8517                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8518                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8519                });
 8520
 8521                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8522                    if let Some(selection) = current_ranges.first() {
 8523                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8524                    }
 8525                }
 8526
 8527                // If snippet state is not at the last tabstop, push it back on the stack
 8528                if snippet.active_index + 1 < snippet.ranges.len() {
 8529                    self.snippet_stack.push(snippet);
 8530                }
 8531                return true;
 8532            }
 8533        }
 8534
 8535        false
 8536    }
 8537
 8538    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8539        self.transact(window, cx, |this, window, cx| {
 8540            this.select_all(&SelectAll, window, cx);
 8541            this.insert("", window, cx);
 8542        });
 8543    }
 8544
 8545    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8546        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8547        self.transact(window, cx, |this, window, cx| {
 8548            this.select_autoclose_pair(window, cx);
 8549            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8550            if !this.linked_edit_ranges.is_empty() {
 8551                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8552                let snapshot = this.buffer.read(cx).snapshot(cx);
 8553
 8554                for selection in selections.iter() {
 8555                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8556                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8557                    if selection_start.buffer_id != selection_end.buffer_id {
 8558                        continue;
 8559                    }
 8560                    if let Some(ranges) =
 8561                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8562                    {
 8563                        for (buffer, entries) in ranges {
 8564                            linked_ranges.entry(buffer).or_default().extend(entries);
 8565                        }
 8566                    }
 8567                }
 8568            }
 8569
 8570            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8571            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8572            for selection in &mut selections {
 8573                if selection.is_empty() {
 8574                    let old_head = selection.head();
 8575                    let mut new_head =
 8576                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8577                            .to_point(&display_map);
 8578                    if let Some((buffer, line_buffer_range)) = display_map
 8579                        .buffer_snapshot
 8580                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8581                    {
 8582                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8583                        let indent_len = match indent_size.kind {
 8584                            IndentKind::Space => {
 8585                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8586                            }
 8587                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8588                        };
 8589                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8590                            let indent_len = indent_len.get();
 8591                            new_head = cmp::min(
 8592                                new_head,
 8593                                MultiBufferPoint::new(
 8594                                    old_head.row,
 8595                                    ((old_head.column - 1) / indent_len) * indent_len,
 8596                                ),
 8597                            );
 8598                        }
 8599                    }
 8600
 8601                    selection.set_head(new_head, SelectionGoal::None);
 8602                }
 8603            }
 8604
 8605            this.signature_help_state.set_backspace_pressed(true);
 8606            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8607                s.select(selections)
 8608            });
 8609            this.insert("", window, cx);
 8610            let empty_str: Arc<str> = Arc::from("");
 8611            for (buffer, edits) in linked_ranges {
 8612                let snapshot = buffer.read(cx).snapshot();
 8613                use text::ToPoint as TP;
 8614
 8615                let edits = edits
 8616                    .into_iter()
 8617                    .map(|range| {
 8618                        let end_point = TP::to_point(&range.end, &snapshot);
 8619                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8620
 8621                        if end_point == start_point {
 8622                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8623                                .saturating_sub(1);
 8624                            start_point =
 8625                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8626                        };
 8627
 8628                        (start_point..end_point, empty_str.clone())
 8629                    })
 8630                    .sorted_by_key(|(range, _)| range.start)
 8631                    .collect::<Vec<_>>();
 8632                buffer.update(cx, |this, cx| {
 8633                    this.edit(edits, None, cx);
 8634                })
 8635            }
 8636            this.refresh_inline_completion(true, false, window, cx);
 8637            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8638        });
 8639    }
 8640
 8641    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8642        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8643        self.transact(window, cx, |this, window, cx| {
 8644            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8645                s.move_with(|map, selection| {
 8646                    if selection.is_empty() {
 8647                        let cursor = movement::right(map, selection.head());
 8648                        selection.end = cursor;
 8649                        selection.reversed = true;
 8650                        selection.goal = SelectionGoal::None;
 8651                    }
 8652                })
 8653            });
 8654            this.insert("", window, cx);
 8655            this.refresh_inline_completion(true, false, window, cx);
 8656        });
 8657    }
 8658
 8659    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8660        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8661        if self.move_to_prev_snippet_tabstop(window, cx) {
 8662            return;
 8663        }
 8664        self.outdent(&Outdent, window, cx);
 8665    }
 8666
 8667    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8668        if self.move_to_next_snippet_tabstop(window, cx) {
 8669            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8670            return;
 8671        }
 8672        if self.read_only(cx) {
 8673            return;
 8674        }
 8675        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8676        let mut selections = self.selections.all_adjusted(cx);
 8677        let buffer = self.buffer.read(cx);
 8678        let snapshot = buffer.snapshot(cx);
 8679        let rows_iter = selections.iter().map(|s| s.head().row);
 8680        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8681
 8682        let has_some_cursor_in_whitespace = selections
 8683            .iter()
 8684            .filter(|selection| selection.is_empty())
 8685            .any(|selection| {
 8686                let cursor = selection.head();
 8687                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8688                cursor.column < current_indent.len
 8689            });
 8690
 8691        let mut edits = Vec::new();
 8692        let mut prev_edited_row = 0;
 8693        let mut row_delta = 0;
 8694        for selection in &mut selections {
 8695            if selection.start.row != prev_edited_row {
 8696                row_delta = 0;
 8697            }
 8698            prev_edited_row = selection.end.row;
 8699
 8700            // If the selection is non-empty, then increase the indentation of the selected lines.
 8701            if !selection.is_empty() {
 8702                row_delta =
 8703                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8704                continue;
 8705            }
 8706
 8707            // If the selection is empty and the cursor is in the leading whitespace before the
 8708            // suggested indentation, then auto-indent the line.
 8709            let cursor = selection.head();
 8710            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8711            if let Some(suggested_indent) =
 8712                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8713            {
 8714                // If there exist any empty selection in the leading whitespace, then skip
 8715                // indent for selections at the boundary.
 8716                if has_some_cursor_in_whitespace
 8717                    && cursor.column == current_indent.len
 8718                    && current_indent.len == suggested_indent.len
 8719                {
 8720                    continue;
 8721                }
 8722
 8723                if cursor.column < suggested_indent.len
 8724                    && cursor.column <= current_indent.len
 8725                    && current_indent.len <= suggested_indent.len
 8726                {
 8727                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8728                    selection.end = selection.start;
 8729                    if row_delta == 0 {
 8730                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8731                            cursor.row,
 8732                            current_indent,
 8733                            suggested_indent,
 8734                        ));
 8735                        row_delta = suggested_indent.len - current_indent.len;
 8736                    }
 8737                    continue;
 8738                }
 8739            }
 8740
 8741            // Otherwise, insert a hard or soft tab.
 8742            let settings = buffer.language_settings_at(cursor, cx);
 8743            let tab_size = if settings.hard_tabs {
 8744                IndentSize::tab()
 8745            } else {
 8746                let tab_size = settings.tab_size.get();
 8747                let indent_remainder = snapshot
 8748                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8749                    .flat_map(str::chars)
 8750                    .fold(row_delta % tab_size, |counter: u32, c| {
 8751                        if c == '\t' {
 8752                            0
 8753                        } else {
 8754                            (counter + 1) % tab_size
 8755                        }
 8756                    });
 8757
 8758                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8759                IndentSize::spaces(chars_to_next_tab_stop)
 8760            };
 8761            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8762            selection.end = selection.start;
 8763            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8764            row_delta += tab_size.len;
 8765        }
 8766
 8767        self.transact(window, cx, |this, window, cx| {
 8768            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8769            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8770                s.select(selections)
 8771            });
 8772            this.refresh_inline_completion(true, false, window, cx);
 8773        });
 8774    }
 8775
 8776    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8777        if self.read_only(cx) {
 8778            return;
 8779        }
 8780        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8781        let mut selections = self.selections.all::<Point>(cx);
 8782        let mut prev_edited_row = 0;
 8783        let mut row_delta = 0;
 8784        let mut edits = Vec::new();
 8785        let buffer = self.buffer.read(cx);
 8786        let snapshot = buffer.snapshot(cx);
 8787        for selection in &mut selections {
 8788            if selection.start.row != prev_edited_row {
 8789                row_delta = 0;
 8790            }
 8791            prev_edited_row = selection.end.row;
 8792
 8793            row_delta =
 8794                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8795        }
 8796
 8797        self.transact(window, cx, |this, window, cx| {
 8798            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8799            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8800                s.select(selections)
 8801            });
 8802        });
 8803    }
 8804
 8805    fn indent_selection(
 8806        buffer: &MultiBuffer,
 8807        snapshot: &MultiBufferSnapshot,
 8808        selection: &mut Selection<Point>,
 8809        edits: &mut Vec<(Range<Point>, String)>,
 8810        delta_for_start_row: u32,
 8811        cx: &App,
 8812    ) -> u32 {
 8813        let settings = buffer.language_settings_at(selection.start, cx);
 8814        let tab_size = settings.tab_size.get();
 8815        let indent_kind = if settings.hard_tabs {
 8816            IndentKind::Tab
 8817        } else {
 8818            IndentKind::Space
 8819        };
 8820        let mut start_row = selection.start.row;
 8821        let mut end_row = selection.end.row + 1;
 8822
 8823        // If a selection ends at the beginning of a line, don't indent
 8824        // that last line.
 8825        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8826            end_row -= 1;
 8827        }
 8828
 8829        // Avoid re-indenting a row that has already been indented by a
 8830        // previous selection, but still update this selection's column
 8831        // to reflect that indentation.
 8832        if delta_for_start_row > 0 {
 8833            start_row += 1;
 8834            selection.start.column += delta_for_start_row;
 8835            if selection.end.row == selection.start.row {
 8836                selection.end.column += delta_for_start_row;
 8837            }
 8838        }
 8839
 8840        let mut delta_for_end_row = 0;
 8841        let has_multiple_rows = start_row + 1 != end_row;
 8842        for row in start_row..end_row {
 8843            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8844            let indent_delta = match (current_indent.kind, indent_kind) {
 8845                (IndentKind::Space, IndentKind::Space) => {
 8846                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8847                    IndentSize::spaces(columns_to_next_tab_stop)
 8848                }
 8849                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8850                (_, IndentKind::Tab) => IndentSize::tab(),
 8851            };
 8852
 8853            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8854                0
 8855            } else {
 8856                selection.start.column
 8857            };
 8858            let row_start = Point::new(row, start);
 8859            edits.push((
 8860                row_start..row_start,
 8861                indent_delta.chars().collect::<String>(),
 8862            ));
 8863
 8864            // Update this selection's endpoints to reflect the indentation.
 8865            if row == selection.start.row {
 8866                selection.start.column += indent_delta.len;
 8867            }
 8868            if row == selection.end.row {
 8869                selection.end.column += indent_delta.len;
 8870                delta_for_end_row = indent_delta.len;
 8871            }
 8872        }
 8873
 8874        if selection.start.row == selection.end.row {
 8875            delta_for_start_row + delta_for_end_row
 8876        } else {
 8877            delta_for_end_row
 8878        }
 8879    }
 8880
 8881    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8882        if self.read_only(cx) {
 8883            return;
 8884        }
 8885        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8886        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8887        let selections = self.selections.all::<Point>(cx);
 8888        let mut deletion_ranges = Vec::new();
 8889        let mut last_outdent = None;
 8890        {
 8891            let buffer = self.buffer.read(cx);
 8892            let snapshot = buffer.snapshot(cx);
 8893            for selection in &selections {
 8894                let settings = buffer.language_settings_at(selection.start, cx);
 8895                let tab_size = settings.tab_size.get();
 8896                let mut rows = selection.spanned_rows(false, &display_map);
 8897
 8898                // Avoid re-outdenting a row that has already been outdented by a
 8899                // previous selection.
 8900                if let Some(last_row) = last_outdent {
 8901                    if last_row == rows.start {
 8902                        rows.start = rows.start.next_row();
 8903                    }
 8904                }
 8905                let has_multiple_rows = rows.len() > 1;
 8906                for row in rows.iter_rows() {
 8907                    let indent_size = snapshot.indent_size_for_line(row);
 8908                    if indent_size.len > 0 {
 8909                        let deletion_len = match indent_size.kind {
 8910                            IndentKind::Space => {
 8911                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8912                                if columns_to_prev_tab_stop == 0 {
 8913                                    tab_size
 8914                                } else {
 8915                                    columns_to_prev_tab_stop
 8916                                }
 8917                            }
 8918                            IndentKind::Tab => 1,
 8919                        };
 8920                        let start = if has_multiple_rows
 8921                            || deletion_len > selection.start.column
 8922                            || indent_size.len < selection.start.column
 8923                        {
 8924                            0
 8925                        } else {
 8926                            selection.start.column - deletion_len
 8927                        };
 8928                        deletion_ranges.push(
 8929                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8930                        );
 8931                        last_outdent = Some(row);
 8932                    }
 8933                }
 8934            }
 8935        }
 8936
 8937        self.transact(window, cx, |this, window, cx| {
 8938            this.buffer.update(cx, |buffer, cx| {
 8939                let empty_str: Arc<str> = Arc::default();
 8940                buffer.edit(
 8941                    deletion_ranges
 8942                        .into_iter()
 8943                        .map(|range| (range, empty_str.clone())),
 8944                    None,
 8945                    cx,
 8946                );
 8947            });
 8948            let selections = this.selections.all::<usize>(cx);
 8949            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8950                s.select(selections)
 8951            });
 8952        });
 8953    }
 8954
 8955    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8956        if self.read_only(cx) {
 8957            return;
 8958        }
 8959        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8960        let selections = self
 8961            .selections
 8962            .all::<usize>(cx)
 8963            .into_iter()
 8964            .map(|s| s.range());
 8965
 8966        self.transact(window, cx, |this, window, cx| {
 8967            this.buffer.update(cx, |buffer, cx| {
 8968                buffer.autoindent_ranges(selections, cx);
 8969            });
 8970            let selections = this.selections.all::<usize>(cx);
 8971            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8972                s.select(selections)
 8973            });
 8974        });
 8975    }
 8976
 8977    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8978        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8979        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8980        let selections = self.selections.all::<Point>(cx);
 8981
 8982        let mut new_cursors = Vec::new();
 8983        let mut edit_ranges = Vec::new();
 8984        let mut selections = selections.iter().peekable();
 8985        while let Some(selection) = selections.next() {
 8986            let mut rows = selection.spanned_rows(false, &display_map);
 8987            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8988
 8989            // Accumulate contiguous regions of rows that we want to delete.
 8990            while let Some(next_selection) = selections.peek() {
 8991                let next_rows = next_selection.spanned_rows(false, &display_map);
 8992                if next_rows.start <= rows.end {
 8993                    rows.end = next_rows.end;
 8994                    selections.next().unwrap();
 8995                } else {
 8996                    break;
 8997                }
 8998            }
 8999
 9000            let buffer = &display_map.buffer_snapshot;
 9001            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 9002            let edit_end;
 9003            let cursor_buffer_row;
 9004            if buffer.max_point().row >= rows.end.0 {
 9005                // If there's a line after the range, delete the \n from the end of the row range
 9006                // and position the cursor on the next line.
 9007                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 9008                cursor_buffer_row = rows.end;
 9009            } else {
 9010                // If there isn't a line after the range, delete the \n from the line before the
 9011                // start of the row range and position the cursor there.
 9012                edit_start = edit_start.saturating_sub(1);
 9013                edit_end = buffer.len();
 9014                cursor_buffer_row = rows.start.previous_row();
 9015            }
 9016
 9017            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 9018            *cursor.column_mut() =
 9019                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 9020
 9021            new_cursors.push((
 9022                selection.id,
 9023                buffer.anchor_after(cursor.to_point(&display_map)),
 9024            ));
 9025            edit_ranges.push(edit_start..edit_end);
 9026        }
 9027
 9028        self.transact(window, cx, |this, window, cx| {
 9029            let buffer = this.buffer.update(cx, |buffer, cx| {
 9030                let empty_str: Arc<str> = Arc::default();
 9031                buffer.edit(
 9032                    edit_ranges
 9033                        .into_iter()
 9034                        .map(|range| (range, empty_str.clone())),
 9035                    None,
 9036                    cx,
 9037                );
 9038                buffer.snapshot(cx)
 9039            });
 9040            let new_selections = new_cursors
 9041                .into_iter()
 9042                .map(|(id, cursor)| {
 9043                    let cursor = cursor.to_point(&buffer);
 9044                    Selection {
 9045                        id,
 9046                        start: cursor,
 9047                        end: cursor,
 9048                        reversed: false,
 9049                        goal: SelectionGoal::None,
 9050                    }
 9051                })
 9052                .collect();
 9053
 9054            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9055                s.select(new_selections);
 9056            });
 9057        });
 9058    }
 9059
 9060    pub fn join_lines_impl(
 9061        &mut self,
 9062        insert_whitespace: bool,
 9063        window: &mut Window,
 9064        cx: &mut Context<Self>,
 9065    ) {
 9066        if self.read_only(cx) {
 9067            return;
 9068        }
 9069        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9070        for selection in self.selections.all::<Point>(cx) {
 9071            let start = MultiBufferRow(selection.start.row);
 9072            // Treat single line selections as if they include the next line. Otherwise this action
 9073            // would do nothing for single line selections individual cursors.
 9074            let end = if selection.start.row == selection.end.row {
 9075                MultiBufferRow(selection.start.row + 1)
 9076            } else {
 9077                MultiBufferRow(selection.end.row)
 9078            };
 9079
 9080            if let Some(last_row_range) = row_ranges.last_mut() {
 9081                if start <= last_row_range.end {
 9082                    last_row_range.end = end;
 9083                    continue;
 9084                }
 9085            }
 9086            row_ranges.push(start..end);
 9087        }
 9088
 9089        let snapshot = self.buffer.read(cx).snapshot(cx);
 9090        let mut cursor_positions = Vec::new();
 9091        for row_range in &row_ranges {
 9092            let anchor = snapshot.anchor_before(Point::new(
 9093                row_range.end.previous_row().0,
 9094                snapshot.line_len(row_range.end.previous_row()),
 9095            ));
 9096            cursor_positions.push(anchor..anchor);
 9097        }
 9098
 9099        self.transact(window, cx, |this, window, cx| {
 9100            for row_range in row_ranges.into_iter().rev() {
 9101                for row in row_range.iter_rows().rev() {
 9102                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9103                    let next_line_row = row.next_row();
 9104                    let indent = snapshot.indent_size_for_line(next_line_row);
 9105                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9106
 9107                    let replace =
 9108                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9109                            " "
 9110                        } else {
 9111                            ""
 9112                        };
 9113
 9114                    this.buffer.update(cx, |buffer, cx| {
 9115                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9116                    });
 9117                }
 9118            }
 9119
 9120            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9121                s.select_anchor_ranges(cursor_positions)
 9122            });
 9123        });
 9124    }
 9125
 9126    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9127        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9128        self.join_lines_impl(true, window, cx);
 9129    }
 9130
 9131    pub fn sort_lines_case_sensitive(
 9132        &mut self,
 9133        _: &SortLinesCaseSensitive,
 9134        window: &mut Window,
 9135        cx: &mut Context<Self>,
 9136    ) {
 9137        self.manipulate_lines(window, cx, |lines| lines.sort())
 9138    }
 9139
 9140    pub fn sort_lines_case_insensitive(
 9141        &mut self,
 9142        _: &SortLinesCaseInsensitive,
 9143        window: &mut Window,
 9144        cx: &mut Context<Self>,
 9145    ) {
 9146        self.manipulate_lines(window, cx, |lines| {
 9147            lines.sort_by_key(|line| line.to_lowercase())
 9148        })
 9149    }
 9150
 9151    pub fn unique_lines_case_insensitive(
 9152        &mut self,
 9153        _: &UniqueLinesCaseInsensitive,
 9154        window: &mut Window,
 9155        cx: &mut Context<Self>,
 9156    ) {
 9157        self.manipulate_lines(window, cx, |lines| {
 9158            let mut seen = HashSet::default();
 9159            lines.retain(|line| seen.insert(line.to_lowercase()));
 9160        })
 9161    }
 9162
 9163    pub fn unique_lines_case_sensitive(
 9164        &mut self,
 9165        _: &UniqueLinesCaseSensitive,
 9166        window: &mut Window,
 9167        cx: &mut Context<Self>,
 9168    ) {
 9169        self.manipulate_lines(window, cx, |lines| {
 9170            let mut seen = HashSet::default();
 9171            lines.retain(|line| seen.insert(*line));
 9172        })
 9173    }
 9174
 9175    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9176        let Some(project) = self.project.clone() else {
 9177            return;
 9178        };
 9179        self.reload(project, window, cx)
 9180            .detach_and_notify_err(window, cx);
 9181    }
 9182
 9183    pub fn restore_file(
 9184        &mut self,
 9185        _: &::git::RestoreFile,
 9186        window: &mut Window,
 9187        cx: &mut Context<Self>,
 9188    ) {
 9189        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9190        let mut buffer_ids = HashSet::default();
 9191        let snapshot = self.buffer().read(cx).snapshot(cx);
 9192        for selection in self.selections.all::<usize>(cx) {
 9193            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9194        }
 9195
 9196        let buffer = self.buffer().read(cx);
 9197        let ranges = buffer_ids
 9198            .into_iter()
 9199            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9200            .collect::<Vec<_>>();
 9201
 9202        self.restore_hunks_in_ranges(ranges, window, cx);
 9203    }
 9204
 9205    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9206        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9207        let selections = self
 9208            .selections
 9209            .all(cx)
 9210            .into_iter()
 9211            .map(|s| s.range())
 9212            .collect();
 9213        self.restore_hunks_in_ranges(selections, window, cx);
 9214    }
 9215
 9216    pub fn restore_hunks_in_ranges(
 9217        &mut self,
 9218        ranges: Vec<Range<Point>>,
 9219        window: &mut Window,
 9220        cx: &mut Context<Editor>,
 9221    ) {
 9222        let mut revert_changes = HashMap::default();
 9223        let chunk_by = self
 9224            .snapshot(window, cx)
 9225            .hunks_for_ranges(ranges)
 9226            .into_iter()
 9227            .chunk_by(|hunk| hunk.buffer_id);
 9228        for (buffer_id, hunks) in &chunk_by {
 9229            let hunks = hunks.collect::<Vec<_>>();
 9230            for hunk in &hunks {
 9231                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9232            }
 9233            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9234        }
 9235        drop(chunk_by);
 9236        if !revert_changes.is_empty() {
 9237            self.transact(window, cx, |editor, window, cx| {
 9238                editor.restore(revert_changes, window, cx);
 9239            });
 9240        }
 9241    }
 9242
 9243    pub fn open_active_item_in_terminal(
 9244        &mut self,
 9245        _: &OpenInTerminal,
 9246        window: &mut Window,
 9247        cx: &mut Context<Self>,
 9248    ) {
 9249        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9250            let project_path = buffer.read(cx).project_path(cx)?;
 9251            let project = self.project.as_ref()?.read(cx);
 9252            let entry = project.entry_for_path(&project_path, cx)?;
 9253            let parent = match &entry.canonical_path {
 9254                Some(canonical_path) => canonical_path.to_path_buf(),
 9255                None => project.absolute_path(&project_path, cx)?,
 9256            }
 9257            .parent()?
 9258            .to_path_buf();
 9259            Some(parent)
 9260        }) {
 9261            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9262        }
 9263    }
 9264
 9265    fn set_breakpoint_context_menu(
 9266        &mut self,
 9267        display_row: DisplayRow,
 9268        position: Option<Anchor>,
 9269        clicked_point: gpui::Point<Pixels>,
 9270        window: &mut Window,
 9271        cx: &mut Context<Self>,
 9272    ) {
 9273        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9274            return;
 9275        }
 9276        let source = self
 9277            .buffer
 9278            .read(cx)
 9279            .snapshot(cx)
 9280            .anchor_before(Point::new(display_row.0, 0u32));
 9281
 9282        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9283
 9284        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9285            self,
 9286            source,
 9287            clicked_point,
 9288            context_menu,
 9289            window,
 9290            cx,
 9291        );
 9292    }
 9293
 9294    fn add_edit_breakpoint_block(
 9295        &mut self,
 9296        anchor: Anchor,
 9297        breakpoint: &Breakpoint,
 9298        edit_action: BreakpointPromptEditAction,
 9299        window: &mut Window,
 9300        cx: &mut Context<Self>,
 9301    ) {
 9302        let weak_editor = cx.weak_entity();
 9303        let bp_prompt = cx.new(|cx| {
 9304            BreakpointPromptEditor::new(
 9305                weak_editor,
 9306                anchor,
 9307                breakpoint.clone(),
 9308                edit_action,
 9309                window,
 9310                cx,
 9311            )
 9312        });
 9313
 9314        let height = bp_prompt.update(cx, |this, cx| {
 9315            this.prompt
 9316                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9317        });
 9318        let cloned_prompt = bp_prompt.clone();
 9319        let blocks = vec![BlockProperties {
 9320            style: BlockStyle::Sticky,
 9321            placement: BlockPlacement::Above(anchor),
 9322            height: Some(height),
 9323            render: Arc::new(move |cx| {
 9324                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9325                cloned_prompt.clone().into_any_element()
 9326            }),
 9327            priority: 0,
 9328        }];
 9329
 9330        let focus_handle = bp_prompt.focus_handle(cx);
 9331        window.focus(&focus_handle);
 9332
 9333        let block_ids = self.insert_blocks(blocks, None, cx);
 9334        bp_prompt.update(cx, |prompt, _| {
 9335            prompt.add_block_ids(block_ids);
 9336        });
 9337    }
 9338
 9339    pub(crate) fn breakpoint_at_row(
 9340        &self,
 9341        row: u32,
 9342        window: &mut Window,
 9343        cx: &mut Context<Self>,
 9344    ) -> Option<(Anchor, Breakpoint)> {
 9345        let snapshot = self.snapshot(window, cx);
 9346        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9347
 9348        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9349    }
 9350
 9351    pub(crate) fn breakpoint_at_anchor(
 9352        &self,
 9353        breakpoint_position: Anchor,
 9354        snapshot: &EditorSnapshot,
 9355        cx: &mut Context<Self>,
 9356    ) -> Option<(Anchor, Breakpoint)> {
 9357        let project = self.project.clone()?;
 9358
 9359        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9360            snapshot
 9361                .buffer_snapshot
 9362                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9363        })?;
 9364
 9365        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9366        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9367        let buffer_snapshot = buffer.read(cx).snapshot();
 9368
 9369        let row = buffer_snapshot
 9370            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9371            .row;
 9372
 9373        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9374        let anchor_end = snapshot
 9375            .buffer_snapshot
 9376            .anchor_after(Point::new(row, line_len));
 9377
 9378        let bp = self
 9379            .breakpoint_store
 9380            .as_ref()?
 9381            .read_with(cx, |breakpoint_store, cx| {
 9382                breakpoint_store
 9383                    .breakpoints(
 9384                        &buffer,
 9385                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9386                        &buffer_snapshot,
 9387                        cx,
 9388                    )
 9389                    .next()
 9390                    .and_then(|(anchor, bp)| {
 9391                        let breakpoint_row = buffer_snapshot
 9392                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9393                            .row;
 9394
 9395                        if breakpoint_row == row {
 9396                            snapshot
 9397                                .buffer_snapshot
 9398                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9399                                .map(|anchor| (anchor, bp.clone()))
 9400                        } else {
 9401                            None
 9402                        }
 9403                    })
 9404            });
 9405        bp
 9406    }
 9407
 9408    pub fn edit_log_breakpoint(
 9409        &mut self,
 9410        _: &EditLogBreakpoint,
 9411        window: &mut Window,
 9412        cx: &mut Context<Self>,
 9413    ) {
 9414        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9415            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9416                message: None,
 9417                state: BreakpointState::Enabled,
 9418                condition: None,
 9419                hit_condition: None,
 9420            });
 9421
 9422            self.add_edit_breakpoint_block(
 9423                anchor,
 9424                &breakpoint,
 9425                BreakpointPromptEditAction::Log,
 9426                window,
 9427                cx,
 9428            );
 9429        }
 9430    }
 9431
 9432    fn breakpoints_at_cursors(
 9433        &self,
 9434        window: &mut Window,
 9435        cx: &mut Context<Self>,
 9436    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9437        let snapshot = self.snapshot(window, cx);
 9438        let cursors = self
 9439            .selections
 9440            .disjoint_anchors()
 9441            .into_iter()
 9442            .map(|selection| {
 9443                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9444
 9445                let breakpoint_position = self
 9446                    .breakpoint_at_row(cursor_position.row, window, cx)
 9447                    .map(|bp| bp.0)
 9448                    .unwrap_or_else(|| {
 9449                        snapshot
 9450                            .display_snapshot
 9451                            .buffer_snapshot
 9452                            .anchor_after(Point::new(cursor_position.row, 0))
 9453                    });
 9454
 9455                let breakpoint = self
 9456                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9457                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9458
 9459                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9460            })
 9461            // 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.
 9462            .collect::<HashMap<Anchor, _>>();
 9463
 9464        cursors.into_iter().collect()
 9465    }
 9466
 9467    pub fn enable_breakpoint(
 9468        &mut self,
 9469        _: &crate::actions::EnableBreakpoint,
 9470        window: &mut Window,
 9471        cx: &mut Context<Self>,
 9472    ) {
 9473        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9474            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9475                continue;
 9476            };
 9477            self.edit_breakpoint_at_anchor(
 9478                anchor,
 9479                breakpoint,
 9480                BreakpointEditAction::InvertState,
 9481                cx,
 9482            );
 9483        }
 9484    }
 9485
 9486    pub fn disable_breakpoint(
 9487        &mut self,
 9488        _: &crate::actions::DisableBreakpoint,
 9489        window: &mut Window,
 9490        cx: &mut Context<Self>,
 9491    ) {
 9492        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9493            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9494                continue;
 9495            };
 9496            self.edit_breakpoint_at_anchor(
 9497                anchor,
 9498                breakpoint,
 9499                BreakpointEditAction::InvertState,
 9500                cx,
 9501            );
 9502        }
 9503    }
 9504
 9505    pub fn toggle_breakpoint(
 9506        &mut self,
 9507        _: &crate::actions::ToggleBreakpoint,
 9508        window: &mut Window,
 9509        cx: &mut Context<Self>,
 9510    ) {
 9511        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9512            if let Some(breakpoint) = breakpoint {
 9513                self.edit_breakpoint_at_anchor(
 9514                    anchor,
 9515                    breakpoint,
 9516                    BreakpointEditAction::Toggle,
 9517                    cx,
 9518                );
 9519            } else {
 9520                self.edit_breakpoint_at_anchor(
 9521                    anchor,
 9522                    Breakpoint::new_standard(),
 9523                    BreakpointEditAction::Toggle,
 9524                    cx,
 9525                );
 9526            }
 9527        }
 9528    }
 9529
 9530    pub fn edit_breakpoint_at_anchor(
 9531        &mut self,
 9532        breakpoint_position: Anchor,
 9533        breakpoint: Breakpoint,
 9534        edit_action: BreakpointEditAction,
 9535        cx: &mut Context<Self>,
 9536    ) {
 9537        let Some(breakpoint_store) = &self.breakpoint_store else {
 9538            return;
 9539        };
 9540
 9541        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9542            if breakpoint_position == Anchor::min() {
 9543                self.buffer()
 9544                    .read(cx)
 9545                    .excerpt_buffer_ids()
 9546                    .into_iter()
 9547                    .next()
 9548            } else {
 9549                None
 9550            }
 9551        }) else {
 9552            return;
 9553        };
 9554
 9555        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9556            return;
 9557        };
 9558
 9559        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9560            breakpoint_store.toggle_breakpoint(
 9561                buffer,
 9562                (breakpoint_position.text_anchor, breakpoint),
 9563                edit_action,
 9564                cx,
 9565            );
 9566        });
 9567
 9568        cx.notify();
 9569    }
 9570
 9571    #[cfg(any(test, feature = "test-support"))]
 9572    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9573        self.breakpoint_store.clone()
 9574    }
 9575
 9576    pub fn prepare_restore_change(
 9577        &self,
 9578        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9579        hunk: &MultiBufferDiffHunk,
 9580        cx: &mut App,
 9581    ) -> Option<()> {
 9582        if hunk.is_created_file() {
 9583            return None;
 9584        }
 9585        let buffer = self.buffer.read(cx);
 9586        let diff = buffer.diff_for(hunk.buffer_id)?;
 9587        let buffer = buffer.buffer(hunk.buffer_id)?;
 9588        let buffer = buffer.read(cx);
 9589        let original_text = diff
 9590            .read(cx)
 9591            .base_text()
 9592            .as_rope()
 9593            .slice(hunk.diff_base_byte_range.clone());
 9594        let buffer_snapshot = buffer.snapshot();
 9595        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9596        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9597            probe
 9598                .0
 9599                .start
 9600                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9601                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9602        }) {
 9603            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9604            Some(())
 9605        } else {
 9606            None
 9607        }
 9608    }
 9609
 9610    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9611        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9612    }
 9613
 9614    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9615        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9616    }
 9617
 9618    fn manipulate_lines<Fn>(
 9619        &mut self,
 9620        window: &mut Window,
 9621        cx: &mut Context<Self>,
 9622        mut callback: Fn,
 9623    ) where
 9624        Fn: FnMut(&mut Vec<&str>),
 9625    {
 9626        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9627
 9628        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9629        let buffer = self.buffer.read(cx).snapshot(cx);
 9630
 9631        let mut edits = Vec::new();
 9632
 9633        let selections = self.selections.all::<Point>(cx);
 9634        let mut selections = selections.iter().peekable();
 9635        let mut contiguous_row_selections = Vec::new();
 9636        let mut new_selections = Vec::new();
 9637        let mut added_lines = 0;
 9638        let mut removed_lines = 0;
 9639
 9640        while let Some(selection) = selections.next() {
 9641            let (start_row, end_row) = consume_contiguous_rows(
 9642                &mut contiguous_row_selections,
 9643                selection,
 9644                &display_map,
 9645                &mut selections,
 9646            );
 9647
 9648            let start_point = Point::new(start_row.0, 0);
 9649            let end_point = Point::new(
 9650                end_row.previous_row().0,
 9651                buffer.line_len(end_row.previous_row()),
 9652            );
 9653            let text = buffer
 9654                .text_for_range(start_point..end_point)
 9655                .collect::<String>();
 9656
 9657            let mut lines = text.split('\n').collect_vec();
 9658
 9659            let lines_before = lines.len();
 9660            callback(&mut lines);
 9661            let lines_after = lines.len();
 9662
 9663            edits.push((start_point..end_point, lines.join("\n")));
 9664
 9665            // Selections must change based on added and removed line count
 9666            let start_row =
 9667                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9668            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9669            new_selections.push(Selection {
 9670                id: selection.id,
 9671                start: start_row,
 9672                end: end_row,
 9673                goal: SelectionGoal::None,
 9674                reversed: selection.reversed,
 9675            });
 9676
 9677            if lines_after > lines_before {
 9678                added_lines += lines_after - lines_before;
 9679            } else if lines_before > lines_after {
 9680                removed_lines += lines_before - lines_after;
 9681            }
 9682        }
 9683
 9684        self.transact(window, cx, |this, window, cx| {
 9685            let buffer = this.buffer.update(cx, |buffer, cx| {
 9686                buffer.edit(edits, None, cx);
 9687                buffer.snapshot(cx)
 9688            });
 9689
 9690            // Recalculate offsets on newly edited buffer
 9691            let new_selections = new_selections
 9692                .iter()
 9693                .map(|s| {
 9694                    let start_point = Point::new(s.start.0, 0);
 9695                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9696                    Selection {
 9697                        id: s.id,
 9698                        start: buffer.point_to_offset(start_point),
 9699                        end: buffer.point_to_offset(end_point),
 9700                        goal: s.goal,
 9701                        reversed: s.reversed,
 9702                    }
 9703                })
 9704                .collect();
 9705
 9706            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9707                s.select(new_selections);
 9708            });
 9709
 9710            this.request_autoscroll(Autoscroll::fit(), cx);
 9711        });
 9712    }
 9713
 9714    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9715        self.manipulate_text(window, cx, |text| {
 9716            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9717            if has_upper_case_characters {
 9718                text.to_lowercase()
 9719            } else {
 9720                text.to_uppercase()
 9721            }
 9722        })
 9723    }
 9724
 9725    pub fn convert_to_upper_case(
 9726        &mut self,
 9727        _: &ConvertToUpperCase,
 9728        window: &mut Window,
 9729        cx: &mut Context<Self>,
 9730    ) {
 9731        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9732    }
 9733
 9734    pub fn convert_to_lower_case(
 9735        &mut self,
 9736        _: &ConvertToLowerCase,
 9737        window: &mut Window,
 9738        cx: &mut Context<Self>,
 9739    ) {
 9740        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9741    }
 9742
 9743    pub fn convert_to_title_case(
 9744        &mut self,
 9745        _: &ConvertToTitleCase,
 9746        window: &mut Window,
 9747        cx: &mut Context<Self>,
 9748    ) {
 9749        self.manipulate_text(window, cx, |text| {
 9750            text.split('\n')
 9751                .map(|line| line.to_case(Case::Title))
 9752                .join("\n")
 9753        })
 9754    }
 9755
 9756    pub fn convert_to_snake_case(
 9757        &mut self,
 9758        _: &ConvertToSnakeCase,
 9759        window: &mut Window,
 9760        cx: &mut Context<Self>,
 9761    ) {
 9762        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9763    }
 9764
 9765    pub fn convert_to_kebab_case(
 9766        &mut self,
 9767        _: &ConvertToKebabCase,
 9768        window: &mut Window,
 9769        cx: &mut Context<Self>,
 9770    ) {
 9771        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9772    }
 9773
 9774    pub fn convert_to_upper_camel_case(
 9775        &mut self,
 9776        _: &ConvertToUpperCamelCase,
 9777        window: &mut Window,
 9778        cx: &mut Context<Self>,
 9779    ) {
 9780        self.manipulate_text(window, cx, |text| {
 9781            text.split('\n')
 9782                .map(|line| line.to_case(Case::UpperCamel))
 9783                .join("\n")
 9784        })
 9785    }
 9786
 9787    pub fn convert_to_lower_camel_case(
 9788        &mut self,
 9789        _: &ConvertToLowerCamelCase,
 9790        window: &mut Window,
 9791        cx: &mut Context<Self>,
 9792    ) {
 9793        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9794    }
 9795
 9796    pub fn convert_to_opposite_case(
 9797        &mut self,
 9798        _: &ConvertToOppositeCase,
 9799        window: &mut Window,
 9800        cx: &mut Context<Self>,
 9801    ) {
 9802        self.manipulate_text(window, cx, |text| {
 9803            text.chars()
 9804                .fold(String::with_capacity(text.len()), |mut t, c| {
 9805                    if c.is_uppercase() {
 9806                        t.extend(c.to_lowercase());
 9807                    } else {
 9808                        t.extend(c.to_uppercase());
 9809                    }
 9810                    t
 9811                })
 9812        })
 9813    }
 9814
 9815    pub fn convert_to_rot13(
 9816        &mut self,
 9817        _: &ConvertToRot13,
 9818        window: &mut Window,
 9819        cx: &mut Context<Self>,
 9820    ) {
 9821        self.manipulate_text(window, cx, |text| {
 9822            text.chars()
 9823                .map(|c| match c {
 9824                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9825                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9826                    _ => c,
 9827                })
 9828                .collect()
 9829        })
 9830    }
 9831
 9832    pub fn convert_to_rot47(
 9833        &mut self,
 9834        _: &ConvertToRot47,
 9835        window: &mut Window,
 9836        cx: &mut Context<Self>,
 9837    ) {
 9838        self.manipulate_text(window, cx, |text| {
 9839            text.chars()
 9840                .map(|c| {
 9841                    let code_point = c as u32;
 9842                    if code_point >= 33 && code_point <= 126 {
 9843                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9844                    }
 9845                    c
 9846                })
 9847                .collect()
 9848        })
 9849    }
 9850
 9851    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9852    where
 9853        Fn: FnMut(&str) -> String,
 9854    {
 9855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9856        let buffer = self.buffer.read(cx).snapshot(cx);
 9857
 9858        let mut new_selections = Vec::new();
 9859        let mut edits = Vec::new();
 9860        let mut selection_adjustment = 0i32;
 9861
 9862        for selection in self.selections.all::<usize>(cx) {
 9863            let selection_is_empty = selection.is_empty();
 9864
 9865            let (start, end) = if selection_is_empty {
 9866                let word_range = movement::surrounding_word(
 9867                    &display_map,
 9868                    selection.start.to_display_point(&display_map),
 9869                );
 9870                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9871                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9872                (start, end)
 9873            } else {
 9874                (selection.start, selection.end)
 9875            };
 9876
 9877            let text = buffer.text_for_range(start..end).collect::<String>();
 9878            let old_length = text.len() as i32;
 9879            let text = callback(&text);
 9880
 9881            new_selections.push(Selection {
 9882                start: (start as i32 - selection_adjustment) as usize,
 9883                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9884                goal: SelectionGoal::None,
 9885                ..selection
 9886            });
 9887
 9888            selection_adjustment += old_length - text.len() as i32;
 9889
 9890            edits.push((start..end, text));
 9891        }
 9892
 9893        self.transact(window, cx, |this, window, cx| {
 9894            this.buffer.update(cx, |buffer, cx| {
 9895                buffer.edit(edits, None, cx);
 9896            });
 9897
 9898            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9899                s.select(new_selections);
 9900            });
 9901
 9902            this.request_autoscroll(Autoscroll::fit(), cx);
 9903        });
 9904    }
 9905
 9906    pub fn duplicate(
 9907        &mut self,
 9908        upwards: bool,
 9909        whole_lines: bool,
 9910        window: &mut Window,
 9911        cx: &mut Context<Self>,
 9912    ) {
 9913        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9914
 9915        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9916        let buffer = &display_map.buffer_snapshot;
 9917        let selections = self.selections.all::<Point>(cx);
 9918
 9919        let mut edits = Vec::new();
 9920        let mut selections_iter = selections.iter().peekable();
 9921        while let Some(selection) = selections_iter.next() {
 9922            let mut rows = selection.spanned_rows(false, &display_map);
 9923            // duplicate line-wise
 9924            if whole_lines || selection.start == selection.end {
 9925                // Avoid duplicating the same lines twice.
 9926                while let Some(next_selection) = selections_iter.peek() {
 9927                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9928                    if next_rows.start < rows.end {
 9929                        rows.end = next_rows.end;
 9930                        selections_iter.next().unwrap();
 9931                    } else {
 9932                        break;
 9933                    }
 9934                }
 9935
 9936                // Copy the text from the selected row region and splice it either at the start
 9937                // or end of the region.
 9938                let start = Point::new(rows.start.0, 0);
 9939                let end = Point::new(
 9940                    rows.end.previous_row().0,
 9941                    buffer.line_len(rows.end.previous_row()),
 9942                );
 9943                let text = buffer
 9944                    .text_for_range(start..end)
 9945                    .chain(Some("\n"))
 9946                    .collect::<String>();
 9947                let insert_location = if upwards {
 9948                    Point::new(rows.end.0, 0)
 9949                } else {
 9950                    start
 9951                };
 9952                edits.push((insert_location..insert_location, text));
 9953            } else {
 9954                // duplicate character-wise
 9955                let start = selection.start;
 9956                let end = selection.end;
 9957                let text = buffer.text_for_range(start..end).collect::<String>();
 9958                edits.push((selection.end..selection.end, text));
 9959            }
 9960        }
 9961
 9962        self.transact(window, cx, |this, _, cx| {
 9963            this.buffer.update(cx, |buffer, cx| {
 9964                buffer.edit(edits, None, cx);
 9965            });
 9966
 9967            this.request_autoscroll(Autoscroll::fit(), cx);
 9968        });
 9969    }
 9970
 9971    pub fn duplicate_line_up(
 9972        &mut self,
 9973        _: &DuplicateLineUp,
 9974        window: &mut Window,
 9975        cx: &mut Context<Self>,
 9976    ) {
 9977        self.duplicate(true, true, window, cx);
 9978    }
 9979
 9980    pub fn duplicate_line_down(
 9981        &mut self,
 9982        _: &DuplicateLineDown,
 9983        window: &mut Window,
 9984        cx: &mut Context<Self>,
 9985    ) {
 9986        self.duplicate(false, true, window, cx);
 9987    }
 9988
 9989    pub fn duplicate_selection(
 9990        &mut self,
 9991        _: &DuplicateSelection,
 9992        window: &mut Window,
 9993        cx: &mut Context<Self>,
 9994    ) {
 9995        self.duplicate(false, false, window, cx);
 9996    }
 9997
 9998    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9999        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10000
10001        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10002        let buffer = self.buffer.read(cx).snapshot(cx);
10003
10004        let mut edits = Vec::new();
10005        let mut unfold_ranges = Vec::new();
10006        let mut refold_creases = Vec::new();
10007
10008        let selections = self.selections.all::<Point>(cx);
10009        let mut selections = selections.iter().peekable();
10010        let mut contiguous_row_selections = Vec::new();
10011        let mut new_selections = Vec::new();
10012
10013        while let Some(selection) = selections.next() {
10014            // Find all the selections that span a contiguous row range
10015            let (start_row, end_row) = consume_contiguous_rows(
10016                &mut contiguous_row_selections,
10017                selection,
10018                &display_map,
10019                &mut selections,
10020            );
10021
10022            // Move the text spanned by the row range to be before the line preceding the row range
10023            if start_row.0 > 0 {
10024                let range_to_move = Point::new(
10025                    start_row.previous_row().0,
10026                    buffer.line_len(start_row.previous_row()),
10027                )
10028                    ..Point::new(
10029                        end_row.previous_row().0,
10030                        buffer.line_len(end_row.previous_row()),
10031                    );
10032                let insertion_point = display_map
10033                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10034                    .0;
10035
10036                // Don't move lines across excerpts
10037                if buffer
10038                    .excerpt_containing(insertion_point..range_to_move.end)
10039                    .is_some()
10040                {
10041                    let text = buffer
10042                        .text_for_range(range_to_move.clone())
10043                        .flat_map(|s| s.chars())
10044                        .skip(1)
10045                        .chain(['\n'])
10046                        .collect::<String>();
10047
10048                    edits.push((
10049                        buffer.anchor_after(range_to_move.start)
10050                            ..buffer.anchor_before(range_to_move.end),
10051                        String::new(),
10052                    ));
10053                    let insertion_anchor = buffer.anchor_after(insertion_point);
10054                    edits.push((insertion_anchor..insertion_anchor, text));
10055
10056                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10057
10058                    // Move selections up
10059                    new_selections.extend(contiguous_row_selections.drain(..).map(
10060                        |mut selection| {
10061                            selection.start.row -= row_delta;
10062                            selection.end.row -= row_delta;
10063                            selection
10064                        },
10065                    ));
10066
10067                    // Move folds up
10068                    unfold_ranges.push(range_to_move.clone());
10069                    for fold in display_map.folds_in_range(
10070                        buffer.anchor_before(range_to_move.start)
10071                            ..buffer.anchor_after(range_to_move.end),
10072                    ) {
10073                        let mut start = fold.range.start.to_point(&buffer);
10074                        let mut end = fold.range.end.to_point(&buffer);
10075                        start.row -= row_delta;
10076                        end.row -= row_delta;
10077                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10078                    }
10079                }
10080            }
10081
10082            // If we didn't move line(s), preserve the existing selections
10083            new_selections.append(&mut contiguous_row_selections);
10084        }
10085
10086        self.transact(window, cx, |this, window, cx| {
10087            this.unfold_ranges(&unfold_ranges, true, true, cx);
10088            this.buffer.update(cx, |buffer, cx| {
10089                for (range, text) in edits {
10090                    buffer.edit([(range, text)], None, cx);
10091                }
10092            });
10093            this.fold_creases(refold_creases, true, window, cx);
10094            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10095                s.select(new_selections);
10096            })
10097        });
10098    }
10099
10100    pub fn move_line_down(
10101        &mut self,
10102        _: &MoveLineDown,
10103        window: &mut Window,
10104        cx: &mut Context<Self>,
10105    ) {
10106        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10107
10108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10109        let buffer = self.buffer.read(cx).snapshot(cx);
10110
10111        let mut edits = Vec::new();
10112        let mut unfold_ranges = Vec::new();
10113        let mut refold_creases = Vec::new();
10114
10115        let selections = self.selections.all::<Point>(cx);
10116        let mut selections = selections.iter().peekable();
10117        let mut contiguous_row_selections = Vec::new();
10118        let mut new_selections = Vec::new();
10119
10120        while let Some(selection) = selections.next() {
10121            // Find all the selections that span a contiguous row range
10122            let (start_row, end_row) = consume_contiguous_rows(
10123                &mut contiguous_row_selections,
10124                selection,
10125                &display_map,
10126                &mut selections,
10127            );
10128
10129            // Move the text spanned by the row range to be after the last line of the row range
10130            if end_row.0 <= buffer.max_point().row {
10131                let range_to_move =
10132                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10133                let insertion_point = display_map
10134                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10135                    .0;
10136
10137                // Don't move lines across excerpt boundaries
10138                if buffer
10139                    .excerpt_containing(range_to_move.start..insertion_point)
10140                    .is_some()
10141                {
10142                    let mut text = String::from("\n");
10143                    text.extend(buffer.text_for_range(range_to_move.clone()));
10144                    text.pop(); // Drop trailing newline
10145                    edits.push((
10146                        buffer.anchor_after(range_to_move.start)
10147                            ..buffer.anchor_before(range_to_move.end),
10148                        String::new(),
10149                    ));
10150                    let insertion_anchor = buffer.anchor_after(insertion_point);
10151                    edits.push((insertion_anchor..insertion_anchor, text));
10152
10153                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10154
10155                    // Move selections down
10156                    new_selections.extend(contiguous_row_selections.drain(..).map(
10157                        |mut selection| {
10158                            selection.start.row += row_delta;
10159                            selection.end.row += row_delta;
10160                            selection
10161                        },
10162                    ));
10163
10164                    // Move folds down
10165                    unfold_ranges.push(range_to_move.clone());
10166                    for fold in display_map.folds_in_range(
10167                        buffer.anchor_before(range_to_move.start)
10168                            ..buffer.anchor_after(range_to_move.end),
10169                    ) {
10170                        let mut start = fold.range.start.to_point(&buffer);
10171                        let mut end = fold.range.end.to_point(&buffer);
10172                        start.row += row_delta;
10173                        end.row += row_delta;
10174                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10175                    }
10176                }
10177            }
10178
10179            // If we didn't move line(s), preserve the existing selections
10180            new_selections.append(&mut contiguous_row_selections);
10181        }
10182
10183        self.transact(window, cx, |this, window, cx| {
10184            this.unfold_ranges(&unfold_ranges, true, true, cx);
10185            this.buffer.update(cx, |buffer, cx| {
10186                for (range, text) in edits {
10187                    buffer.edit([(range, text)], None, cx);
10188                }
10189            });
10190            this.fold_creases(refold_creases, true, window, cx);
10191            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10192                s.select(new_selections)
10193            });
10194        });
10195    }
10196
10197    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10198        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10199        let text_layout_details = &self.text_layout_details(window);
10200        self.transact(window, cx, |this, window, cx| {
10201            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10202                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10203                s.move_with(|display_map, selection| {
10204                    if !selection.is_empty() {
10205                        return;
10206                    }
10207
10208                    let mut head = selection.head();
10209                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10210                    if head.column() == display_map.line_len(head.row()) {
10211                        transpose_offset = display_map
10212                            .buffer_snapshot
10213                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10214                    }
10215
10216                    if transpose_offset == 0 {
10217                        return;
10218                    }
10219
10220                    *head.column_mut() += 1;
10221                    head = display_map.clip_point(head, Bias::Right);
10222                    let goal = SelectionGoal::HorizontalPosition(
10223                        display_map
10224                            .x_for_display_point(head, text_layout_details)
10225                            .into(),
10226                    );
10227                    selection.collapse_to(head, goal);
10228
10229                    let transpose_start = display_map
10230                        .buffer_snapshot
10231                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10232                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10233                        let transpose_end = display_map
10234                            .buffer_snapshot
10235                            .clip_offset(transpose_offset + 1, Bias::Right);
10236                        if let Some(ch) =
10237                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10238                        {
10239                            edits.push((transpose_start..transpose_offset, String::new()));
10240                            edits.push((transpose_end..transpose_end, ch.to_string()));
10241                        }
10242                    }
10243                });
10244                edits
10245            });
10246            this.buffer
10247                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10248            let selections = this.selections.all::<usize>(cx);
10249            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10250                s.select(selections);
10251            });
10252        });
10253    }
10254
10255    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10256        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10257        self.rewrap_impl(RewrapOptions::default(), cx)
10258    }
10259
10260    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10261        let buffer = self.buffer.read(cx).snapshot(cx);
10262        let selections = self.selections.all::<Point>(cx);
10263        let mut selections = selections.iter().peekable();
10264
10265        let mut edits = Vec::new();
10266        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10267
10268        while let Some(selection) = selections.next() {
10269            let mut start_row = selection.start.row;
10270            let mut end_row = selection.end.row;
10271
10272            // Skip selections that overlap with a range that has already been rewrapped.
10273            let selection_range = start_row..end_row;
10274            if rewrapped_row_ranges
10275                .iter()
10276                .any(|range| range.overlaps(&selection_range))
10277            {
10278                continue;
10279            }
10280
10281            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10282
10283            // Since not all lines in the selection may be at the same indent
10284            // level, choose the indent size that is the most common between all
10285            // of the lines.
10286            //
10287            // If there is a tie, we use the deepest indent.
10288            let (indent_size, indent_end) = {
10289                let mut indent_size_occurrences = HashMap::default();
10290                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10291
10292                for row in start_row..=end_row {
10293                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10294                    rows_by_indent_size.entry(indent).or_default().push(row);
10295                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10296                }
10297
10298                let indent_size = indent_size_occurrences
10299                    .into_iter()
10300                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10301                    .map(|(indent, _)| indent)
10302                    .unwrap_or_default();
10303                let row = rows_by_indent_size[&indent_size][0];
10304                let indent_end = Point::new(row, indent_size.len);
10305
10306                (indent_size, indent_end)
10307            };
10308
10309            let mut line_prefix = indent_size.chars().collect::<String>();
10310
10311            let mut inside_comment = false;
10312            if let Some(comment_prefix) =
10313                buffer
10314                    .language_scope_at(selection.head())
10315                    .and_then(|language| {
10316                        language
10317                            .line_comment_prefixes()
10318                            .iter()
10319                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10320                            .cloned()
10321                    })
10322            {
10323                line_prefix.push_str(&comment_prefix);
10324                inside_comment = true;
10325            }
10326
10327            let language_settings = buffer.language_settings_at(selection.head(), cx);
10328            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10329                RewrapBehavior::InComments => inside_comment,
10330                RewrapBehavior::InSelections => !selection.is_empty(),
10331                RewrapBehavior::Anywhere => true,
10332            };
10333
10334            let should_rewrap = options.override_language_settings
10335                || allow_rewrap_based_on_language
10336                || self.hard_wrap.is_some();
10337            if !should_rewrap {
10338                continue;
10339            }
10340
10341            if selection.is_empty() {
10342                'expand_upwards: while start_row > 0 {
10343                    let prev_row = start_row - 1;
10344                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10345                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10346                    {
10347                        start_row = prev_row;
10348                    } else {
10349                        break 'expand_upwards;
10350                    }
10351                }
10352
10353                'expand_downwards: while end_row < buffer.max_point().row {
10354                    let next_row = end_row + 1;
10355                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10356                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10357                    {
10358                        end_row = next_row;
10359                    } else {
10360                        break 'expand_downwards;
10361                    }
10362                }
10363            }
10364
10365            let start = Point::new(start_row, 0);
10366            let start_offset = start.to_offset(&buffer);
10367            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10368            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10369            let Some(lines_without_prefixes) = selection_text
10370                .lines()
10371                .map(|line| {
10372                    line.strip_prefix(&line_prefix)
10373                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10374                        .ok_or_else(|| {
10375                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10376                        })
10377                })
10378                .collect::<Result<Vec<_>, _>>()
10379                .log_err()
10380            else {
10381                continue;
10382            };
10383
10384            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10385                buffer
10386                    .language_settings_at(Point::new(start_row, 0), cx)
10387                    .preferred_line_length as usize
10388            });
10389            let wrapped_text = wrap_with_prefix(
10390                line_prefix,
10391                lines_without_prefixes.join("\n"),
10392                wrap_column,
10393                tab_size,
10394                options.preserve_existing_whitespace,
10395            );
10396
10397            // TODO: should always use char-based diff while still supporting cursor behavior that
10398            // matches vim.
10399            let mut diff_options = DiffOptions::default();
10400            if options.override_language_settings {
10401                diff_options.max_word_diff_len = 0;
10402                diff_options.max_word_diff_line_count = 0;
10403            } else {
10404                diff_options.max_word_diff_len = usize::MAX;
10405                diff_options.max_word_diff_line_count = usize::MAX;
10406            }
10407
10408            for (old_range, new_text) in
10409                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10410            {
10411                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10412                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10413                edits.push((edit_start..edit_end, new_text));
10414            }
10415
10416            rewrapped_row_ranges.push(start_row..=end_row);
10417        }
10418
10419        self.buffer
10420            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10421    }
10422
10423    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10424        let mut text = String::new();
10425        let buffer = self.buffer.read(cx).snapshot(cx);
10426        let mut selections = self.selections.all::<Point>(cx);
10427        let mut clipboard_selections = Vec::with_capacity(selections.len());
10428        {
10429            let max_point = buffer.max_point();
10430            let mut is_first = true;
10431            for selection in &mut selections {
10432                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10433                if is_entire_line {
10434                    selection.start = Point::new(selection.start.row, 0);
10435                    if !selection.is_empty() && selection.end.column == 0 {
10436                        selection.end = cmp::min(max_point, selection.end);
10437                    } else {
10438                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10439                    }
10440                    selection.goal = SelectionGoal::None;
10441                }
10442                if is_first {
10443                    is_first = false;
10444                } else {
10445                    text += "\n";
10446                }
10447                let mut len = 0;
10448                for chunk in buffer.text_for_range(selection.start..selection.end) {
10449                    text.push_str(chunk);
10450                    len += chunk.len();
10451                }
10452                clipboard_selections.push(ClipboardSelection {
10453                    len,
10454                    is_entire_line,
10455                    first_line_indent: buffer
10456                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10457                        .len,
10458                });
10459            }
10460        }
10461
10462        self.transact(window, cx, |this, window, cx| {
10463            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464                s.select(selections);
10465            });
10466            this.insert("", window, cx);
10467        });
10468        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10469    }
10470
10471    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10472        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10473        let item = self.cut_common(window, cx);
10474        cx.write_to_clipboard(item);
10475    }
10476
10477    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10478        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10479        self.change_selections(None, window, cx, |s| {
10480            s.move_with(|snapshot, sel| {
10481                if sel.is_empty() {
10482                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10483                }
10484            });
10485        });
10486        let item = self.cut_common(window, cx);
10487        cx.set_global(KillRing(item))
10488    }
10489
10490    pub fn kill_ring_yank(
10491        &mut self,
10492        _: &KillRingYank,
10493        window: &mut Window,
10494        cx: &mut Context<Self>,
10495    ) {
10496        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10497        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10498            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10499                (kill_ring.text().to_string(), kill_ring.metadata_json())
10500            } else {
10501                return;
10502            }
10503        } else {
10504            return;
10505        };
10506        self.do_paste(&text, metadata, false, window, cx);
10507    }
10508
10509    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10510        self.do_copy(true, cx);
10511    }
10512
10513    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10514        self.do_copy(false, cx);
10515    }
10516
10517    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10518        let selections = self.selections.all::<Point>(cx);
10519        let buffer = self.buffer.read(cx).read(cx);
10520        let mut text = String::new();
10521
10522        let mut clipboard_selections = Vec::with_capacity(selections.len());
10523        {
10524            let max_point = buffer.max_point();
10525            let mut is_first = true;
10526            for selection in &selections {
10527                let mut start = selection.start;
10528                let mut end = selection.end;
10529                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10530                if is_entire_line {
10531                    start = Point::new(start.row, 0);
10532                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10533                }
10534
10535                let mut trimmed_selections = Vec::new();
10536                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10537                    let row = MultiBufferRow(start.row);
10538                    let first_indent = buffer.indent_size_for_line(row);
10539                    if first_indent.len == 0 || start.column > first_indent.len {
10540                        trimmed_selections.push(start..end);
10541                    } else {
10542                        trimmed_selections.push(
10543                            Point::new(row.0, first_indent.len)
10544                                ..Point::new(row.0, buffer.line_len(row)),
10545                        );
10546                        for row in start.row + 1..=end.row {
10547                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10548                            if row == end.row {
10549                                line_len = end.column;
10550                            }
10551                            if line_len == 0 {
10552                                trimmed_selections
10553                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10554                                continue;
10555                            }
10556                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10557                            if row_indent_size.len >= first_indent.len {
10558                                trimmed_selections.push(
10559                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10560                                );
10561                            } else {
10562                                trimmed_selections.clear();
10563                                trimmed_selections.push(start..end);
10564                                break;
10565                            }
10566                        }
10567                    }
10568                } else {
10569                    trimmed_selections.push(start..end);
10570                }
10571
10572                for trimmed_range in trimmed_selections {
10573                    if is_first {
10574                        is_first = false;
10575                    } else {
10576                        text += "\n";
10577                    }
10578                    let mut len = 0;
10579                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10580                        text.push_str(chunk);
10581                        len += chunk.len();
10582                    }
10583                    clipboard_selections.push(ClipboardSelection {
10584                        len,
10585                        is_entire_line,
10586                        first_line_indent: buffer
10587                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10588                            .len,
10589                    });
10590                }
10591            }
10592        }
10593
10594        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10595            text,
10596            clipboard_selections,
10597        ));
10598    }
10599
10600    pub fn do_paste(
10601        &mut self,
10602        text: &String,
10603        clipboard_selections: Option<Vec<ClipboardSelection>>,
10604        handle_entire_lines: bool,
10605        window: &mut Window,
10606        cx: &mut Context<Self>,
10607    ) {
10608        if self.read_only(cx) {
10609            return;
10610        }
10611
10612        let clipboard_text = Cow::Borrowed(text);
10613
10614        self.transact(window, cx, |this, window, cx| {
10615            if let Some(mut clipboard_selections) = clipboard_selections {
10616                let old_selections = this.selections.all::<usize>(cx);
10617                let all_selections_were_entire_line =
10618                    clipboard_selections.iter().all(|s| s.is_entire_line);
10619                let first_selection_indent_column =
10620                    clipboard_selections.first().map(|s| s.first_line_indent);
10621                if clipboard_selections.len() != old_selections.len() {
10622                    clipboard_selections.drain(..);
10623                }
10624                let cursor_offset = this.selections.last::<usize>(cx).head();
10625                let mut auto_indent_on_paste = true;
10626
10627                this.buffer.update(cx, |buffer, cx| {
10628                    let snapshot = buffer.read(cx);
10629                    auto_indent_on_paste = snapshot
10630                        .language_settings_at(cursor_offset, cx)
10631                        .auto_indent_on_paste;
10632
10633                    let mut start_offset = 0;
10634                    let mut edits = Vec::new();
10635                    let mut original_indent_columns = Vec::new();
10636                    for (ix, selection) in old_selections.iter().enumerate() {
10637                        let to_insert;
10638                        let entire_line;
10639                        let original_indent_column;
10640                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10641                            let end_offset = start_offset + clipboard_selection.len;
10642                            to_insert = &clipboard_text[start_offset..end_offset];
10643                            entire_line = clipboard_selection.is_entire_line;
10644                            start_offset = end_offset + 1;
10645                            original_indent_column = Some(clipboard_selection.first_line_indent);
10646                        } else {
10647                            to_insert = clipboard_text.as_str();
10648                            entire_line = all_selections_were_entire_line;
10649                            original_indent_column = first_selection_indent_column
10650                        }
10651
10652                        // If the corresponding selection was empty when this slice of the
10653                        // clipboard text was written, then the entire line containing the
10654                        // selection was copied. If this selection is also currently empty,
10655                        // then paste the line before the current line of the buffer.
10656                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10657                            let column = selection.start.to_point(&snapshot).column as usize;
10658                            let line_start = selection.start - column;
10659                            line_start..line_start
10660                        } else {
10661                            selection.range()
10662                        };
10663
10664                        edits.push((range, to_insert));
10665                        original_indent_columns.push(original_indent_column);
10666                    }
10667                    drop(snapshot);
10668
10669                    buffer.edit(
10670                        edits,
10671                        if auto_indent_on_paste {
10672                            Some(AutoindentMode::Block {
10673                                original_indent_columns,
10674                            })
10675                        } else {
10676                            None
10677                        },
10678                        cx,
10679                    );
10680                });
10681
10682                let selections = this.selections.all::<usize>(cx);
10683                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10684                    s.select(selections)
10685                });
10686            } else {
10687                this.insert(&clipboard_text, window, cx);
10688            }
10689        });
10690    }
10691
10692    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10693        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10694        if let Some(item) = cx.read_from_clipboard() {
10695            let entries = item.entries();
10696
10697            match entries.first() {
10698                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10699                // of all the pasted entries.
10700                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10701                    .do_paste(
10702                        clipboard_string.text(),
10703                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10704                        true,
10705                        window,
10706                        cx,
10707                    ),
10708                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10709            }
10710        }
10711    }
10712
10713    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10714        if self.read_only(cx) {
10715            return;
10716        }
10717
10718        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10719
10720        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10721            if let Some((selections, _)) =
10722                self.selection_history.transaction(transaction_id).cloned()
10723            {
10724                self.change_selections(None, window, cx, |s| {
10725                    s.select_anchors(selections.to_vec());
10726                });
10727            } else {
10728                log::error!(
10729                    "No entry in selection_history found for undo. \
10730                     This may correspond to a bug where undo does not update the selection. \
10731                     If this is occurring, please add details to \
10732                     https://github.com/zed-industries/zed/issues/22692"
10733                );
10734            }
10735            self.request_autoscroll(Autoscroll::fit(), cx);
10736            self.unmark_text(window, cx);
10737            self.refresh_inline_completion(true, false, window, cx);
10738            cx.emit(EditorEvent::Edited { transaction_id });
10739            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10740        }
10741    }
10742
10743    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10744        if self.read_only(cx) {
10745            return;
10746        }
10747
10748        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10749
10750        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10751            if let Some((_, Some(selections))) =
10752                self.selection_history.transaction(transaction_id).cloned()
10753            {
10754                self.change_selections(None, window, cx, |s| {
10755                    s.select_anchors(selections.to_vec());
10756                });
10757            } else {
10758                log::error!(
10759                    "No entry in selection_history found for redo. \
10760                     This may correspond to a bug where undo does not update the selection. \
10761                     If this is occurring, please add details to \
10762                     https://github.com/zed-industries/zed/issues/22692"
10763                );
10764            }
10765            self.request_autoscroll(Autoscroll::fit(), cx);
10766            self.unmark_text(window, cx);
10767            self.refresh_inline_completion(true, false, window, cx);
10768            cx.emit(EditorEvent::Edited { transaction_id });
10769        }
10770    }
10771
10772    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10773        self.buffer
10774            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10775    }
10776
10777    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10778        self.buffer
10779            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10780    }
10781
10782    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10783        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10784        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10785            s.move_with(|map, selection| {
10786                let cursor = if selection.is_empty() {
10787                    movement::left(map, selection.start)
10788                } else {
10789                    selection.start
10790                };
10791                selection.collapse_to(cursor, SelectionGoal::None);
10792            });
10793        })
10794    }
10795
10796    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10797        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10799            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10800        })
10801    }
10802
10803    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10804        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10806            s.move_with(|map, selection| {
10807                let cursor = if selection.is_empty() {
10808                    movement::right(map, selection.end)
10809                } else {
10810                    selection.end
10811                };
10812                selection.collapse_to(cursor, SelectionGoal::None)
10813            });
10814        })
10815    }
10816
10817    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10818        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10819        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10820            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10821        })
10822    }
10823
10824    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10825        if self.take_rename(true, window, cx).is_some() {
10826            return;
10827        }
10828
10829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10830            cx.propagate();
10831            return;
10832        }
10833
10834        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10835
10836        let text_layout_details = &self.text_layout_details(window);
10837        let selection_count = self.selections.count();
10838        let first_selection = self.selections.first_anchor();
10839
10840        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10841            s.move_with(|map, selection| {
10842                if !selection.is_empty() {
10843                    selection.goal = SelectionGoal::None;
10844                }
10845                let (cursor, goal) = movement::up(
10846                    map,
10847                    selection.start,
10848                    selection.goal,
10849                    false,
10850                    text_layout_details,
10851                );
10852                selection.collapse_to(cursor, goal);
10853            });
10854        });
10855
10856        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10857        {
10858            cx.propagate();
10859        }
10860    }
10861
10862    pub fn move_up_by_lines(
10863        &mut self,
10864        action: &MoveUpByLines,
10865        window: &mut Window,
10866        cx: &mut Context<Self>,
10867    ) {
10868        if self.take_rename(true, window, cx).is_some() {
10869            return;
10870        }
10871
10872        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10873            cx.propagate();
10874            return;
10875        }
10876
10877        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10878
10879        let text_layout_details = &self.text_layout_details(window);
10880
10881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10882            s.move_with(|map, selection| {
10883                if !selection.is_empty() {
10884                    selection.goal = SelectionGoal::None;
10885                }
10886                let (cursor, goal) = movement::up_by_rows(
10887                    map,
10888                    selection.start,
10889                    action.lines,
10890                    selection.goal,
10891                    false,
10892                    text_layout_details,
10893                );
10894                selection.collapse_to(cursor, goal);
10895            });
10896        })
10897    }
10898
10899    pub fn move_down_by_lines(
10900        &mut self,
10901        action: &MoveDownByLines,
10902        window: &mut Window,
10903        cx: &mut Context<Self>,
10904    ) {
10905        if self.take_rename(true, window, cx).is_some() {
10906            return;
10907        }
10908
10909        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10910            cx.propagate();
10911            return;
10912        }
10913
10914        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10915
10916        let text_layout_details = &self.text_layout_details(window);
10917
10918        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10919            s.move_with(|map, selection| {
10920                if !selection.is_empty() {
10921                    selection.goal = SelectionGoal::None;
10922                }
10923                let (cursor, goal) = movement::down_by_rows(
10924                    map,
10925                    selection.start,
10926                    action.lines,
10927                    selection.goal,
10928                    false,
10929                    text_layout_details,
10930                );
10931                selection.collapse_to(cursor, goal);
10932            });
10933        })
10934    }
10935
10936    pub fn select_down_by_lines(
10937        &mut self,
10938        action: &SelectDownByLines,
10939        window: &mut Window,
10940        cx: &mut Context<Self>,
10941    ) {
10942        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10943        let text_layout_details = &self.text_layout_details(window);
10944        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10945            s.move_heads_with(|map, head, goal| {
10946                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10947            })
10948        })
10949    }
10950
10951    pub fn select_up_by_lines(
10952        &mut self,
10953        action: &SelectUpByLines,
10954        window: &mut Window,
10955        cx: &mut Context<Self>,
10956    ) {
10957        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10958        let text_layout_details = &self.text_layout_details(window);
10959        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10960            s.move_heads_with(|map, head, goal| {
10961                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10962            })
10963        })
10964    }
10965
10966    pub fn select_page_up(
10967        &mut self,
10968        _: &SelectPageUp,
10969        window: &mut Window,
10970        cx: &mut Context<Self>,
10971    ) {
10972        let Some(row_count) = self.visible_row_count() else {
10973            return;
10974        };
10975
10976        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10977
10978        let text_layout_details = &self.text_layout_details(window);
10979
10980        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10981            s.move_heads_with(|map, head, goal| {
10982                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10983            })
10984        })
10985    }
10986
10987    pub fn move_page_up(
10988        &mut self,
10989        action: &MovePageUp,
10990        window: &mut Window,
10991        cx: &mut Context<Self>,
10992    ) {
10993        if self.take_rename(true, window, cx).is_some() {
10994            return;
10995        }
10996
10997        if self
10998            .context_menu
10999            .borrow_mut()
11000            .as_mut()
11001            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11002            .unwrap_or(false)
11003        {
11004            return;
11005        }
11006
11007        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11008            cx.propagate();
11009            return;
11010        }
11011
11012        let Some(row_count) = self.visible_row_count() else {
11013            return;
11014        };
11015
11016        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11017
11018        let autoscroll = if action.center_cursor {
11019            Autoscroll::center()
11020        } else {
11021            Autoscroll::fit()
11022        };
11023
11024        let text_layout_details = &self.text_layout_details(window);
11025
11026        self.change_selections(Some(autoscroll), window, cx, |s| {
11027            s.move_with(|map, selection| {
11028                if !selection.is_empty() {
11029                    selection.goal = SelectionGoal::None;
11030                }
11031                let (cursor, goal) = movement::up_by_rows(
11032                    map,
11033                    selection.end,
11034                    row_count,
11035                    selection.goal,
11036                    false,
11037                    text_layout_details,
11038                );
11039                selection.collapse_to(cursor, goal);
11040            });
11041        });
11042    }
11043
11044    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11045        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11046        let text_layout_details = &self.text_layout_details(window);
11047        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11048            s.move_heads_with(|map, head, goal| {
11049                movement::up(map, head, goal, false, text_layout_details)
11050            })
11051        })
11052    }
11053
11054    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11055        self.take_rename(true, window, cx);
11056
11057        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11058            cx.propagate();
11059            return;
11060        }
11061
11062        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11063
11064        let text_layout_details = &self.text_layout_details(window);
11065        let selection_count = self.selections.count();
11066        let first_selection = self.selections.first_anchor();
11067
11068        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11069            s.move_with(|map, selection| {
11070                if !selection.is_empty() {
11071                    selection.goal = SelectionGoal::None;
11072                }
11073                let (cursor, goal) = movement::down(
11074                    map,
11075                    selection.end,
11076                    selection.goal,
11077                    false,
11078                    text_layout_details,
11079                );
11080                selection.collapse_to(cursor, goal);
11081            });
11082        });
11083
11084        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11085        {
11086            cx.propagate();
11087        }
11088    }
11089
11090    pub fn select_page_down(
11091        &mut self,
11092        _: &SelectPageDown,
11093        window: &mut Window,
11094        cx: &mut Context<Self>,
11095    ) {
11096        let Some(row_count) = self.visible_row_count() else {
11097            return;
11098        };
11099
11100        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11101
11102        let text_layout_details = &self.text_layout_details(window);
11103
11104        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11105            s.move_heads_with(|map, head, goal| {
11106                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11107            })
11108        })
11109    }
11110
11111    pub fn move_page_down(
11112        &mut self,
11113        action: &MovePageDown,
11114        window: &mut Window,
11115        cx: &mut Context<Self>,
11116    ) {
11117        if self.take_rename(true, window, cx).is_some() {
11118            return;
11119        }
11120
11121        if self
11122            .context_menu
11123            .borrow_mut()
11124            .as_mut()
11125            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11126            .unwrap_or(false)
11127        {
11128            return;
11129        }
11130
11131        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11132            cx.propagate();
11133            return;
11134        }
11135
11136        let Some(row_count) = self.visible_row_count() else {
11137            return;
11138        };
11139
11140        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11141
11142        let autoscroll = if action.center_cursor {
11143            Autoscroll::center()
11144        } else {
11145            Autoscroll::fit()
11146        };
11147
11148        let text_layout_details = &self.text_layout_details(window);
11149        self.change_selections(Some(autoscroll), window, cx, |s| {
11150            s.move_with(|map, selection| {
11151                if !selection.is_empty() {
11152                    selection.goal = SelectionGoal::None;
11153                }
11154                let (cursor, goal) = movement::down_by_rows(
11155                    map,
11156                    selection.end,
11157                    row_count,
11158                    selection.goal,
11159                    false,
11160                    text_layout_details,
11161                );
11162                selection.collapse_to(cursor, goal);
11163            });
11164        });
11165    }
11166
11167    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11168        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11169        let text_layout_details = &self.text_layout_details(window);
11170        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11171            s.move_heads_with(|map, head, goal| {
11172                movement::down(map, head, goal, false, text_layout_details)
11173            })
11174        });
11175    }
11176
11177    pub fn context_menu_first(
11178        &mut self,
11179        _: &ContextMenuFirst,
11180        _window: &mut Window,
11181        cx: &mut Context<Self>,
11182    ) {
11183        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11184            context_menu.select_first(self.completion_provider.as_deref(), cx);
11185        }
11186    }
11187
11188    pub fn context_menu_prev(
11189        &mut self,
11190        _: &ContextMenuPrevious,
11191        _window: &mut Window,
11192        cx: &mut Context<Self>,
11193    ) {
11194        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11195            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11196        }
11197    }
11198
11199    pub fn context_menu_next(
11200        &mut self,
11201        _: &ContextMenuNext,
11202        _window: &mut Window,
11203        cx: &mut Context<Self>,
11204    ) {
11205        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11206            context_menu.select_next(self.completion_provider.as_deref(), cx);
11207        }
11208    }
11209
11210    pub fn context_menu_last(
11211        &mut self,
11212        _: &ContextMenuLast,
11213        _window: &mut Window,
11214        cx: &mut Context<Self>,
11215    ) {
11216        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11217            context_menu.select_last(self.completion_provider.as_deref(), cx);
11218        }
11219    }
11220
11221    pub fn move_to_previous_word_start(
11222        &mut self,
11223        _: &MoveToPreviousWordStart,
11224        window: &mut Window,
11225        cx: &mut Context<Self>,
11226    ) {
11227        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11228        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11229            s.move_cursors_with(|map, head, _| {
11230                (
11231                    movement::previous_word_start(map, head),
11232                    SelectionGoal::None,
11233                )
11234            });
11235        })
11236    }
11237
11238    pub fn move_to_previous_subword_start(
11239        &mut self,
11240        _: &MoveToPreviousSubwordStart,
11241        window: &mut Window,
11242        cx: &mut Context<Self>,
11243    ) {
11244        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11245        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11246            s.move_cursors_with(|map, head, _| {
11247                (
11248                    movement::previous_subword_start(map, head),
11249                    SelectionGoal::None,
11250                )
11251            });
11252        })
11253    }
11254
11255    pub fn select_to_previous_word_start(
11256        &mut self,
11257        _: &SelectToPreviousWordStart,
11258        window: &mut Window,
11259        cx: &mut Context<Self>,
11260    ) {
11261        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11262        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11263            s.move_heads_with(|map, head, _| {
11264                (
11265                    movement::previous_word_start(map, head),
11266                    SelectionGoal::None,
11267                )
11268            });
11269        })
11270    }
11271
11272    pub fn select_to_previous_subword_start(
11273        &mut self,
11274        _: &SelectToPreviousSubwordStart,
11275        window: &mut Window,
11276        cx: &mut Context<Self>,
11277    ) {
11278        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11279        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11280            s.move_heads_with(|map, head, _| {
11281                (
11282                    movement::previous_subword_start(map, head),
11283                    SelectionGoal::None,
11284                )
11285            });
11286        })
11287    }
11288
11289    pub fn delete_to_previous_word_start(
11290        &mut self,
11291        action: &DeleteToPreviousWordStart,
11292        window: &mut Window,
11293        cx: &mut Context<Self>,
11294    ) {
11295        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11296        self.transact(window, cx, |this, window, cx| {
11297            this.select_autoclose_pair(window, cx);
11298            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11299                s.move_with(|map, selection| {
11300                    if selection.is_empty() {
11301                        let cursor = if action.ignore_newlines {
11302                            movement::previous_word_start(map, selection.head())
11303                        } else {
11304                            movement::previous_word_start_or_newline(map, selection.head())
11305                        };
11306                        selection.set_head(cursor, SelectionGoal::None);
11307                    }
11308                });
11309            });
11310            this.insert("", window, cx);
11311        });
11312    }
11313
11314    pub fn delete_to_previous_subword_start(
11315        &mut self,
11316        _: &DeleteToPreviousSubwordStart,
11317        window: &mut Window,
11318        cx: &mut Context<Self>,
11319    ) {
11320        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11321        self.transact(window, cx, |this, window, cx| {
11322            this.select_autoclose_pair(window, cx);
11323            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11324                s.move_with(|map, selection| {
11325                    if selection.is_empty() {
11326                        let cursor = movement::previous_subword_start(map, selection.head());
11327                        selection.set_head(cursor, SelectionGoal::None);
11328                    }
11329                });
11330            });
11331            this.insert("", window, cx);
11332        });
11333    }
11334
11335    pub fn move_to_next_word_end(
11336        &mut self,
11337        _: &MoveToNextWordEnd,
11338        window: &mut Window,
11339        cx: &mut Context<Self>,
11340    ) {
11341        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11342        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11343            s.move_cursors_with(|map, head, _| {
11344                (movement::next_word_end(map, head), SelectionGoal::None)
11345            });
11346        })
11347    }
11348
11349    pub fn move_to_next_subword_end(
11350        &mut self,
11351        _: &MoveToNextSubwordEnd,
11352        window: &mut Window,
11353        cx: &mut Context<Self>,
11354    ) {
11355        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11356        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11357            s.move_cursors_with(|map, head, _| {
11358                (movement::next_subword_end(map, head), SelectionGoal::None)
11359            });
11360        })
11361    }
11362
11363    pub fn select_to_next_word_end(
11364        &mut self,
11365        _: &SelectToNextWordEnd,
11366        window: &mut Window,
11367        cx: &mut Context<Self>,
11368    ) {
11369        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11370        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11371            s.move_heads_with(|map, head, _| {
11372                (movement::next_word_end(map, head), SelectionGoal::None)
11373            });
11374        })
11375    }
11376
11377    pub fn select_to_next_subword_end(
11378        &mut self,
11379        _: &SelectToNextSubwordEnd,
11380        window: &mut Window,
11381        cx: &mut Context<Self>,
11382    ) {
11383        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11384        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11385            s.move_heads_with(|map, head, _| {
11386                (movement::next_subword_end(map, head), SelectionGoal::None)
11387            });
11388        })
11389    }
11390
11391    pub fn delete_to_next_word_end(
11392        &mut self,
11393        action: &DeleteToNextWordEnd,
11394        window: &mut Window,
11395        cx: &mut Context<Self>,
11396    ) {
11397        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11398        self.transact(window, cx, |this, window, cx| {
11399            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11400                s.move_with(|map, selection| {
11401                    if selection.is_empty() {
11402                        let cursor = if action.ignore_newlines {
11403                            movement::next_word_end(map, selection.head())
11404                        } else {
11405                            movement::next_word_end_or_newline(map, selection.head())
11406                        };
11407                        selection.set_head(cursor, SelectionGoal::None);
11408                    }
11409                });
11410            });
11411            this.insert("", window, cx);
11412        });
11413    }
11414
11415    pub fn delete_to_next_subword_end(
11416        &mut self,
11417        _: &DeleteToNextSubwordEnd,
11418        window: &mut Window,
11419        cx: &mut Context<Self>,
11420    ) {
11421        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11422        self.transact(window, cx, |this, window, cx| {
11423            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11424                s.move_with(|map, selection| {
11425                    if selection.is_empty() {
11426                        let cursor = movement::next_subword_end(map, selection.head());
11427                        selection.set_head(cursor, SelectionGoal::None);
11428                    }
11429                });
11430            });
11431            this.insert("", window, cx);
11432        });
11433    }
11434
11435    pub fn move_to_beginning_of_line(
11436        &mut self,
11437        action: &MoveToBeginningOfLine,
11438        window: &mut Window,
11439        cx: &mut Context<Self>,
11440    ) {
11441        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11443            s.move_cursors_with(|map, head, _| {
11444                (
11445                    movement::indented_line_beginning(
11446                        map,
11447                        head,
11448                        action.stop_at_soft_wraps,
11449                        action.stop_at_indent,
11450                    ),
11451                    SelectionGoal::None,
11452                )
11453            });
11454        })
11455    }
11456
11457    pub fn select_to_beginning_of_line(
11458        &mut self,
11459        action: &SelectToBeginningOfLine,
11460        window: &mut Window,
11461        cx: &mut Context<Self>,
11462    ) {
11463        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11464        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11465            s.move_heads_with(|map, head, _| {
11466                (
11467                    movement::indented_line_beginning(
11468                        map,
11469                        head,
11470                        action.stop_at_soft_wraps,
11471                        action.stop_at_indent,
11472                    ),
11473                    SelectionGoal::None,
11474                )
11475            });
11476        });
11477    }
11478
11479    pub fn delete_to_beginning_of_line(
11480        &mut self,
11481        action: &DeleteToBeginningOfLine,
11482        window: &mut Window,
11483        cx: &mut Context<Self>,
11484    ) {
11485        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11486        self.transact(window, cx, |this, window, cx| {
11487            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11488                s.move_with(|_, selection| {
11489                    selection.reversed = true;
11490                });
11491            });
11492
11493            this.select_to_beginning_of_line(
11494                &SelectToBeginningOfLine {
11495                    stop_at_soft_wraps: false,
11496                    stop_at_indent: action.stop_at_indent,
11497                },
11498                window,
11499                cx,
11500            );
11501            this.backspace(&Backspace, window, cx);
11502        });
11503    }
11504
11505    pub fn move_to_end_of_line(
11506        &mut self,
11507        action: &MoveToEndOfLine,
11508        window: &mut Window,
11509        cx: &mut Context<Self>,
11510    ) {
11511        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11512        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11513            s.move_cursors_with(|map, head, _| {
11514                (
11515                    movement::line_end(map, head, action.stop_at_soft_wraps),
11516                    SelectionGoal::None,
11517                )
11518            });
11519        })
11520    }
11521
11522    pub fn select_to_end_of_line(
11523        &mut self,
11524        action: &SelectToEndOfLine,
11525        window: &mut Window,
11526        cx: &mut Context<Self>,
11527    ) {
11528        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11530            s.move_heads_with(|map, head, _| {
11531                (
11532                    movement::line_end(map, head, action.stop_at_soft_wraps),
11533                    SelectionGoal::None,
11534                )
11535            });
11536        })
11537    }
11538
11539    pub fn delete_to_end_of_line(
11540        &mut self,
11541        _: &DeleteToEndOfLine,
11542        window: &mut Window,
11543        cx: &mut Context<Self>,
11544    ) {
11545        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11546        self.transact(window, cx, |this, window, cx| {
11547            this.select_to_end_of_line(
11548                &SelectToEndOfLine {
11549                    stop_at_soft_wraps: false,
11550                },
11551                window,
11552                cx,
11553            );
11554            this.delete(&Delete, window, cx);
11555        });
11556    }
11557
11558    pub fn cut_to_end_of_line(
11559        &mut self,
11560        _: &CutToEndOfLine,
11561        window: &mut Window,
11562        cx: &mut Context<Self>,
11563    ) {
11564        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11565        self.transact(window, cx, |this, window, cx| {
11566            this.select_to_end_of_line(
11567                &SelectToEndOfLine {
11568                    stop_at_soft_wraps: false,
11569                },
11570                window,
11571                cx,
11572            );
11573            this.cut(&Cut, window, cx);
11574        });
11575    }
11576
11577    pub fn move_to_start_of_paragraph(
11578        &mut self,
11579        _: &MoveToStartOfParagraph,
11580        window: &mut Window,
11581        cx: &mut Context<Self>,
11582    ) {
11583        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11584            cx.propagate();
11585            return;
11586        }
11587        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11588        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11589            s.move_with(|map, selection| {
11590                selection.collapse_to(
11591                    movement::start_of_paragraph(map, selection.head(), 1),
11592                    SelectionGoal::None,
11593                )
11594            });
11595        })
11596    }
11597
11598    pub fn move_to_end_of_paragraph(
11599        &mut self,
11600        _: &MoveToEndOfParagraph,
11601        window: &mut Window,
11602        cx: &mut Context<Self>,
11603    ) {
11604        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11605            cx.propagate();
11606            return;
11607        }
11608        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11609        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11610            s.move_with(|map, selection| {
11611                selection.collapse_to(
11612                    movement::end_of_paragraph(map, selection.head(), 1),
11613                    SelectionGoal::None,
11614                )
11615            });
11616        })
11617    }
11618
11619    pub fn select_to_start_of_paragraph(
11620        &mut self,
11621        _: &SelectToStartOfParagraph,
11622        window: &mut Window,
11623        cx: &mut Context<Self>,
11624    ) {
11625        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11626            cx.propagate();
11627            return;
11628        }
11629        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11630        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11631            s.move_heads_with(|map, head, _| {
11632                (
11633                    movement::start_of_paragraph(map, head, 1),
11634                    SelectionGoal::None,
11635                )
11636            });
11637        })
11638    }
11639
11640    pub fn select_to_end_of_paragraph(
11641        &mut self,
11642        _: &SelectToEndOfParagraph,
11643        window: &mut Window,
11644        cx: &mut Context<Self>,
11645    ) {
11646        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11647            cx.propagate();
11648            return;
11649        }
11650        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11651        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11652            s.move_heads_with(|map, head, _| {
11653                (
11654                    movement::end_of_paragraph(map, head, 1),
11655                    SelectionGoal::None,
11656                )
11657            });
11658        })
11659    }
11660
11661    pub fn move_to_start_of_excerpt(
11662        &mut self,
11663        _: &MoveToStartOfExcerpt,
11664        window: &mut Window,
11665        cx: &mut Context<Self>,
11666    ) {
11667        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11668            cx.propagate();
11669            return;
11670        }
11671        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11672        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11673            s.move_with(|map, selection| {
11674                selection.collapse_to(
11675                    movement::start_of_excerpt(
11676                        map,
11677                        selection.head(),
11678                        workspace::searchable::Direction::Prev,
11679                    ),
11680                    SelectionGoal::None,
11681                )
11682            });
11683        })
11684    }
11685
11686    pub fn move_to_start_of_next_excerpt(
11687        &mut self,
11688        _: &MoveToStartOfNextExcerpt,
11689        window: &mut Window,
11690        cx: &mut Context<Self>,
11691    ) {
11692        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11693            cx.propagate();
11694            return;
11695        }
11696
11697        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11698            s.move_with(|map, selection| {
11699                selection.collapse_to(
11700                    movement::start_of_excerpt(
11701                        map,
11702                        selection.head(),
11703                        workspace::searchable::Direction::Next,
11704                    ),
11705                    SelectionGoal::None,
11706                )
11707            });
11708        })
11709    }
11710
11711    pub fn move_to_end_of_excerpt(
11712        &mut self,
11713        _: &MoveToEndOfExcerpt,
11714        window: &mut Window,
11715        cx: &mut Context<Self>,
11716    ) {
11717        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11718            cx.propagate();
11719            return;
11720        }
11721        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11722        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11723            s.move_with(|map, selection| {
11724                selection.collapse_to(
11725                    movement::end_of_excerpt(
11726                        map,
11727                        selection.head(),
11728                        workspace::searchable::Direction::Next,
11729                    ),
11730                    SelectionGoal::None,
11731                )
11732            });
11733        })
11734    }
11735
11736    pub fn move_to_end_of_previous_excerpt(
11737        &mut self,
11738        _: &MoveToEndOfPreviousExcerpt,
11739        window: &mut Window,
11740        cx: &mut Context<Self>,
11741    ) {
11742        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11743            cx.propagate();
11744            return;
11745        }
11746        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11747        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11748            s.move_with(|map, selection| {
11749                selection.collapse_to(
11750                    movement::end_of_excerpt(
11751                        map,
11752                        selection.head(),
11753                        workspace::searchable::Direction::Prev,
11754                    ),
11755                    SelectionGoal::None,
11756                )
11757            });
11758        })
11759    }
11760
11761    pub fn select_to_start_of_excerpt(
11762        &mut self,
11763        _: &SelectToStartOfExcerpt,
11764        window: &mut Window,
11765        cx: &mut Context<Self>,
11766    ) {
11767        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11768            cx.propagate();
11769            return;
11770        }
11771        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11772        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11773            s.move_heads_with(|map, head, _| {
11774                (
11775                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11776                    SelectionGoal::None,
11777                )
11778            });
11779        })
11780    }
11781
11782    pub fn select_to_start_of_next_excerpt(
11783        &mut self,
11784        _: &SelectToStartOfNextExcerpt,
11785        window: &mut Window,
11786        cx: &mut Context<Self>,
11787    ) {
11788        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11789            cx.propagate();
11790            return;
11791        }
11792        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11793        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11794            s.move_heads_with(|map, head, _| {
11795                (
11796                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11797                    SelectionGoal::None,
11798                )
11799            });
11800        })
11801    }
11802
11803    pub fn select_to_end_of_excerpt(
11804        &mut self,
11805        _: &SelectToEndOfExcerpt,
11806        window: &mut Window,
11807        cx: &mut Context<Self>,
11808    ) {
11809        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11810            cx.propagate();
11811            return;
11812        }
11813        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11814        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11815            s.move_heads_with(|map, head, _| {
11816                (
11817                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11818                    SelectionGoal::None,
11819                )
11820            });
11821        })
11822    }
11823
11824    pub fn select_to_end_of_previous_excerpt(
11825        &mut self,
11826        _: &SelectToEndOfPreviousExcerpt,
11827        window: &mut Window,
11828        cx: &mut Context<Self>,
11829    ) {
11830        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11831            cx.propagate();
11832            return;
11833        }
11834        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11835        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11836            s.move_heads_with(|map, head, _| {
11837                (
11838                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11839                    SelectionGoal::None,
11840                )
11841            });
11842        })
11843    }
11844
11845    pub fn move_to_beginning(
11846        &mut self,
11847        _: &MoveToBeginning,
11848        window: &mut Window,
11849        cx: &mut Context<Self>,
11850    ) {
11851        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11852            cx.propagate();
11853            return;
11854        }
11855        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11856        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11857            s.select_ranges(vec![0..0]);
11858        });
11859    }
11860
11861    pub fn select_to_beginning(
11862        &mut self,
11863        _: &SelectToBeginning,
11864        window: &mut Window,
11865        cx: &mut Context<Self>,
11866    ) {
11867        let mut selection = self.selections.last::<Point>(cx);
11868        selection.set_head(Point::zero(), SelectionGoal::None);
11869        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11870        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11871            s.select(vec![selection]);
11872        });
11873    }
11874
11875    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11876        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11877            cx.propagate();
11878            return;
11879        }
11880        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11881        let cursor = self.buffer.read(cx).read(cx).len();
11882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11883            s.select_ranges(vec![cursor..cursor])
11884        });
11885    }
11886
11887    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11888        self.nav_history = nav_history;
11889    }
11890
11891    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11892        self.nav_history.as_ref()
11893    }
11894
11895    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11896        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11897    }
11898
11899    fn push_to_nav_history(
11900        &mut self,
11901        cursor_anchor: Anchor,
11902        new_position: Option<Point>,
11903        is_deactivate: bool,
11904        cx: &mut Context<Self>,
11905    ) {
11906        if let Some(nav_history) = self.nav_history.as_mut() {
11907            let buffer = self.buffer.read(cx).read(cx);
11908            let cursor_position = cursor_anchor.to_point(&buffer);
11909            let scroll_state = self.scroll_manager.anchor();
11910            let scroll_top_row = scroll_state.top_row(&buffer);
11911            drop(buffer);
11912
11913            if let Some(new_position) = new_position {
11914                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11915                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11916                    return;
11917                }
11918            }
11919
11920            nav_history.push(
11921                Some(NavigationData {
11922                    cursor_anchor,
11923                    cursor_position,
11924                    scroll_anchor: scroll_state,
11925                    scroll_top_row,
11926                }),
11927                cx,
11928            );
11929            cx.emit(EditorEvent::PushedToNavHistory {
11930                anchor: cursor_anchor,
11931                is_deactivate,
11932            })
11933        }
11934    }
11935
11936    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11937        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11938        let buffer = self.buffer.read(cx).snapshot(cx);
11939        let mut selection = self.selections.first::<usize>(cx);
11940        selection.set_head(buffer.len(), SelectionGoal::None);
11941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11942            s.select(vec![selection]);
11943        });
11944    }
11945
11946    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11947        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11948        let end = self.buffer.read(cx).read(cx).len();
11949        self.change_selections(None, window, cx, |s| {
11950            s.select_ranges(vec![0..end]);
11951        });
11952    }
11953
11954    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11955        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11956        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11957        let mut selections = self.selections.all::<Point>(cx);
11958        let max_point = display_map.buffer_snapshot.max_point();
11959        for selection in &mut selections {
11960            let rows = selection.spanned_rows(true, &display_map);
11961            selection.start = Point::new(rows.start.0, 0);
11962            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11963            selection.reversed = false;
11964        }
11965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11966            s.select(selections);
11967        });
11968    }
11969
11970    pub fn split_selection_into_lines(
11971        &mut self,
11972        _: &SplitSelectionIntoLines,
11973        window: &mut Window,
11974        cx: &mut Context<Self>,
11975    ) {
11976        let selections = self
11977            .selections
11978            .all::<Point>(cx)
11979            .into_iter()
11980            .map(|selection| selection.start..selection.end)
11981            .collect::<Vec<_>>();
11982        self.unfold_ranges(&selections, true, true, cx);
11983
11984        let mut new_selection_ranges = Vec::new();
11985        {
11986            let buffer = self.buffer.read(cx).read(cx);
11987            for selection in selections {
11988                for row in selection.start.row..selection.end.row {
11989                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11990                    new_selection_ranges.push(cursor..cursor);
11991                }
11992
11993                let is_multiline_selection = selection.start.row != selection.end.row;
11994                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11995                // so this action feels more ergonomic when paired with other selection operations
11996                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11997                if !should_skip_last {
11998                    new_selection_ranges.push(selection.end..selection.end);
11999                }
12000            }
12001        }
12002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12003            s.select_ranges(new_selection_ranges);
12004        });
12005    }
12006
12007    pub fn add_selection_above(
12008        &mut self,
12009        _: &AddSelectionAbove,
12010        window: &mut Window,
12011        cx: &mut Context<Self>,
12012    ) {
12013        self.add_selection(true, window, cx);
12014    }
12015
12016    pub fn add_selection_below(
12017        &mut self,
12018        _: &AddSelectionBelow,
12019        window: &mut Window,
12020        cx: &mut Context<Self>,
12021    ) {
12022        self.add_selection(false, window, cx);
12023    }
12024
12025    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12026        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12027
12028        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12029        let mut selections = self.selections.all::<Point>(cx);
12030        let text_layout_details = self.text_layout_details(window);
12031        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12032            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12033            let range = oldest_selection.display_range(&display_map).sorted();
12034
12035            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12036            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12037            let positions = start_x.min(end_x)..start_x.max(end_x);
12038
12039            selections.clear();
12040            let mut stack = Vec::new();
12041            for row in range.start.row().0..=range.end.row().0 {
12042                if let Some(selection) = self.selections.build_columnar_selection(
12043                    &display_map,
12044                    DisplayRow(row),
12045                    &positions,
12046                    oldest_selection.reversed,
12047                    &text_layout_details,
12048                ) {
12049                    stack.push(selection.id);
12050                    selections.push(selection);
12051                }
12052            }
12053
12054            if above {
12055                stack.reverse();
12056            }
12057
12058            AddSelectionsState { above, stack }
12059        });
12060
12061        let last_added_selection = *state.stack.last().unwrap();
12062        let mut new_selections = Vec::new();
12063        if above == state.above {
12064            let end_row = if above {
12065                DisplayRow(0)
12066            } else {
12067                display_map.max_point().row()
12068            };
12069
12070            'outer: for selection in selections {
12071                if selection.id == last_added_selection {
12072                    let range = selection.display_range(&display_map).sorted();
12073                    debug_assert_eq!(range.start.row(), range.end.row());
12074                    let mut row = range.start.row();
12075                    let positions =
12076                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12077                            px(start)..px(end)
12078                        } else {
12079                            let start_x =
12080                                display_map.x_for_display_point(range.start, &text_layout_details);
12081                            let end_x =
12082                                display_map.x_for_display_point(range.end, &text_layout_details);
12083                            start_x.min(end_x)..start_x.max(end_x)
12084                        };
12085
12086                    while row != end_row {
12087                        if above {
12088                            row.0 -= 1;
12089                        } else {
12090                            row.0 += 1;
12091                        }
12092
12093                        if let Some(new_selection) = self.selections.build_columnar_selection(
12094                            &display_map,
12095                            row,
12096                            &positions,
12097                            selection.reversed,
12098                            &text_layout_details,
12099                        ) {
12100                            state.stack.push(new_selection.id);
12101                            if above {
12102                                new_selections.push(new_selection);
12103                                new_selections.push(selection);
12104                            } else {
12105                                new_selections.push(selection);
12106                                new_selections.push(new_selection);
12107                            }
12108
12109                            continue 'outer;
12110                        }
12111                    }
12112                }
12113
12114                new_selections.push(selection);
12115            }
12116        } else {
12117            new_selections = selections;
12118            new_selections.retain(|s| s.id != last_added_selection);
12119            state.stack.pop();
12120        }
12121
12122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12123            s.select(new_selections);
12124        });
12125        if state.stack.len() > 1 {
12126            self.add_selections_state = Some(state);
12127        }
12128    }
12129
12130    pub fn select_next_match_internal(
12131        &mut self,
12132        display_map: &DisplaySnapshot,
12133        replace_newest: bool,
12134        autoscroll: Option<Autoscroll>,
12135        window: &mut Window,
12136        cx: &mut Context<Self>,
12137    ) -> Result<()> {
12138        fn select_next_match_ranges(
12139            this: &mut Editor,
12140            range: Range<usize>,
12141            reversed: bool,
12142            replace_newest: bool,
12143            auto_scroll: Option<Autoscroll>,
12144            window: &mut Window,
12145            cx: &mut Context<Editor>,
12146        ) {
12147            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12148            this.change_selections(auto_scroll, window, cx, |s| {
12149                if replace_newest {
12150                    s.delete(s.newest_anchor().id);
12151                }
12152                if reversed {
12153                    s.insert_range(range.end..range.start);
12154                } else {
12155                    s.insert_range(range);
12156                }
12157            });
12158        }
12159
12160        let buffer = &display_map.buffer_snapshot;
12161        let mut selections = self.selections.all::<usize>(cx);
12162        if let Some(mut select_next_state) = self.select_next_state.take() {
12163            let query = &select_next_state.query;
12164            if !select_next_state.done {
12165                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12166                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12167                let mut next_selected_range = None;
12168
12169                let bytes_after_last_selection =
12170                    buffer.bytes_in_range(last_selection.end..buffer.len());
12171                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12172                let query_matches = query
12173                    .stream_find_iter(bytes_after_last_selection)
12174                    .map(|result| (last_selection.end, result))
12175                    .chain(
12176                        query
12177                            .stream_find_iter(bytes_before_first_selection)
12178                            .map(|result| (0, result)),
12179                    );
12180
12181                for (start_offset, query_match) in query_matches {
12182                    let query_match = query_match.unwrap(); // can only fail due to I/O
12183                    let offset_range =
12184                        start_offset + query_match.start()..start_offset + query_match.end();
12185                    let display_range = offset_range.start.to_display_point(display_map)
12186                        ..offset_range.end.to_display_point(display_map);
12187
12188                    if !select_next_state.wordwise
12189                        || (!movement::is_inside_word(display_map, display_range.start)
12190                            && !movement::is_inside_word(display_map, display_range.end))
12191                    {
12192                        // TODO: This is n^2, because we might check all the selections
12193                        if !selections
12194                            .iter()
12195                            .any(|selection| selection.range().overlaps(&offset_range))
12196                        {
12197                            next_selected_range = Some(offset_range);
12198                            break;
12199                        }
12200                    }
12201                }
12202
12203                if let Some(next_selected_range) = next_selected_range {
12204                    select_next_match_ranges(
12205                        self,
12206                        next_selected_range,
12207                        last_selection.reversed,
12208                        replace_newest,
12209                        autoscroll,
12210                        window,
12211                        cx,
12212                    );
12213                } else {
12214                    select_next_state.done = true;
12215                }
12216            }
12217
12218            self.select_next_state = Some(select_next_state);
12219        } else {
12220            let mut only_carets = true;
12221            let mut same_text_selected = true;
12222            let mut selected_text = None;
12223
12224            let mut selections_iter = selections.iter().peekable();
12225            while let Some(selection) = selections_iter.next() {
12226                if selection.start != selection.end {
12227                    only_carets = false;
12228                }
12229
12230                if same_text_selected {
12231                    if selected_text.is_none() {
12232                        selected_text =
12233                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12234                    }
12235
12236                    if let Some(next_selection) = selections_iter.peek() {
12237                        if next_selection.range().len() == selection.range().len() {
12238                            let next_selected_text = buffer
12239                                .text_for_range(next_selection.range())
12240                                .collect::<String>();
12241                            if Some(next_selected_text) != selected_text {
12242                                same_text_selected = false;
12243                                selected_text = None;
12244                            }
12245                        } else {
12246                            same_text_selected = false;
12247                            selected_text = None;
12248                        }
12249                    }
12250                }
12251            }
12252
12253            if only_carets {
12254                for selection in &mut selections {
12255                    let word_range = movement::surrounding_word(
12256                        display_map,
12257                        selection.start.to_display_point(display_map),
12258                    );
12259                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12260                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12261                    selection.goal = SelectionGoal::None;
12262                    selection.reversed = false;
12263                    select_next_match_ranges(
12264                        self,
12265                        selection.start..selection.end,
12266                        selection.reversed,
12267                        replace_newest,
12268                        autoscroll,
12269                        window,
12270                        cx,
12271                    );
12272                }
12273
12274                if selections.len() == 1 {
12275                    let selection = selections
12276                        .last()
12277                        .expect("ensured that there's only one selection");
12278                    let query = buffer
12279                        .text_for_range(selection.start..selection.end)
12280                        .collect::<String>();
12281                    let is_empty = query.is_empty();
12282                    let select_state = SelectNextState {
12283                        query: AhoCorasick::new(&[query])?,
12284                        wordwise: true,
12285                        done: is_empty,
12286                    };
12287                    self.select_next_state = Some(select_state);
12288                } else {
12289                    self.select_next_state = None;
12290                }
12291            } else if let Some(selected_text) = selected_text {
12292                self.select_next_state = Some(SelectNextState {
12293                    query: AhoCorasick::new(&[selected_text])?,
12294                    wordwise: false,
12295                    done: false,
12296                });
12297                self.select_next_match_internal(
12298                    display_map,
12299                    replace_newest,
12300                    autoscroll,
12301                    window,
12302                    cx,
12303                )?;
12304            }
12305        }
12306        Ok(())
12307    }
12308
12309    pub fn select_all_matches(
12310        &mut self,
12311        _action: &SelectAllMatches,
12312        window: &mut Window,
12313        cx: &mut Context<Self>,
12314    ) -> Result<()> {
12315        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12316
12317        self.push_to_selection_history();
12318        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12319
12320        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12321        let Some(select_next_state) = self.select_next_state.as_mut() else {
12322            return Ok(());
12323        };
12324        if select_next_state.done {
12325            return Ok(());
12326        }
12327
12328        let mut new_selections = Vec::new();
12329
12330        let reversed = self.selections.oldest::<usize>(cx).reversed;
12331        let buffer = &display_map.buffer_snapshot;
12332        let query_matches = select_next_state
12333            .query
12334            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12335
12336        for query_match in query_matches.into_iter() {
12337            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12338            let offset_range = if reversed {
12339                query_match.end()..query_match.start()
12340            } else {
12341                query_match.start()..query_match.end()
12342            };
12343            let display_range = offset_range.start.to_display_point(&display_map)
12344                ..offset_range.end.to_display_point(&display_map);
12345
12346            if !select_next_state.wordwise
12347                || (!movement::is_inside_word(&display_map, display_range.start)
12348                    && !movement::is_inside_word(&display_map, display_range.end))
12349            {
12350                new_selections.push(offset_range.start..offset_range.end);
12351            }
12352        }
12353
12354        select_next_state.done = true;
12355        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12356        self.change_selections(None, window, cx, |selections| {
12357            selections.select_ranges(new_selections)
12358        });
12359
12360        Ok(())
12361    }
12362
12363    pub fn select_next(
12364        &mut self,
12365        action: &SelectNext,
12366        window: &mut Window,
12367        cx: &mut Context<Self>,
12368    ) -> Result<()> {
12369        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12370        self.push_to_selection_history();
12371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12372        self.select_next_match_internal(
12373            &display_map,
12374            action.replace_newest,
12375            Some(Autoscroll::newest()),
12376            window,
12377            cx,
12378        )?;
12379        Ok(())
12380    }
12381
12382    pub fn select_previous(
12383        &mut self,
12384        action: &SelectPrevious,
12385        window: &mut Window,
12386        cx: &mut Context<Self>,
12387    ) -> Result<()> {
12388        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12389        self.push_to_selection_history();
12390        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12391        let buffer = &display_map.buffer_snapshot;
12392        let mut selections = self.selections.all::<usize>(cx);
12393        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12394            let query = &select_prev_state.query;
12395            if !select_prev_state.done {
12396                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12397                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12398                let mut next_selected_range = None;
12399                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12400                let bytes_before_last_selection =
12401                    buffer.reversed_bytes_in_range(0..last_selection.start);
12402                let bytes_after_first_selection =
12403                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12404                let query_matches = query
12405                    .stream_find_iter(bytes_before_last_selection)
12406                    .map(|result| (last_selection.start, result))
12407                    .chain(
12408                        query
12409                            .stream_find_iter(bytes_after_first_selection)
12410                            .map(|result| (buffer.len(), result)),
12411                    );
12412                for (end_offset, query_match) in query_matches {
12413                    let query_match = query_match.unwrap(); // can only fail due to I/O
12414                    let offset_range =
12415                        end_offset - query_match.end()..end_offset - query_match.start();
12416                    let display_range = offset_range.start.to_display_point(&display_map)
12417                        ..offset_range.end.to_display_point(&display_map);
12418
12419                    if !select_prev_state.wordwise
12420                        || (!movement::is_inside_word(&display_map, display_range.start)
12421                            && !movement::is_inside_word(&display_map, display_range.end))
12422                    {
12423                        next_selected_range = Some(offset_range);
12424                        break;
12425                    }
12426                }
12427
12428                if let Some(next_selected_range) = next_selected_range {
12429                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12430                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12431                        if action.replace_newest {
12432                            s.delete(s.newest_anchor().id);
12433                        }
12434                        if last_selection.reversed {
12435                            s.insert_range(next_selected_range.end..next_selected_range.start);
12436                        } else {
12437                            s.insert_range(next_selected_range);
12438                        }
12439                    });
12440                } else {
12441                    select_prev_state.done = true;
12442                }
12443            }
12444
12445            self.select_prev_state = Some(select_prev_state);
12446        } else {
12447            let mut only_carets = true;
12448            let mut same_text_selected = true;
12449            let mut selected_text = None;
12450
12451            let mut selections_iter = selections.iter().peekable();
12452            while let Some(selection) = selections_iter.next() {
12453                if selection.start != selection.end {
12454                    only_carets = false;
12455                }
12456
12457                if same_text_selected {
12458                    if selected_text.is_none() {
12459                        selected_text =
12460                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12461                    }
12462
12463                    if let Some(next_selection) = selections_iter.peek() {
12464                        if next_selection.range().len() == selection.range().len() {
12465                            let next_selected_text = buffer
12466                                .text_for_range(next_selection.range())
12467                                .collect::<String>();
12468                            if Some(next_selected_text) != selected_text {
12469                                same_text_selected = false;
12470                                selected_text = None;
12471                            }
12472                        } else {
12473                            same_text_selected = false;
12474                            selected_text = None;
12475                        }
12476                    }
12477                }
12478            }
12479
12480            if only_carets {
12481                for selection in &mut selections {
12482                    let word_range = movement::surrounding_word(
12483                        &display_map,
12484                        selection.start.to_display_point(&display_map),
12485                    );
12486                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12487                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12488                    selection.goal = SelectionGoal::None;
12489                    selection.reversed = false;
12490                }
12491                if selections.len() == 1 {
12492                    let selection = selections
12493                        .last()
12494                        .expect("ensured that there's only one selection");
12495                    let query = buffer
12496                        .text_for_range(selection.start..selection.end)
12497                        .collect::<String>();
12498                    let is_empty = query.is_empty();
12499                    let select_state = SelectNextState {
12500                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12501                        wordwise: true,
12502                        done: is_empty,
12503                    };
12504                    self.select_prev_state = Some(select_state);
12505                } else {
12506                    self.select_prev_state = None;
12507                }
12508
12509                self.unfold_ranges(
12510                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12511                    false,
12512                    true,
12513                    cx,
12514                );
12515                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12516                    s.select(selections);
12517                });
12518            } else if let Some(selected_text) = selected_text {
12519                self.select_prev_state = Some(SelectNextState {
12520                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12521                    wordwise: false,
12522                    done: false,
12523                });
12524                self.select_previous(action, window, cx)?;
12525            }
12526        }
12527        Ok(())
12528    }
12529
12530    pub fn find_next_match(
12531        &mut self,
12532        _: &FindNextMatch,
12533        window: &mut Window,
12534        cx: &mut Context<Self>,
12535    ) -> Result<()> {
12536        let selections = self.selections.disjoint_anchors();
12537        match selections.first() {
12538            Some(first) if selections.len() >= 2 => {
12539                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12540                    s.select_ranges([first.range()]);
12541                });
12542            }
12543            _ => self.select_next(
12544                &SelectNext {
12545                    replace_newest: true,
12546                },
12547                window,
12548                cx,
12549            )?,
12550        }
12551        Ok(())
12552    }
12553
12554    pub fn find_previous_match(
12555        &mut self,
12556        _: &FindPreviousMatch,
12557        window: &mut Window,
12558        cx: &mut Context<Self>,
12559    ) -> Result<()> {
12560        let selections = self.selections.disjoint_anchors();
12561        match selections.last() {
12562            Some(last) if selections.len() >= 2 => {
12563                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12564                    s.select_ranges([last.range()]);
12565                });
12566            }
12567            _ => self.select_previous(
12568                &SelectPrevious {
12569                    replace_newest: true,
12570                },
12571                window,
12572                cx,
12573            )?,
12574        }
12575        Ok(())
12576    }
12577
12578    pub fn toggle_comments(
12579        &mut self,
12580        action: &ToggleComments,
12581        window: &mut Window,
12582        cx: &mut Context<Self>,
12583    ) {
12584        if self.read_only(cx) {
12585            return;
12586        }
12587        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12588        let text_layout_details = &self.text_layout_details(window);
12589        self.transact(window, cx, |this, window, cx| {
12590            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12591            let mut edits = Vec::new();
12592            let mut selection_edit_ranges = Vec::new();
12593            let mut last_toggled_row = None;
12594            let snapshot = this.buffer.read(cx).read(cx);
12595            let empty_str: Arc<str> = Arc::default();
12596            let mut suffixes_inserted = Vec::new();
12597            let ignore_indent = action.ignore_indent;
12598
12599            fn comment_prefix_range(
12600                snapshot: &MultiBufferSnapshot,
12601                row: MultiBufferRow,
12602                comment_prefix: &str,
12603                comment_prefix_whitespace: &str,
12604                ignore_indent: bool,
12605            ) -> Range<Point> {
12606                let indent_size = if ignore_indent {
12607                    0
12608                } else {
12609                    snapshot.indent_size_for_line(row).len
12610                };
12611
12612                let start = Point::new(row.0, indent_size);
12613
12614                let mut line_bytes = snapshot
12615                    .bytes_in_range(start..snapshot.max_point())
12616                    .flatten()
12617                    .copied();
12618
12619                // If this line currently begins with the line comment prefix, then record
12620                // the range containing the prefix.
12621                if line_bytes
12622                    .by_ref()
12623                    .take(comment_prefix.len())
12624                    .eq(comment_prefix.bytes())
12625                {
12626                    // Include any whitespace that matches the comment prefix.
12627                    let matching_whitespace_len = line_bytes
12628                        .zip(comment_prefix_whitespace.bytes())
12629                        .take_while(|(a, b)| a == b)
12630                        .count() as u32;
12631                    let end = Point::new(
12632                        start.row,
12633                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12634                    );
12635                    start..end
12636                } else {
12637                    start..start
12638                }
12639            }
12640
12641            fn comment_suffix_range(
12642                snapshot: &MultiBufferSnapshot,
12643                row: MultiBufferRow,
12644                comment_suffix: &str,
12645                comment_suffix_has_leading_space: bool,
12646            ) -> Range<Point> {
12647                let end = Point::new(row.0, snapshot.line_len(row));
12648                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12649
12650                let mut line_end_bytes = snapshot
12651                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12652                    .flatten()
12653                    .copied();
12654
12655                let leading_space_len = if suffix_start_column > 0
12656                    && line_end_bytes.next() == Some(b' ')
12657                    && comment_suffix_has_leading_space
12658                {
12659                    1
12660                } else {
12661                    0
12662                };
12663
12664                // If this line currently begins with the line comment prefix, then record
12665                // the range containing the prefix.
12666                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12667                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12668                    start..end
12669                } else {
12670                    end..end
12671                }
12672            }
12673
12674            // TODO: Handle selections that cross excerpts
12675            for selection in &mut selections {
12676                let start_column = snapshot
12677                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12678                    .len;
12679                let language = if let Some(language) =
12680                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12681                {
12682                    language
12683                } else {
12684                    continue;
12685                };
12686
12687                selection_edit_ranges.clear();
12688
12689                // If multiple selections contain a given row, avoid processing that
12690                // row more than once.
12691                let mut start_row = MultiBufferRow(selection.start.row);
12692                if last_toggled_row == Some(start_row) {
12693                    start_row = start_row.next_row();
12694                }
12695                let end_row =
12696                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12697                        MultiBufferRow(selection.end.row - 1)
12698                    } else {
12699                        MultiBufferRow(selection.end.row)
12700                    };
12701                last_toggled_row = Some(end_row);
12702
12703                if start_row > end_row {
12704                    continue;
12705                }
12706
12707                // If the language has line comments, toggle those.
12708                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12709
12710                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12711                if ignore_indent {
12712                    full_comment_prefixes = full_comment_prefixes
12713                        .into_iter()
12714                        .map(|s| Arc::from(s.trim_end()))
12715                        .collect();
12716                }
12717
12718                if !full_comment_prefixes.is_empty() {
12719                    let first_prefix = full_comment_prefixes
12720                        .first()
12721                        .expect("prefixes is non-empty");
12722                    let prefix_trimmed_lengths = full_comment_prefixes
12723                        .iter()
12724                        .map(|p| p.trim_end_matches(' ').len())
12725                        .collect::<SmallVec<[usize; 4]>>();
12726
12727                    let mut all_selection_lines_are_comments = true;
12728
12729                    for row in start_row.0..=end_row.0 {
12730                        let row = MultiBufferRow(row);
12731                        if start_row < end_row && snapshot.is_line_blank(row) {
12732                            continue;
12733                        }
12734
12735                        let prefix_range = full_comment_prefixes
12736                            .iter()
12737                            .zip(prefix_trimmed_lengths.iter().copied())
12738                            .map(|(prefix, trimmed_prefix_len)| {
12739                                comment_prefix_range(
12740                                    snapshot.deref(),
12741                                    row,
12742                                    &prefix[..trimmed_prefix_len],
12743                                    &prefix[trimmed_prefix_len..],
12744                                    ignore_indent,
12745                                )
12746                            })
12747                            .max_by_key(|range| range.end.column - range.start.column)
12748                            .expect("prefixes is non-empty");
12749
12750                        if prefix_range.is_empty() {
12751                            all_selection_lines_are_comments = false;
12752                        }
12753
12754                        selection_edit_ranges.push(prefix_range);
12755                    }
12756
12757                    if all_selection_lines_are_comments {
12758                        edits.extend(
12759                            selection_edit_ranges
12760                                .iter()
12761                                .cloned()
12762                                .map(|range| (range, empty_str.clone())),
12763                        );
12764                    } else {
12765                        let min_column = selection_edit_ranges
12766                            .iter()
12767                            .map(|range| range.start.column)
12768                            .min()
12769                            .unwrap_or(0);
12770                        edits.extend(selection_edit_ranges.iter().map(|range| {
12771                            let position = Point::new(range.start.row, min_column);
12772                            (position..position, first_prefix.clone())
12773                        }));
12774                    }
12775                } else if let Some((full_comment_prefix, comment_suffix)) =
12776                    language.block_comment_delimiters()
12777                {
12778                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12779                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12780                    let prefix_range = comment_prefix_range(
12781                        snapshot.deref(),
12782                        start_row,
12783                        comment_prefix,
12784                        comment_prefix_whitespace,
12785                        ignore_indent,
12786                    );
12787                    let suffix_range = comment_suffix_range(
12788                        snapshot.deref(),
12789                        end_row,
12790                        comment_suffix.trim_start_matches(' '),
12791                        comment_suffix.starts_with(' '),
12792                    );
12793
12794                    if prefix_range.is_empty() || suffix_range.is_empty() {
12795                        edits.push((
12796                            prefix_range.start..prefix_range.start,
12797                            full_comment_prefix.clone(),
12798                        ));
12799                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12800                        suffixes_inserted.push((end_row, comment_suffix.len()));
12801                    } else {
12802                        edits.push((prefix_range, empty_str.clone()));
12803                        edits.push((suffix_range, empty_str.clone()));
12804                    }
12805                } else {
12806                    continue;
12807                }
12808            }
12809
12810            drop(snapshot);
12811            this.buffer.update(cx, |buffer, cx| {
12812                buffer.edit(edits, None, cx);
12813            });
12814
12815            // Adjust selections so that they end before any comment suffixes that
12816            // were inserted.
12817            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12818            let mut selections = this.selections.all::<Point>(cx);
12819            let snapshot = this.buffer.read(cx).read(cx);
12820            for selection in &mut selections {
12821                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12822                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12823                        Ordering::Less => {
12824                            suffixes_inserted.next();
12825                            continue;
12826                        }
12827                        Ordering::Greater => break,
12828                        Ordering::Equal => {
12829                            if selection.end.column == snapshot.line_len(row) {
12830                                if selection.is_empty() {
12831                                    selection.start.column -= suffix_len as u32;
12832                                }
12833                                selection.end.column -= suffix_len as u32;
12834                            }
12835                            break;
12836                        }
12837                    }
12838                }
12839            }
12840
12841            drop(snapshot);
12842            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12843                s.select(selections)
12844            });
12845
12846            let selections = this.selections.all::<Point>(cx);
12847            let selections_on_single_row = selections.windows(2).all(|selections| {
12848                selections[0].start.row == selections[1].start.row
12849                    && selections[0].end.row == selections[1].end.row
12850                    && selections[0].start.row == selections[0].end.row
12851            });
12852            let selections_selecting = selections
12853                .iter()
12854                .any(|selection| selection.start != selection.end);
12855            let advance_downwards = action.advance_downwards
12856                && selections_on_single_row
12857                && !selections_selecting
12858                && !matches!(this.mode, EditorMode::SingleLine { .. });
12859
12860            if advance_downwards {
12861                let snapshot = this.buffer.read(cx).snapshot(cx);
12862
12863                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12864                    s.move_cursors_with(|display_snapshot, display_point, _| {
12865                        let mut point = display_point.to_point(display_snapshot);
12866                        point.row += 1;
12867                        point = snapshot.clip_point(point, Bias::Left);
12868                        let display_point = point.to_display_point(display_snapshot);
12869                        let goal = SelectionGoal::HorizontalPosition(
12870                            display_snapshot
12871                                .x_for_display_point(display_point, text_layout_details)
12872                                .into(),
12873                        );
12874                        (display_point, goal)
12875                    })
12876                });
12877            }
12878        });
12879    }
12880
12881    pub fn select_enclosing_symbol(
12882        &mut self,
12883        _: &SelectEnclosingSymbol,
12884        window: &mut Window,
12885        cx: &mut Context<Self>,
12886    ) {
12887        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12888
12889        let buffer = self.buffer.read(cx).snapshot(cx);
12890        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12891
12892        fn update_selection(
12893            selection: &Selection<usize>,
12894            buffer_snap: &MultiBufferSnapshot,
12895        ) -> Option<Selection<usize>> {
12896            let cursor = selection.head();
12897            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12898            for symbol in symbols.iter().rev() {
12899                let start = symbol.range.start.to_offset(buffer_snap);
12900                let end = symbol.range.end.to_offset(buffer_snap);
12901                let new_range = start..end;
12902                if start < selection.start || end > selection.end {
12903                    return Some(Selection {
12904                        id: selection.id,
12905                        start: new_range.start,
12906                        end: new_range.end,
12907                        goal: SelectionGoal::None,
12908                        reversed: selection.reversed,
12909                    });
12910                }
12911            }
12912            None
12913        }
12914
12915        let mut selected_larger_symbol = false;
12916        let new_selections = old_selections
12917            .iter()
12918            .map(|selection| match update_selection(selection, &buffer) {
12919                Some(new_selection) => {
12920                    if new_selection.range() != selection.range() {
12921                        selected_larger_symbol = true;
12922                    }
12923                    new_selection
12924                }
12925                None => selection.clone(),
12926            })
12927            .collect::<Vec<_>>();
12928
12929        if selected_larger_symbol {
12930            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12931                s.select(new_selections);
12932            });
12933        }
12934    }
12935
12936    pub fn select_larger_syntax_node(
12937        &mut self,
12938        _: &SelectLargerSyntaxNode,
12939        window: &mut Window,
12940        cx: &mut Context<Self>,
12941    ) {
12942        let Some(visible_row_count) = self.visible_row_count() else {
12943            return;
12944        };
12945        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12946        if old_selections.is_empty() {
12947            return;
12948        }
12949
12950        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12951
12952        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12953        let buffer = self.buffer.read(cx).snapshot(cx);
12954
12955        let mut selected_larger_node = false;
12956        let mut new_selections = old_selections
12957            .iter()
12958            .map(|selection| {
12959                let old_range = selection.start..selection.end;
12960
12961                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12962                    // manually select word at selection
12963                    if ["string_content", "inline"].contains(&node.kind()) {
12964                        let word_range = {
12965                            let display_point = buffer
12966                                .offset_to_point(old_range.start)
12967                                .to_display_point(&display_map);
12968                            let Range { start, end } =
12969                                movement::surrounding_word(&display_map, display_point);
12970                            start.to_point(&display_map).to_offset(&buffer)
12971                                ..end.to_point(&display_map).to_offset(&buffer)
12972                        };
12973                        // ignore if word is already selected
12974                        if !word_range.is_empty() && old_range != word_range {
12975                            let last_word_range = {
12976                                let display_point = buffer
12977                                    .offset_to_point(old_range.end)
12978                                    .to_display_point(&display_map);
12979                                let Range { start, end } =
12980                                    movement::surrounding_word(&display_map, display_point);
12981                                start.to_point(&display_map).to_offset(&buffer)
12982                                    ..end.to_point(&display_map).to_offset(&buffer)
12983                            };
12984                            // only select word if start and end point belongs to same word
12985                            if word_range == last_word_range {
12986                                selected_larger_node = true;
12987                                return Selection {
12988                                    id: selection.id,
12989                                    start: word_range.start,
12990                                    end: word_range.end,
12991                                    goal: SelectionGoal::None,
12992                                    reversed: selection.reversed,
12993                                };
12994                            }
12995                        }
12996                    }
12997                }
12998
12999                let mut new_range = old_range.clone();
13000                let mut new_node = None;
13001                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
13002                {
13003                    new_node = Some(node);
13004                    new_range = match containing_range {
13005                        MultiOrSingleBufferOffsetRange::Single(_) => break,
13006                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
13007                    };
13008                    if !display_map.intersects_fold(new_range.start)
13009                        && !display_map.intersects_fold(new_range.end)
13010                    {
13011                        break;
13012                    }
13013                }
13014
13015                if let Some(node) = new_node {
13016                    // Log the ancestor, to support using this action as a way to explore TreeSitter
13017                    // nodes. Parent and grandparent are also logged because this operation will not
13018                    // visit nodes that have the same range as their parent.
13019                    log::info!("Node: {node:?}");
13020                    let parent = node.parent();
13021                    log::info!("Parent: {parent:?}");
13022                    let grandparent = parent.and_then(|x| x.parent());
13023                    log::info!("Grandparent: {grandparent:?}");
13024                }
13025
13026                selected_larger_node |= new_range != old_range;
13027                Selection {
13028                    id: selection.id,
13029                    start: new_range.start,
13030                    end: new_range.end,
13031                    goal: SelectionGoal::None,
13032                    reversed: selection.reversed,
13033                }
13034            })
13035            .collect::<Vec<_>>();
13036
13037        if !selected_larger_node {
13038            return; // don't put this call in the history
13039        }
13040
13041        // scroll based on transformation done to the last selection created by the user
13042        let (last_old, last_new) = old_selections
13043            .last()
13044            .zip(new_selections.last().cloned())
13045            .expect("old_selections isn't empty");
13046
13047        // revert selection
13048        let is_selection_reversed = {
13049            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13050            new_selections.last_mut().expect("checked above").reversed =
13051                should_newest_selection_be_reversed;
13052            should_newest_selection_be_reversed
13053        };
13054
13055        if selected_larger_node {
13056            self.select_syntax_node_history.disable_clearing = true;
13057            self.change_selections(None, window, cx, |s| {
13058                s.select(new_selections.clone());
13059            });
13060            self.select_syntax_node_history.disable_clearing = false;
13061        }
13062
13063        let start_row = last_new.start.to_display_point(&display_map).row().0;
13064        let end_row = last_new.end.to_display_point(&display_map).row().0;
13065        let selection_height = end_row - start_row + 1;
13066        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13067
13068        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13069        let scroll_behavior = if fits_on_the_screen {
13070            self.request_autoscroll(Autoscroll::fit(), cx);
13071            SelectSyntaxNodeScrollBehavior::FitSelection
13072        } else if is_selection_reversed {
13073            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13074            SelectSyntaxNodeScrollBehavior::CursorTop
13075        } else {
13076            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13077            SelectSyntaxNodeScrollBehavior::CursorBottom
13078        };
13079
13080        self.select_syntax_node_history.push((
13081            old_selections,
13082            scroll_behavior,
13083            is_selection_reversed,
13084        ));
13085    }
13086
13087    pub fn select_smaller_syntax_node(
13088        &mut self,
13089        _: &SelectSmallerSyntaxNode,
13090        window: &mut Window,
13091        cx: &mut Context<Self>,
13092    ) {
13093        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13094
13095        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13096            self.select_syntax_node_history.pop()
13097        {
13098            if let Some(selection) = selections.last_mut() {
13099                selection.reversed = is_selection_reversed;
13100            }
13101
13102            self.select_syntax_node_history.disable_clearing = true;
13103            self.change_selections(None, window, cx, |s| {
13104                s.select(selections.to_vec());
13105            });
13106            self.select_syntax_node_history.disable_clearing = false;
13107
13108            match scroll_behavior {
13109                SelectSyntaxNodeScrollBehavior::CursorTop => {
13110                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13111                }
13112                SelectSyntaxNodeScrollBehavior::FitSelection => {
13113                    self.request_autoscroll(Autoscroll::fit(), cx);
13114                }
13115                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13116                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13117                }
13118            }
13119        }
13120    }
13121
13122    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13123        if !EditorSettings::get_global(cx).gutter.runnables {
13124            self.clear_tasks();
13125            return Task::ready(());
13126        }
13127        let project = self.project.as_ref().map(Entity::downgrade);
13128        let task_sources = self.lsp_task_sources(cx);
13129        cx.spawn_in(window, async move |editor, cx| {
13130            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13131            let Some(project) = project.and_then(|p| p.upgrade()) else {
13132                return;
13133            };
13134            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13135                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13136            }) else {
13137                return;
13138            };
13139
13140            let hide_runnables = project
13141                .update(cx, |project, cx| {
13142                    // Do not display any test indicators in non-dev server remote projects.
13143                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13144                })
13145                .unwrap_or(true);
13146            if hide_runnables {
13147                return;
13148            }
13149            let new_rows =
13150                cx.background_spawn({
13151                    let snapshot = display_snapshot.clone();
13152                    async move {
13153                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13154                    }
13155                })
13156                    .await;
13157            let Ok(lsp_tasks) =
13158                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13159            else {
13160                return;
13161            };
13162            let lsp_tasks = lsp_tasks.await;
13163
13164            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13165                lsp_tasks
13166                    .into_iter()
13167                    .flat_map(|(kind, tasks)| {
13168                        tasks.into_iter().filter_map(move |(location, task)| {
13169                            Some((kind.clone(), location?, task))
13170                        })
13171                    })
13172                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13173                        let buffer = location.target.buffer;
13174                        let buffer_snapshot = buffer.read(cx).snapshot();
13175                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13176                            |(excerpt_id, snapshot, _)| {
13177                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13178                                    display_snapshot
13179                                        .buffer_snapshot
13180                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13181                                } else {
13182                                    None
13183                                }
13184                            },
13185                        );
13186                        if let Some(offset) = offset {
13187                            let task_buffer_range =
13188                                location.target.range.to_point(&buffer_snapshot);
13189                            let context_buffer_range =
13190                                task_buffer_range.to_offset(&buffer_snapshot);
13191                            let context_range = BufferOffset(context_buffer_range.start)
13192                                ..BufferOffset(context_buffer_range.end);
13193
13194                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13195                                .or_insert_with(|| RunnableTasks {
13196                                    templates: Vec::new(),
13197                                    offset,
13198                                    column: task_buffer_range.start.column,
13199                                    extra_variables: HashMap::default(),
13200                                    context_range,
13201                                })
13202                                .templates
13203                                .push((kind, task.original_task().clone()));
13204                        }
13205
13206                        acc
13207                    })
13208            }) else {
13209                return;
13210            };
13211
13212            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13213            editor
13214                .update(cx, |editor, _| {
13215                    editor.clear_tasks();
13216                    for (key, mut value) in rows {
13217                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13218                            value.templates.extend(lsp_tasks.templates);
13219                        }
13220
13221                        editor.insert_tasks(key, value);
13222                    }
13223                    for (key, value) in lsp_tasks_by_rows {
13224                        editor.insert_tasks(key, value);
13225                    }
13226                })
13227                .ok();
13228        })
13229    }
13230    fn fetch_runnable_ranges(
13231        snapshot: &DisplaySnapshot,
13232        range: Range<Anchor>,
13233    ) -> Vec<language::RunnableRange> {
13234        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13235    }
13236
13237    fn runnable_rows(
13238        project: Entity<Project>,
13239        snapshot: DisplaySnapshot,
13240        runnable_ranges: Vec<RunnableRange>,
13241        mut cx: AsyncWindowContext,
13242    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13243        runnable_ranges
13244            .into_iter()
13245            .filter_map(|mut runnable| {
13246                let tasks = cx
13247                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13248                    .ok()?;
13249                if tasks.is_empty() {
13250                    return None;
13251                }
13252
13253                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13254
13255                let row = snapshot
13256                    .buffer_snapshot
13257                    .buffer_line_for_row(MultiBufferRow(point.row))?
13258                    .1
13259                    .start
13260                    .row;
13261
13262                let context_range =
13263                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13264                Some((
13265                    (runnable.buffer_id, row),
13266                    RunnableTasks {
13267                        templates: tasks,
13268                        offset: snapshot
13269                            .buffer_snapshot
13270                            .anchor_before(runnable.run_range.start),
13271                        context_range,
13272                        column: point.column,
13273                        extra_variables: runnable.extra_captures,
13274                    },
13275                ))
13276            })
13277            .collect()
13278    }
13279
13280    fn templates_with_tags(
13281        project: &Entity<Project>,
13282        runnable: &mut Runnable,
13283        cx: &mut App,
13284    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13285        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13286            let (worktree_id, file) = project
13287                .buffer_for_id(runnable.buffer, cx)
13288                .and_then(|buffer| buffer.read(cx).file())
13289                .map(|file| (file.worktree_id(cx), file.clone()))
13290                .unzip();
13291
13292            (
13293                project.task_store().read(cx).task_inventory().cloned(),
13294                worktree_id,
13295                file,
13296            )
13297        });
13298
13299        let mut templates_with_tags = mem::take(&mut runnable.tags)
13300            .into_iter()
13301            .flat_map(|RunnableTag(tag)| {
13302                inventory
13303                    .as_ref()
13304                    .into_iter()
13305                    .flat_map(|inventory| {
13306                        inventory.read(cx).list_tasks(
13307                            file.clone(),
13308                            Some(runnable.language.clone()),
13309                            worktree_id,
13310                            cx,
13311                        )
13312                    })
13313                    .filter(move |(_, template)| {
13314                        template.tags.iter().any(|source_tag| source_tag == &tag)
13315                    })
13316            })
13317            .sorted_by_key(|(kind, _)| kind.to_owned())
13318            .collect::<Vec<_>>();
13319        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13320            // Strongest source wins; if we have worktree tag binding, prefer that to
13321            // global and language bindings;
13322            // if we have a global binding, prefer that to language binding.
13323            let first_mismatch = templates_with_tags
13324                .iter()
13325                .position(|(tag_source, _)| tag_source != leading_tag_source);
13326            if let Some(index) = first_mismatch {
13327                templates_with_tags.truncate(index);
13328            }
13329        }
13330
13331        templates_with_tags
13332    }
13333
13334    pub fn move_to_enclosing_bracket(
13335        &mut self,
13336        _: &MoveToEnclosingBracket,
13337        window: &mut Window,
13338        cx: &mut Context<Self>,
13339    ) {
13340        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13342            s.move_offsets_with(|snapshot, selection| {
13343                let Some(enclosing_bracket_ranges) =
13344                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13345                else {
13346                    return;
13347                };
13348
13349                let mut best_length = usize::MAX;
13350                let mut best_inside = false;
13351                let mut best_in_bracket_range = false;
13352                let mut best_destination = None;
13353                for (open, close) in enclosing_bracket_ranges {
13354                    let close = close.to_inclusive();
13355                    let length = close.end() - open.start;
13356                    let inside = selection.start >= open.end && selection.end <= *close.start();
13357                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13358                        || close.contains(&selection.head());
13359
13360                    // If best is next to a bracket and current isn't, skip
13361                    if !in_bracket_range && best_in_bracket_range {
13362                        continue;
13363                    }
13364
13365                    // Prefer smaller lengths unless best is inside and current isn't
13366                    if length > best_length && (best_inside || !inside) {
13367                        continue;
13368                    }
13369
13370                    best_length = length;
13371                    best_inside = inside;
13372                    best_in_bracket_range = in_bracket_range;
13373                    best_destination = Some(
13374                        if close.contains(&selection.start) && close.contains(&selection.end) {
13375                            if inside { open.end } else { open.start }
13376                        } else if inside {
13377                            *close.start()
13378                        } else {
13379                            *close.end()
13380                        },
13381                    );
13382                }
13383
13384                if let Some(destination) = best_destination {
13385                    selection.collapse_to(destination, SelectionGoal::None);
13386                }
13387            })
13388        });
13389    }
13390
13391    pub fn undo_selection(
13392        &mut self,
13393        _: &UndoSelection,
13394        window: &mut Window,
13395        cx: &mut Context<Self>,
13396    ) {
13397        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13398        self.end_selection(window, cx);
13399        self.selection_history.mode = SelectionHistoryMode::Undoing;
13400        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13401            self.change_selections(None, window, cx, |s| {
13402                s.select_anchors(entry.selections.to_vec())
13403            });
13404            self.select_next_state = entry.select_next_state;
13405            self.select_prev_state = entry.select_prev_state;
13406            self.add_selections_state = entry.add_selections_state;
13407            self.request_autoscroll(Autoscroll::newest(), cx);
13408        }
13409        self.selection_history.mode = SelectionHistoryMode::Normal;
13410    }
13411
13412    pub fn redo_selection(
13413        &mut self,
13414        _: &RedoSelection,
13415        window: &mut Window,
13416        cx: &mut Context<Self>,
13417    ) {
13418        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13419        self.end_selection(window, cx);
13420        self.selection_history.mode = SelectionHistoryMode::Redoing;
13421        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13422            self.change_selections(None, window, cx, |s| {
13423                s.select_anchors(entry.selections.to_vec())
13424            });
13425            self.select_next_state = entry.select_next_state;
13426            self.select_prev_state = entry.select_prev_state;
13427            self.add_selections_state = entry.add_selections_state;
13428            self.request_autoscroll(Autoscroll::newest(), cx);
13429        }
13430        self.selection_history.mode = SelectionHistoryMode::Normal;
13431    }
13432
13433    pub fn expand_excerpts(
13434        &mut self,
13435        action: &ExpandExcerpts,
13436        _: &mut Window,
13437        cx: &mut Context<Self>,
13438    ) {
13439        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13440    }
13441
13442    pub fn expand_excerpts_down(
13443        &mut self,
13444        action: &ExpandExcerptsDown,
13445        _: &mut Window,
13446        cx: &mut Context<Self>,
13447    ) {
13448        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13449    }
13450
13451    pub fn expand_excerpts_up(
13452        &mut self,
13453        action: &ExpandExcerptsUp,
13454        _: &mut Window,
13455        cx: &mut Context<Self>,
13456    ) {
13457        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13458    }
13459
13460    pub fn expand_excerpts_for_direction(
13461        &mut self,
13462        lines: u32,
13463        direction: ExpandExcerptDirection,
13464
13465        cx: &mut Context<Self>,
13466    ) {
13467        let selections = self.selections.disjoint_anchors();
13468
13469        let lines = if lines == 0 {
13470            EditorSettings::get_global(cx).expand_excerpt_lines
13471        } else {
13472            lines
13473        };
13474
13475        self.buffer.update(cx, |buffer, cx| {
13476            let snapshot = buffer.snapshot(cx);
13477            let mut excerpt_ids = selections
13478                .iter()
13479                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13480                .collect::<Vec<_>>();
13481            excerpt_ids.sort();
13482            excerpt_ids.dedup();
13483            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13484        })
13485    }
13486
13487    pub fn expand_excerpt(
13488        &mut self,
13489        excerpt: ExcerptId,
13490        direction: ExpandExcerptDirection,
13491        window: &mut Window,
13492        cx: &mut Context<Self>,
13493    ) {
13494        let current_scroll_position = self.scroll_position(cx);
13495        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13496        let mut should_scroll_up = false;
13497
13498        if direction == ExpandExcerptDirection::Down {
13499            let multi_buffer = self.buffer.read(cx);
13500            let snapshot = multi_buffer.snapshot(cx);
13501            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13502                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13503                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13504                        let buffer_snapshot = buffer.read(cx).snapshot();
13505                        let excerpt_end_row =
13506                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13507                        let last_row = buffer_snapshot.max_point().row;
13508                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13509                        should_scroll_up = lines_below >= lines_to_expand;
13510                    }
13511                }
13512            }
13513        }
13514
13515        self.buffer.update(cx, |buffer, cx| {
13516            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13517        });
13518
13519        if should_scroll_up {
13520            let new_scroll_position =
13521                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13522            self.set_scroll_position(new_scroll_position, window, cx);
13523        }
13524    }
13525
13526    pub fn go_to_singleton_buffer_point(
13527        &mut self,
13528        point: Point,
13529        window: &mut Window,
13530        cx: &mut Context<Self>,
13531    ) {
13532        self.go_to_singleton_buffer_range(point..point, window, cx);
13533    }
13534
13535    pub fn go_to_singleton_buffer_range(
13536        &mut self,
13537        range: Range<Point>,
13538        window: &mut Window,
13539        cx: &mut Context<Self>,
13540    ) {
13541        let multibuffer = self.buffer().read(cx);
13542        let Some(buffer) = multibuffer.as_singleton() else {
13543            return;
13544        };
13545        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13546            return;
13547        };
13548        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13549            return;
13550        };
13551        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13552            s.select_anchor_ranges([start..end])
13553        });
13554    }
13555
13556    pub fn go_to_diagnostic(
13557        &mut self,
13558        _: &GoToDiagnostic,
13559        window: &mut Window,
13560        cx: &mut Context<Self>,
13561    ) {
13562        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13563        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13564    }
13565
13566    pub fn go_to_prev_diagnostic(
13567        &mut self,
13568        _: &GoToPreviousDiagnostic,
13569        window: &mut Window,
13570        cx: &mut Context<Self>,
13571    ) {
13572        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13573        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13574    }
13575
13576    pub fn go_to_diagnostic_impl(
13577        &mut self,
13578        direction: Direction,
13579        window: &mut Window,
13580        cx: &mut Context<Self>,
13581    ) {
13582        let buffer = self.buffer.read(cx).snapshot(cx);
13583        let selection = self.selections.newest::<usize>(cx);
13584
13585        let mut active_group_id = None;
13586        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13587            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13588                active_group_id = Some(active_group.group_id);
13589            }
13590        }
13591
13592        fn filtered(
13593            snapshot: EditorSnapshot,
13594            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13595        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13596            diagnostics
13597                .filter(|entry| entry.range.start != entry.range.end)
13598                .filter(|entry| !entry.diagnostic.is_unnecessary)
13599                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13600        }
13601
13602        let snapshot = self.snapshot(window, cx);
13603        let before = filtered(
13604            snapshot.clone(),
13605            buffer
13606                .diagnostics_in_range(0..selection.start)
13607                .filter(|entry| entry.range.start <= selection.start),
13608        );
13609        let after = filtered(
13610            snapshot,
13611            buffer
13612                .diagnostics_in_range(selection.start..buffer.len())
13613                .filter(|entry| entry.range.start >= selection.start),
13614        );
13615
13616        let mut found: Option<DiagnosticEntry<usize>> = None;
13617        if direction == Direction::Prev {
13618            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13619            {
13620                for diagnostic in prev_diagnostics.into_iter().rev() {
13621                    if diagnostic.range.start != selection.start
13622                        || active_group_id
13623                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13624                    {
13625                        found = Some(diagnostic);
13626                        break 'outer;
13627                    }
13628                }
13629            }
13630        } else {
13631            for diagnostic in after.chain(before) {
13632                if diagnostic.range.start != selection.start
13633                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13634                {
13635                    found = Some(diagnostic);
13636                    break;
13637                }
13638            }
13639        }
13640        let Some(next_diagnostic) = found else {
13641            return;
13642        };
13643
13644        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13645            return;
13646        };
13647        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13648            s.select_ranges(vec![
13649                next_diagnostic.range.start..next_diagnostic.range.start,
13650            ])
13651        });
13652        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13653        self.refresh_inline_completion(false, true, window, cx);
13654    }
13655
13656    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13657        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13658        let snapshot = self.snapshot(window, cx);
13659        let selection = self.selections.newest::<Point>(cx);
13660        self.go_to_hunk_before_or_after_position(
13661            &snapshot,
13662            selection.head(),
13663            Direction::Next,
13664            window,
13665            cx,
13666        );
13667    }
13668
13669    pub fn go_to_hunk_before_or_after_position(
13670        &mut self,
13671        snapshot: &EditorSnapshot,
13672        position: Point,
13673        direction: Direction,
13674        window: &mut Window,
13675        cx: &mut Context<Editor>,
13676    ) {
13677        let row = if direction == Direction::Next {
13678            self.hunk_after_position(snapshot, position)
13679                .map(|hunk| hunk.row_range.start)
13680        } else {
13681            self.hunk_before_position(snapshot, position)
13682        };
13683
13684        if let Some(row) = row {
13685            let destination = Point::new(row.0, 0);
13686            let autoscroll = Autoscroll::center();
13687
13688            self.unfold_ranges(&[destination..destination], false, false, cx);
13689            self.change_selections(Some(autoscroll), window, cx, |s| {
13690                s.select_ranges([destination..destination]);
13691            });
13692        }
13693    }
13694
13695    fn hunk_after_position(
13696        &mut self,
13697        snapshot: &EditorSnapshot,
13698        position: Point,
13699    ) -> Option<MultiBufferDiffHunk> {
13700        snapshot
13701            .buffer_snapshot
13702            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13703            .find(|hunk| hunk.row_range.start.0 > position.row)
13704            .or_else(|| {
13705                snapshot
13706                    .buffer_snapshot
13707                    .diff_hunks_in_range(Point::zero()..position)
13708                    .find(|hunk| hunk.row_range.end.0 < position.row)
13709            })
13710    }
13711
13712    fn go_to_prev_hunk(
13713        &mut self,
13714        _: &GoToPreviousHunk,
13715        window: &mut Window,
13716        cx: &mut Context<Self>,
13717    ) {
13718        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13719        let snapshot = self.snapshot(window, cx);
13720        let selection = self.selections.newest::<Point>(cx);
13721        self.go_to_hunk_before_or_after_position(
13722            &snapshot,
13723            selection.head(),
13724            Direction::Prev,
13725            window,
13726            cx,
13727        );
13728    }
13729
13730    fn hunk_before_position(
13731        &mut self,
13732        snapshot: &EditorSnapshot,
13733        position: Point,
13734    ) -> Option<MultiBufferRow> {
13735        snapshot
13736            .buffer_snapshot
13737            .diff_hunk_before(position)
13738            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13739    }
13740
13741    fn go_to_next_change(
13742        &mut self,
13743        _: &GoToNextChange,
13744        window: &mut Window,
13745        cx: &mut Context<Self>,
13746    ) {
13747        if let Some(selections) = self
13748            .change_list
13749            .next_change(1, Direction::Next)
13750            .map(|s| s.to_vec())
13751        {
13752            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13753                let map = s.display_map();
13754                s.select_display_ranges(selections.iter().map(|a| {
13755                    let point = a.to_display_point(&map);
13756                    point..point
13757                }))
13758            })
13759        }
13760    }
13761
13762    fn go_to_previous_change(
13763        &mut self,
13764        _: &GoToPreviousChange,
13765        window: &mut Window,
13766        cx: &mut Context<Self>,
13767    ) {
13768        if let Some(selections) = self
13769            .change_list
13770            .next_change(1, Direction::Prev)
13771            .map(|s| s.to_vec())
13772        {
13773            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13774                let map = s.display_map();
13775                s.select_display_ranges(selections.iter().map(|a| {
13776                    let point = a.to_display_point(&map);
13777                    point..point
13778                }))
13779            })
13780        }
13781    }
13782
13783    fn go_to_line<T: 'static>(
13784        &mut self,
13785        position: Anchor,
13786        highlight_color: Option<Hsla>,
13787        window: &mut Window,
13788        cx: &mut Context<Self>,
13789    ) {
13790        let snapshot = self.snapshot(window, cx).display_snapshot;
13791        let position = position.to_point(&snapshot.buffer_snapshot);
13792        let start = snapshot
13793            .buffer_snapshot
13794            .clip_point(Point::new(position.row, 0), Bias::Left);
13795        let end = start + Point::new(1, 0);
13796        let start = snapshot.buffer_snapshot.anchor_before(start);
13797        let end = snapshot.buffer_snapshot.anchor_before(end);
13798
13799        self.highlight_rows::<T>(
13800            start..end,
13801            highlight_color
13802                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13803            Default::default(),
13804            cx,
13805        );
13806        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13807    }
13808
13809    pub fn go_to_definition(
13810        &mut self,
13811        _: &GoToDefinition,
13812        window: &mut Window,
13813        cx: &mut Context<Self>,
13814    ) -> Task<Result<Navigated>> {
13815        let definition =
13816            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13817        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13818        cx.spawn_in(window, async move |editor, cx| {
13819            if definition.await? == Navigated::Yes {
13820                return Ok(Navigated::Yes);
13821            }
13822            match fallback_strategy {
13823                GoToDefinitionFallback::None => Ok(Navigated::No),
13824                GoToDefinitionFallback::FindAllReferences => {
13825                    match editor.update_in(cx, |editor, window, cx| {
13826                        editor.find_all_references(&FindAllReferences, window, cx)
13827                    })? {
13828                        Some(references) => references.await,
13829                        None => Ok(Navigated::No),
13830                    }
13831                }
13832            }
13833        })
13834    }
13835
13836    pub fn go_to_declaration(
13837        &mut self,
13838        _: &GoToDeclaration,
13839        window: &mut Window,
13840        cx: &mut Context<Self>,
13841    ) -> Task<Result<Navigated>> {
13842        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13843    }
13844
13845    pub fn go_to_declaration_split(
13846        &mut self,
13847        _: &GoToDeclaration,
13848        window: &mut Window,
13849        cx: &mut Context<Self>,
13850    ) -> Task<Result<Navigated>> {
13851        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13852    }
13853
13854    pub fn go_to_implementation(
13855        &mut self,
13856        _: &GoToImplementation,
13857        window: &mut Window,
13858        cx: &mut Context<Self>,
13859    ) -> Task<Result<Navigated>> {
13860        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13861    }
13862
13863    pub fn go_to_implementation_split(
13864        &mut self,
13865        _: &GoToImplementationSplit,
13866        window: &mut Window,
13867        cx: &mut Context<Self>,
13868    ) -> Task<Result<Navigated>> {
13869        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13870    }
13871
13872    pub fn go_to_type_definition(
13873        &mut self,
13874        _: &GoToTypeDefinition,
13875        window: &mut Window,
13876        cx: &mut Context<Self>,
13877    ) -> Task<Result<Navigated>> {
13878        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13879    }
13880
13881    pub fn go_to_definition_split(
13882        &mut self,
13883        _: &GoToDefinitionSplit,
13884        window: &mut Window,
13885        cx: &mut Context<Self>,
13886    ) -> Task<Result<Navigated>> {
13887        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13888    }
13889
13890    pub fn go_to_type_definition_split(
13891        &mut self,
13892        _: &GoToTypeDefinitionSplit,
13893        window: &mut Window,
13894        cx: &mut Context<Self>,
13895    ) -> Task<Result<Navigated>> {
13896        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13897    }
13898
13899    fn go_to_definition_of_kind(
13900        &mut self,
13901        kind: GotoDefinitionKind,
13902        split: bool,
13903        window: &mut Window,
13904        cx: &mut Context<Self>,
13905    ) -> Task<Result<Navigated>> {
13906        let Some(provider) = self.semantics_provider.clone() else {
13907            return Task::ready(Ok(Navigated::No));
13908        };
13909        let head = self.selections.newest::<usize>(cx).head();
13910        let buffer = self.buffer.read(cx);
13911        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13912            text_anchor
13913        } else {
13914            return Task::ready(Ok(Navigated::No));
13915        };
13916
13917        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13918            return Task::ready(Ok(Navigated::No));
13919        };
13920
13921        cx.spawn_in(window, async move |editor, cx| {
13922            let definitions = definitions.await?;
13923            let navigated = editor
13924                .update_in(cx, |editor, window, cx| {
13925                    editor.navigate_to_hover_links(
13926                        Some(kind),
13927                        definitions
13928                            .into_iter()
13929                            .filter(|location| {
13930                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13931                            })
13932                            .map(HoverLink::Text)
13933                            .collect::<Vec<_>>(),
13934                        split,
13935                        window,
13936                        cx,
13937                    )
13938                })?
13939                .await?;
13940            anyhow::Ok(navigated)
13941        })
13942    }
13943
13944    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13945        let selection = self.selections.newest_anchor();
13946        let head = selection.head();
13947        let tail = selection.tail();
13948
13949        let Some((buffer, start_position)) =
13950            self.buffer.read(cx).text_anchor_for_position(head, cx)
13951        else {
13952            return;
13953        };
13954
13955        let end_position = if head != tail {
13956            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13957                return;
13958            };
13959            Some(pos)
13960        } else {
13961            None
13962        };
13963
13964        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13965            let url = if let Some(end_pos) = end_position {
13966                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13967            } else {
13968                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13969            };
13970
13971            if let Some(url) = url {
13972                editor.update(cx, |_, cx| {
13973                    cx.open_url(&url);
13974                })
13975            } else {
13976                Ok(())
13977            }
13978        });
13979
13980        url_finder.detach();
13981    }
13982
13983    pub fn open_selected_filename(
13984        &mut self,
13985        _: &OpenSelectedFilename,
13986        window: &mut Window,
13987        cx: &mut Context<Self>,
13988    ) {
13989        let Some(workspace) = self.workspace() else {
13990            return;
13991        };
13992
13993        let position = self.selections.newest_anchor().head();
13994
13995        let Some((buffer, buffer_position)) =
13996            self.buffer.read(cx).text_anchor_for_position(position, cx)
13997        else {
13998            return;
13999        };
14000
14001        let project = self.project.clone();
14002
14003        cx.spawn_in(window, async move |_, cx| {
14004            let result = find_file(&buffer, project, buffer_position, cx).await;
14005
14006            if let Some((_, path)) = result {
14007                workspace
14008                    .update_in(cx, |workspace, window, cx| {
14009                        workspace.open_resolved_path(path, window, cx)
14010                    })?
14011                    .await?;
14012            }
14013            anyhow::Ok(())
14014        })
14015        .detach();
14016    }
14017
14018    pub(crate) fn navigate_to_hover_links(
14019        &mut self,
14020        kind: Option<GotoDefinitionKind>,
14021        mut definitions: Vec<HoverLink>,
14022        split: bool,
14023        window: &mut Window,
14024        cx: &mut Context<Editor>,
14025    ) -> Task<Result<Navigated>> {
14026        // If there is one definition, just open it directly
14027        if definitions.len() == 1 {
14028            let definition = definitions.pop().unwrap();
14029
14030            enum TargetTaskResult {
14031                Location(Option<Location>),
14032                AlreadyNavigated,
14033            }
14034
14035            let target_task = match definition {
14036                HoverLink::Text(link) => {
14037                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14038                }
14039                HoverLink::InlayHint(lsp_location, server_id) => {
14040                    let computation =
14041                        self.compute_target_location(lsp_location, server_id, window, cx);
14042                    cx.background_spawn(async move {
14043                        let location = computation.await?;
14044                        Ok(TargetTaskResult::Location(location))
14045                    })
14046                }
14047                HoverLink::Url(url) => {
14048                    cx.open_url(&url);
14049                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14050                }
14051                HoverLink::File(path) => {
14052                    if let Some(workspace) = self.workspace() {
14053                        cx.spawn_in(window, async move |_, cx| {
14054                            workspace
14055                                .update_in(cx, |workspace, window, cx| {
14056                                    workspace.open_resolved_path(path, window, cx)
14057                                })?
14058                                .await
14059                                .map(|_| TargetTaskResult::AlreadyNavigated)
14060                        })
14061                    } else {
14062                        Task::ready(Ok(TargetTaskResult::Location(None)))
14063                    }
14064                }
14065            };
14066            cx.spawn_in(window, async move |editor, cx| {
14067                let target = match target_task.await.context("target resolution task")? {
14068                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14069                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14070                    TargetTaskResult::Location(Some(target)) => target,
14071                };
14072
14073                editor.update_in(cx, |editor, window, cx| {
14074                    let Some(workspace) = editor.workspace() else {
14075                        return Navigated::No;
14076                    };
14077                    let pane = workspace.read(cx).active_pane().clone();
14078
14079                    let range = target.range.to_point(target.buffer.read(cx));
14080                    let range = editor.range_for_match(&range);
14081                    let range = collapse_multiline_range(range);
14082
14083                    if !split
14084                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14085                    {
14086                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14087                    } else {
14088                        window.defer(cx, move |window, cx| {
14089                            let target_editor: Entity<Self> =
14090                                workspace.update(cx, |workspace, cx| {
14091                                    let pane = if split {
14092                                        workspace.adjacent_pane(window, cx)
14093                                    } else {
14094                                        workspace.active_pane().clone()
14095                                    };
14096
14097                                    workspace.open_project_item(
14098                                        pane,
14099                                        target.buffer.clone(),
14100                                        true,
14101                                        true,
14102                                        window,
14103                                        cx,
14104                                    )
14105                                });
14106                            target_editor.update(cx, |target_editor, cx| {
14107                                // When selecting a definition in a different buffer, disable the nav history
14108                                // to avoid creating a history entry at the previous cursor location.
14109                                pane.update(cx, |pane, _| pane.disable_history());
14110                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14111                                pane.update(cx, |pane, _| pane.enable_history());
14112                            });
14113                        });
14114                    }
14115                    Navigated::Yes
14116                })
14117            })
14118        } else if !definitions.is_empty() {
14119            cx.spawn_in(window, async move |editor, cx| {
14120                let (title, location_tasks, workspace) = editor
14121                    .update_in(cx, |editor, window, cx| {
14122                        let tab_kind = match kind {
14123                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14124                            _ => "Definitions",
14125                        };
14126                        let title = definitions
14127                            .iter()
14128                            .find_map(|definition| match definition {
14129                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14130                                    let buffer = origin.buffer.read(cx);
14131                                    format!(
14132                                        "{} for {}",
14133                                        tab_kind,
14134                                        buffer
14135                                            .text_for_range(origin.range.clone())
14136                                            .collect::<String>()
14137                                    )
14138                                }),
14139                                HoverLink::InlayHint(_, _) => None,
14140                                HoverLink::Url(_) => None,
14141                                HoverLink::File(_) => None,
14142                            })
14143                            .unwrap_or(tab_kind.to_string());
14144                        let location_tasks = definitions
14145                            .into_iter()
14146                            .map(|definition| match definition {
14147                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14148                                HoverLink::InlayHint(lsp_location, server_id) => editor
14149                                    .compute_target_location(lsp_location, server_id, window, cx),
14150                                HoverLink::Url(_) => Task::ready(Ok(None)),
14151                                HoverLink::File(_) => Task::ready(Ok(None)),
14152                            })
14153                            .collect::<Vec<_>>();
14154                        (title, location_tasks, editor.workspace().clone())
14155                    })
14156                    .context("location tasks preparation")?;
14157
14158                let locations = future::join_all(location_tasks)
14159                    .await
14160                    .into_iter()
14161                    .filter_map(|location| location.transpose())
14162                    .collect::<Result<_>>()
14163                    .context("location tasks")?;
14164
14165                let Some(workspace) = workspace else {
14166                    return Ok(Navigated::No);
14167                };
14168                let opened = workspace
14169                    .update_in(cx, |workspace, window, cx| {
14170                        Self::open_locations_in_multibuffer(
14171                            workspace,
14172                            locations,
14173                            title,
14174                            split,
14175                            MultibufferSelectionMode::First,
14176                            window,
14177                            cx,
14178                        )
14179                    })
14180                    .ok();
14181
14182                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14183            })
14184        } else {
14185            Task::ready(Ok(Navigated::No))
14186        }
14187    }
14188
14189    fn compute_target_location(
14190        &self,
14191        lsp_location: lsp::Location,
14192        server_id: LanguageServerId,
14193        window: &mut Window,
14194        cx: &mut Context<Self>,
14195    ) -> Task<anyhow::Result<Option<Location>>> {
14196        let Some(project) = self.project.clone() else {
14197            return Task::ready(Ok(None));
14198        };
14199
14200        cx.spawn_in(window, async move |editor, cx| {
14201            let location_task = editor.update(cx, |_, cx| {
14202                project.update(cx, |project, cx| {
14203                    let language_server_name = project
14204                        .language_server_statuses(cx)
14205                        .find(|(id, _)| server_id == *id)
14206                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14207                    language_server_name.map(|language_server_name| {
14208                        project.open_local_buffer_via_lsp(
14209                            lsp_location.uri.clone(),
14210                            server_id,
14211                            language_server_name,
14212                            cx,
14213                        )
14214                    })
14215                })
14216            })?;
14217            let location = match location_task {
14218                Some(task) => Some({
14219                    let target_buffer_handle = task.await.context("open local buffer")?;
14220                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14221                        let target_start = target_buffer
14222                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14223                        let target_end = target_buffer
14224                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14225                        target_buffer.anchor_after(target_start)
14226                            ..target_buffer.anchor_before(target_end)
14227                    })?;
14228                    Location {
14229                        buffer: target_buffer_handle,
14230                        range,
14231                    }
14232                }),
14233                None => None,
14234            };
14235            Ok(location)
14236        })
14237    }
14238
14239    pub fn find_all_references(
14240        &mut self,
14241        _: &FindAllReferences,
14242        window: &mut Window,
14243        cx: &mut Context<Self>,
14244    ) -> Option<Task<Result<Navigated>>> {
14245        let selection = self.selections.newest::<usize>(cx);
14246        let multi_buffer = self.buffer.read(cx);
14247        let head = selection.head();
14248
14249        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14250        let head_anchor = multi_buffer_snapshot.anchor_at(
14251            head,
14252            if head < selection.tail() {
14253                Bias::Right
14254            } else {
14255                Bias::Left
14256            },
14257        );
14258
14259        match self
14260            .find_all_references_task_sources
14261            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14262        {
14263            Ok(_) => {
14264                log::info!(
14265                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14266                );
14267                return None;
14268            }
14269            Err(i) => {
14270                self.find_all_references_task_sources.insert(i, head_anchor);
14271            }
14272        }
14273
14274        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14275        let workspace = self.workspace()?;
14276        let project = workspace.read(cx).project().clone();
14277        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14278        Some(cx.spawn_in(window, async move |editor, cx| {
14279            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14280                if let Ok(i) = editor
14281                    .find_all_references_task_sources
14282                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14283                {
14284                    editor.find_all_references_task_sources.remove(i);
14285                }
14286            });
14287
14288            let locations = references.await?;
14289            if locations.is_empty() {
14290                return anyhow::Ok(Navigated::No);
14291            }
14292
14293            workspace.update_in(cx, |workspace, window, cx| {
14294                let title = locations
14295                    .first()
14296                    .as_ref()
14297                    .map(|location| {
14298                        let buffer = location.buffer.read(cx);
14299                        format!(
14300                            "References to `{}`",
14301                            buffer
14302                                .text_for_range(location.range.clone())
14303                                .collect::<String>()
14304                        )
14305                    })
14306                    .unwrap();
14307                Self::open_locations_in_multibuffer(
14308                    workspace,
14309                    locations,
14310                    title,
14311                    false,
14312                    MultibufferSelectionMode::First,
14313                    window,
14314                    cx,
14315                );
14316                Navigated::Yes
14317            })
14318        }))
14319    }
14320
14321    /// Opens a multibuffer with the given project locations in it
14322    pub fn open_locations_in_multibuffer(
14323        workspace: &mut Workspace,
14324        mut locations: Vec<Location>,
14325        title: String,
14326        split: bool,
14327        multibuffer_selection_mode: MultibufferSelectionMode,
14328        window: &mut Window,
14329        cx: &mut Context<Workspace>,
14330    ) {
14331        // If there are multiple definitions, open them in a multibuffer
14332        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14333        let mut locations = locations.into_iter().peekable();
14334        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14335        let capability = workspace.project().read(cx).capability();
14336
14337        let excerpt_buffer = cx.new(|cx| {
14338            let mut multibuffer = MultiBuffer::new(capability);
14339            while let Some(location) = locations.next() {
14340                let buffer = location.buffer.read(cx);
14341                let mut ranges_for_buffer = Vec::new();
14342                let range = location.range.to_point(buffer);
14343                ranges_for_buffer.push(range.clone());
14344
14345                while let Some(next_location) = locations.peek() {
14346                    if next_location.buffer == location.buffer {
14347                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14348                        locations.next();
14349                    } else {
14350                        break;
14351                    }
14352                }
14353
14354                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14355                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14356                    PathKey::for_buffer(&location.buffer, cx),
14357                    location.buffer.clone(),
14358                    ranges_for_buffer,
14359                    DEFAULT_MULTIBUFFER_CONTEXT,
14360                    cx,
14361                );
14362                ranges.extend(new_ranges)
14363            }
14364
14365            multibuffer.with_title(title)
14366        });
14367
14368        let editor = cx.new(|cx| {
14369            Editor::for_multibuffer(
14370                excerpt_buffer,
14371                Some(workspace.project().clone()),
14372                window,
14373                cx,
14374            )
14375        });
14376        editor.update(cx, |editor, cx| {
14377            match multibuffer_selection_mode {
14378                MultibufferSelectionMode::First => {
14379                    if let Some(first_range) = ranges.first() {
14380                        editor.change_selections(None, window, cx, |selections| {
14381                            selections.clear_disjoint();
14382                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14383                        });
14384                    }
14385                    editor.highlight_background::<Self>(
14386                        &ranges,
14387                        |theme| theme.editor_highlighted_line_background,
14388                        cx,
14389                    );
14390                }
14391                MultibufferSelectionMode::All => {
14392                    editor.change_selections(None, window, cx, |selections| {
14393                        selections.clear_disjoint();
14394                        selections.select_anchor_ranges(ranges);
14395                    });
14396                }
14397            }
14398            editor.register_buffers_with_language_servers(cx);
14399        });
14400
14401        let item = Box::new(editor);
14402        let item_id = item.item_id();
14403
14404        if split {
14405            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14406        } else {
14407            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14408                let (preview_item_id, preview_item_idx) =
14409                    workspace.active_pane().update(cx, |pane, _| {
14410                        (pane.preview_item_id(), pane.preview_item_idx())
14411                    });
14412
14413                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14414
14415                if let Some(preview_item_id) = preview_item_id {
14416                    workspace.active_pane().update(cx, |pane, cx| {
14417                        pane.remove_item(preview_item_id, false, false, window, cx);
14418                    });
14419                }
14420            } else {
14421                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14422            }
14423        }
14424        workspace.active_pane().update(cx, |pane, cx| {
14425            pane.set_preview_item_id(Some(item_id), cx);
14426        });
14427    }
14428
14429    pub fn rename(
14430        &mut self,
14431        _: &Rename,
14432        window: &mut Window,
14433        cx: &mut Context<Self>,
14434    ) -> Option<Task<Result<()>>> {
14435        use language::ToOffset as _;
14436
14437        let provider = self.semantics_provider.clone()?;
14438        let selection = self.selections.newest_anchor().clone();
14439        let (cursor_buffer, cursor_buffer_position) = self
14440            .buffer
14441            .read(cx)
14442            .text_anchor_for_position(selection.head(), cx)?;
14443        let (tail_buffer, cursor_buffer_position_end) = self
14444            .buffer
14445            .read(cx)
14446            .text_anchor_for_position(selection.tail(), cx)?;
14447        if tail_buffer != cursor_buffer {
14448            return None;
14449        }
14450
14451        let snapshot = cursor_buffer.read(cx).snapshot();
14452        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14453        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14454        let prepare_rename = provider
14455            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14456            .unwrap_or_else(|| Task::ready(Ok(None)));
14457        drop(snapshot);
14458
14459        Some(cx.spawn_in(window, async move |this, cx| {
14460            let rename_range = if let Some(range) = prepare_rename.await? {
14461                Some(range)
14462            } else {
14463                this.update(cx, |this, cx| {
14464                    let buffer = this.buffer.read(cx).snapshot(cx);
14465                    let mut buffer_highlights = this
14466                        .document_highlights_for_position(selection.head(), &buffer)
14467                        .filter(|highlight| {
14468                            highlight.start.excerpt_id == selection.head().excerpt_id
14469                                && highlight.end.excerpt_id == selection.head().excerpt_id
14470                        });
14471                    buffer_highlights
14472                        .next()
14473                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14474                })?
14475            };
14476            if let Some(rename_range) = rename_range {
14477                this.update_in(cx, |this, window, cx| {
14478                    let snapshot = cursor_buffer.read(cx).snapshot();
14479                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14480                    let cursor_offset_in_rename_range =
14481                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14482                    let cursor_offset_in_rename_range_end =
14483                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14484
14485                    this.take_rename(false, window, cx);
14486                    let buffer = this.buffer.read(cx).read(cx);
14487                    let cursor_offset = selection.head().to_offset(&buffer);
14488                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14489                    let rename_end = rename_start + rename_buffer_range.len();
14490                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14491                    let mut old_highlight_id = None;
14492                    let old_name: Arc<str> = buffer
14493                        .chunks(rename_start..rename_end, true)
14494                        .map(|chunk| {
14495                            if old_highlight_id.is_none() {
14496                                old_highlight_id = chunk.syntax_highlight_id;
14497                            }
14498                            chunk.text
14499                        })
14500                        .collect::<String>()
14501                        .into();
14502
14503                    drop(buffer);
14504
14505                    // Position the selection in the rename editor so that it matches the current selection.
14506                    this.show_local_selections = false;
14507                    let rename_editor = cx.new(|cx| {
14508                        let mut editor = Editor::single_line(window, cx);
14509                        editor.buffer.update(cx, |buffer, cx| {
14510                            buffer.edit([(0..0, old_name.clone())], None, cx)
14511                        });
14512                        let rename_selection_range = match cursor_offset_in_rename_range
14513                            .cmp(&cursor_offset_in_rename_range_end)
14514                        {
14515                            Ordering::Equal => {
14516                                editor.select_all(&SelectAll, window, cx);
14517                                return editor;
14518                            }
14519                            Ordering::Less => {
14520                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14521                            }
14522                            Ordering::Greater => {
14523                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14524                            }
14525                        };
14526                        if rename_selection_range.end > old_name.len() {
14527                            editor.select_all(&SelectAll, window, cx);
14528                        } else {
14529                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14530                                s.select_ranges([rename_selection_range]);
14531                            });
14532                        }
14533                        editor
14534                    });
14535                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14536                        if e == &EditorEvent::Focused {
14537                            cx.emit(EditorEvent::FocusedIn)
14538                        }
14539                    })
14540                    .detach();
14541
14542                    let write_highlights =
14543                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14544                    let read_highlights =
14545                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14546                    let ranges = write_highlights
14547                        .iter()
14548                        .flat_map(|(_, ranges)| ranges.iter())
14549                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14550                        .cloned()
14551                        .collect();
14552
14553                    this.highlight_text::<Rename>(
14554                        ranges,
14555                        HighlightStyle {
14556                            fade_out: Some(0.6),
14557                            ..Default::default()
14558                        },
14559                        cx,
14560                    );
14561                    let rename_focus_handle = rename_editor.focus_handle(cx);
14562                    window.focus(&rename_focus_handle);
14563                    let block_id = this.insert_blocks(
14564                        [BlockProperties {
14565                            style: BlockStyle::Flex,
14566                            placement: BlockPlacement::Below(range.start),
14567                            height: Some(1),
14568                            render: Arc::new({
14569                                let rename_editor = rename_editor.clone();
14570                                move |cx: &mut BlockContext| {
14571                                    let mut text_style = cx.editor_style.text.clone();
14572                                    if let Some(highlight_style) = old_highlight_id
14573                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14574                                    {
14575                                        text_style = text_style.highlight(highlight_style);
14576                                    }
14577                                    div()
14578                                        .block_mouse_down()
14579                                        .pl(cx.anchor_x)
14580                                        .child(EditorElement::new(
14581                                            &rename_editor,
14582                                            EditorStyle {
14583                                                background: cx.theme().system().transparent,
14584                                                local_player: cx.editor_style.local_player,
14585                                                text: text_style,
14586                                                scrollbar_width: cx.editor_style.scrollbar_width,
14587                                                syntax: cx.editor_style.syntax.clone(),
14588                                                status: cx.editor_style.status.clone(),
14589                                                inlay_hints_style: HighlightStyle {
14590                                                    font_weight: Some(FontWeight::BOLD),
14591                                                    ..make_inlay_hints_style(cx.app)
14592                                                },
14593                                                inline_completion_styles: make_suggestion_styles(
14594                                                    cx.app,
14595                                                ),
14596                                                ..EditorStyle::default()
14597                                            },
14598                                        ))
14599                                        .into_any_element()
14600                                }
14601                            }),
14602                            priority: 0,
14603                        }],
14604                        Some(Autoscroll::fit()),
14605                        cx,
14606                    )[0];
14607                    this.pending_rename = Some(RenameState {
14608                        range,
14609                        old_name,
14610                        editor: rename_editor,
14611                        block_id,
14612                    });
14613                })?;
14614            }
14615
14616            Ok(())
14617        }))
14618    }
14619
14620    pub fn confirm_rename(
14621        &mut self,
14622        _: &ConfirmRename,
14623        window: &mut Window,
14624        cx: &mut Context<Self>,
14625    ) -> Option<Task<Result<()>>> {
14626        let rename = self.take_rename(false, window, cx)?;
14627        let workspace = self.workspace()?.downgrade();
14628        let (buffer, start) = self
14629            .buffer
14630            .read(cx)
14631            .text_anchor_for_position(rename.range.start, cx)?;
14632        let (end_buffer, _) = self
14633            .buffer
14634            .read(cx)
14635            .text_anchor_for_position(rename.range.end, cx)?;
14636        if buffer != end_buffer {
14637            return None;
14638        }
14639
14640        let old_name = rename.old_name;
14641        let new_name = rename.editor.read(cx).text(cx);
14642
14643        let rename = self.semantics_provider.as_ref()?.perform_rename(
14644            &buffer,
14645            start,
14646            new_name.clone(),
14647            cx,
14648        )?;
14649
14650        Some(cx.spawn_in(window, async move |editor, cx| {
14651            let project_transaction = rename.await?;
14652            Self::open_project_transaction(
14653                &editor,
14654                workspace,
14655                project_transaction,
14656                format!("Rename: {}{}", old_name, new_name),
14657                cx,
14658            )
14659            .await?;
14660
14661            editor.update(cx, |editor, cx| {
14662                editor.refresh_document_highlights(cx);
14663            })?;
14664            Ok(())
14665        }))
14666    }
14667
14668    fn take_rename(
14669        &mut self,
14670        moving_cursor: bool,
14671        window: &mut Window,
14672        cx: &mut Context<Self>,
14673    ) -> Option<RenameState> {
14674        let rename = self.pending_rename.take()?;
14675        if rename.editor.focus_handle(cx).is_focused(window) {
14676            window.focus(&self.focus_handle);
14677        }
14678
14679        self.remove_blocks(
14680            [rename.block_id].into_iter().collect(),
14681            Some(Autoscroll::fit()),
14682            cx,
14683        );
14684        self.clear_highlights::<Rename>(cx);
14685        self.show_local_selections = true;
14686
14687        if moving_cursor {
14688            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14689                editor.selections.newest::<usize>(cx).head()
14690            });
14691
14692            // Update the selection to match the position of the selection inside
14693            // the rename editor.
14694            let snapshot = self.buffer.read(cx).read(cx);
14695            let rename_range = rename.range.to_offset(&snapshot);
14696            let cursor_in_editor = snapshot
14697                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14698                .min(rename_range.end);
14699            drop(snapshot);
14700
14701            self.change_selections(None, window, cx, |s| {
14702                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14703            });
14704        } else {
14705            self.refresh_document_highlights(cx);
14706        }
14707
14708        Some(rename)
14709    }
14710
14711    pub fn pending_rename(&self) -> Option<&RenameState> {
14712        self.pending_rename.as_ref()
14713    }
14714
14715    fn format(
14716        &mut self,
14717        _: &Format,
14718        window: &mut Window,
14719        cx: &mut Context<Self>,
14720    ) -> Option<Task<Result<()>>> {
14721        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14722
14723        let project = match &self.project {
14724            Some(project) => project.clone(),
14725            None => return None,
14726        };
14727
14728        Some(self.perform_format(
14729            project,
14730            FormatTrigger::Manual,
14731            FormatTarget::Buffers,
14732            window,
14733            cx,
14734        ))
14735    }
14736
14737    fn format_selections(
14738        &mut self,
14739        _: &FormatSelections,
14740        window: &mut Window,
14741        cx: &mut Context<Self>,
14742    ) -> Option<Task<Result<()>>> {
14743        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14744
14745        let project = match &self.project {
14746            Some(project) => project.clone(),
14747            None => return None,
14748        };
14749
14750        let ranges = self
14751            .selections
14752            .all_adjusted(cx)
14753            .into_iter()
14754            .map(|selection| selection.range())
14755            .collect_vec();
14756
14757        Some(self.perform_format(
14758            project,
14759            FormatTrigger::Manual,
14760            FormatTarget::Ranges(ranges),
14761            window,
14762            cx,
14763        ))
14764    }
14765
14766    fn perform_format(
14767        &mut self,
14768        project: Entity<Project>,
14769        trigger: FormatTrigger,
14770        target: FormatTarget,
14771        window: &mut Window,
14772        cx: &mut Context<Self>,
14773    ) -> Task<Result<()>> {
14774        let buffer = self.buffer.clone();
14775        let (buffers, target) = match target {
14776            FormatTarget::Buffers => {
14777                let mut buffers = buffer.read(cx).all_buffers();
14778                if trigger == FormatTrigger::Save {
14779                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14780                }
14781                (buffers, LspFormatTarget::Buffers)
14782            }
14783            FormatTarget::Ranges(selection_ranges) => {
14784                let multi_buffer = buffer.read(cx);
14785                let snapshot = multi_buffer.read(cx);
14786                let mut buffers = HashSet::default();
14787                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14788                    BTreeMap::new();
14789                for selection_range in selection_ranges {
14790                    for (buffer, buffer_range, _) in
14791                        snapshot.range_to_buffer_ranges(selection_range)
14792                    {
14793                        let buffer_id = buffer.remote_id();
14794                        let start = buffer.anchor_before(buffer_range.start);
14795                        let end = buffer.anchor_after(buffer_range.end);
14796                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14797                        buffer_id_to_ranges
14798                            .entry(buffer_id)
14799                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14800                            .or_insert_with(|| vec![start..end]);
14801                    }
14802                }
14803                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14804            }
14805        };
14806
14807        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14808        let selections_prev = transaction_id_prev
14809            .and_then(|transaction_id_prev| {
14810                // default to selections as they were after the last edit, if we have them,
14811                // instead of how they are now.
14812                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14813                // will take you back to where you made the last edit, instead of staying where you scrolled
14814                self.selection_history
14815                    .transaction(transaction_id_prev)
14816                    .map(|t| t.0.clone())
14817            })
14818            .unwrap_or_else(|| {
14819                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14820                self.selections.disjoint_anchors()
14821            });
14822
14823        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14824        let format = project.update(cx, |project, cx| {
14825            project.format(buffers, target, true, trigger, cx)
14826        });
14827
14828        cx.spawn_in(window, async move |editor, cx| {
14829            let transaction = futures::select_biased! {
14830                transaction = format.log_err().fuse() => transaction,
14831                () = timeout => {
14832                    log::warn!("timed out waiting for formatting");
14833                    None
14834                }
14835            };
14836
14837            buffer
14838                .update(cx, |buffer, cx| {
14839                    if let Some(transaction) = transaction {
14840                        if !buffer.is_singleton() {
14841                            buffer.push_transaction(&transaction.0, cx);
14842                        }
14843                    }
14844                    cx.notify();
14845                })
14846                .ok();
14847
14848            if let Some(transaction_id_now) =
14849                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14850            {
14851                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14852                if has_new_transaction {
14853                    _ = editor.update(cx, |editor, _| {
14854                        editor
14855                            .selection_history
14856                            .insert_transaction(transaction_id_now, selections_prev);
14857                    });
14858                }
14859            }
14860
14861            Ok(())
14862        })
14863    }
14864
14865    fn organize_imports(
14866        &mut self,
14867        _: &OrganizeImports,
14868        window: &mut Window,
14869        cx: &mut Context<Self>,
14870    ) -> Option<Task<Result<()>>> {
14871        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14872        let project = match &self.project {
14873            Some(project) => project.clone(),
14874            None => return None,
14875        };
14876        Some(self.perform_code_action_kind(
14877            project,
14878            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14879            window,
14880            cx,
14881        ))
14882    }
14883
14884    fn perform_code_action_kind(
14885        &mut self,
14886        project: Entity<Project>,
14887        kind: CodeActionKind,
14888        window: &mut Window,
14889        cx: &mut Context<Self>,
14890    ) -> Task<Result<()>> {
14891        let buffer = self.buffer.clone();
14892        let buffers = buffer.read(cx).all_buffers();
14893        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14894        let apply_action = project.update(cx, |project, cx| {
14895            project.apply_code_action_kind(buffers, kind, true, cx)
14896        });
14897        cx.spawn_in(window, async move |_, cx| {
14898            let transaction = futures::select_biased! {
14899                () = timeout => {
14900                    log::warn!("timed out waiting for executing code action");
14901                    None
14902                }
14903                transaction = apply_action.log_err().fuse() => transaction,
14904            };
14905            buffer
14906                .update(cx, |buffer, cx| {
14907                    // check if we need this
14908                    if let Some(transaction) = transaction {
14909                        if !buffer.is_singleton() {
14910                            buffer.push_transaction(&transaction.0, cx);
14911                        }
14912                    }
14913                    cx.notify();
14914                })
14915                .ok();
14916            Ok(())
14917        })
14918    }
14919
14920    fn restart_language_server(
14921        &mut self,
14922        _: &RestartLanguageServer,
14923        _: &mut Window,
14924        cx: &mut Context<Self>,
14925    ) {
14926        if let Some(project) = self.project.clone() {
14927            self.buffer.update(cx, |multi_buffer, cx| {
14928                project.update(cx, |project, cx| {
14929                    project.restart_language_servers_for_buffers(
14930                        multi_buffer.all_buffers().into_iter().collect(),
14931                        cx,
14932                    );
14933                });
14934            })
14935        }
14936    }
14937
14938    fn stop_language_server(
14939        &mut self,
14940        _: &StopLanguageServer,
14941        _: &mut Window,
14942        cx: &mut Context<Self>,
14943    ) {
14944        if let Some(project) = self.project.clone() {
14945            self.buffer.update(cx, |multi_buffer, cx| {
14946                project.update(cx, |project, cx| {
14947                    project.stop_language_servers_for_buffers(
14948                        multi_buffer.all_buffers().into_iter().collect(),
14949                        cx,
14950                    );
14951                    cx.emit(project::Event::RefreshInlayHints);
14952                });
14953            });
14954        }
14955    }
14956
14957    fn cancel_language_server_work(
14958        workspace: &mut Workspace,
14959        _: &actions::CancelLanguageServerWork,
14960        _: &mut Window,
14961        cx: &mut Context<Workspace>,
14962    ) {
14963        let project = workspace.project();
14964        let buffers = workspace
14965            .active_item(cx)
14966            .and_then(|item| item.act_as::<Editor>(cx))
14967            .map_or(HashSet::default(), |editor| {
14968                editor.read(cx).buffer.read(cx).all_buffers()
14969            });
14970        project.update(cx, |project, cx| {
14971            project.cancel_language_server_work_for_buffers(buffers, cx);
14972        });
14973    }
14974
14975    fn show_character_palette(
14976        &mut self,
14977        _: &ShowCharacterPalette,
14978        window: &mut Window,
14979        _: &mut Context<Self>,
14980    ) {
14981        window.show_character_palette();
14982    }
14983
14984    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14985        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14986            let buffer = self.buffer.read(cx).snapshot(cx);
14987            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14988            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14989            let is_valid = buffer
14990                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14991                .any(|entry| {
14992                    entry.diagnostic.is_primary
14993                        && !entry.range.is_empty()
14994                        && entry.range.start == primary_range_start
14995                        && entry.diagnostic.message == active_diagnostics.active_message
14996                });
14997
14998            if !is_valid {
14999                self.dismiss_diagnostics(cx);
15000            }
15001        }
15002    }
15003
15004    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15005        match &self.active_diagnostics {
15006            ActiveDiagnostic::Group(group) => Some(group),
15007            _ => None,
15008        }
15009    }
15010
15011    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15012        self.dismiss_diagnostics(cx);
15013        self.active_diagnostics = ActiveDiagnostic::All;
15014    }
15015
15016    fn activate_diagnostics(
15017        &mut self,
15018        buffer_id: BufferId,
15019        diagnostic: DiagnosticEntry<usize>,
15020        window: &mut Window,
15021        cx: &mut Context<Self>,
15022    ) {
15023        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15024            return;
15025        }
15026        self.dismiss_diagnostics(cx);
15027        let snapshot = self.snapshot(window, cx);
15028        let buffer = self.buffer.read(cx).snapshot(cx);
15029        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15030            return;
15031        };
15032
15033        let diagnostic_group = buffer
15034            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15035            .collect::<Vec<_>>();
15036
15037        let blocks =
15038            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15039
15040        let blocks = self.display_map.update(cx, |display_map, cx| {
15041            display_map.insert_blocks(blocks, cx).into_iter().collect()
15042        });
15043        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15044            active_range: buffer.anchor_before(diagnostic.range.start)
15045                ..buffer.anchor_after(diagnostic.range.end),
15046            active_message: diagnostic.diagnostic.message.clone(),
15047            group_id: diagnostic.diagnostic.group_id,
15048            blocks,
15049        });
15050        cx.notify();
15051    }
15052
15053    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15054        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15055            return;
15056        };
15057
15058        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15059        if let ActiveDiagnostic::Group(group) = prev {
15060            self.display_map.update(cx, |display_map, cx| {
15061                display_map.remove_blocks(group.blocks, cx);
15062            });
15063            cx.notify();
15064        }
15065    }
15066
15067    /// Disable inline diagnostics rendering for this editor.
15068    pub fn disable_inline_diagnostics(&mut self) {
15069        self.inline_diagnostics_enabled = false;
15070        self.inline_diagnostics_update = Task::ready(());
15071        self.inline_diagnostics.clear();
15072    }
15073
15074    pub fn inline_diagnostics_enabled(&self) -> bool {
15075        self.inline_diagnostics_enabled
15076    }
15077
15078    pub fn show_inline_diagnostics(&self) -> bool {
15079        self.show_inline_diagnostics
15080    }
15081
15082    pub fn toggle_inline_diagnostics(
15083        &mut self,
15084        _: &ToggleInlineDiagnostics,
15085        window: &mut Window,
15086        cx: &mut Context<Editor>,
15087    ) {
15088        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15089        self.refresh_inline_diagnostics(false, window, cx);
15090    }
15091
15092    fn refresh_inline_diagnostics(
15093        &mut self,
15094        debounce: bool,
15095        window: &mut Window,
15096        cx: &mut Context<Self>,
15097    ) {
15098        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15099            self.inline_diagnostics_update = Task::ready(());
15100            self.inline_diagnostics.clear();
15101            return;
15102        }
15103
15104        let debounce_ms = ProjectSettings::get_global(cx)
15105            .diagnostics
15106            .inline
15107            .update_debounce_ms;
15108        let debounce = if debounce && debounce_ms > 0 {
15109            Some(Duration::from_millis(debounce_ms))
15110        } else {
15111            None
15112        };
15113        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15114            let editor = editor.upgrade().unwrap();
15115
15116            if let Some(debounce) = debounce {
15117                cx.background_executor().timer(debounce).await;
15118            }
15119            let Some(snapshot) = editor
15120                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15121                .ok()
15122            else {
15123                return;
15124            };
15125
15126            let new_inline_diagnostics = cx
15127                .background_spawn(async move {
15128                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15129                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15130                        let message = diagnostic_entry
15131                            .diagnostic
15132                            .message
15133                            .split_once('\n')
15134                            .map(|(line, _)| line)
15135                            .map(SharedString::new)
15136                            .unwrap_or_else(|| {
15137                                SharedString::from(diagnostic_entry.diagnostic.message)
15138                            });
15139                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15140                        let (Ok(i) | Err(i)) = inline_diagnostics
15141                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15142                        inline_diagnostics.insert(
15143                            i,
15144                            (
15145                                start_anchor,
15146                                InlineDiagnostic {
15147                                    message,
15148                                    group_id: diagnostic_entry.diagnostic.group_id,
15149                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15150                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15151                                    severity: diagnostic_entry.diagnostic.severity,
15152                                },
15153                            ),
15154                        );
15155                    }
15156                    inline_diagnostics
15157                })
15158                .await;
15159
15160            editor
15161                .update(cx, |editor, cx| {
15162                    editor.inline_diagnostics = new_inline_diagnostics;
15163                    cx.notify();
15164                })
15165                .ok();
15166        });
15167    }
15168
15169    pub fn set_selections_from_remote(
15170        &mut self,
15171        selections: Vec<Selection<Anchor>>,
15172        pending_selection: Option<Selection<Anchor>>,
15173        window: &mut Window,
15174        cx: &mut Context<Self>,
15175    ) {
15176        let old_cursor_position = self.selections.newest_anchor().head();
15177        self.selections.change_with(cx, |s| {
15178            s.select_anchors(selections);
15179            if let Some(pending_selection) = pending_selection {
15180                s.set_pending(pending_selection, SelectMode::Character);
15181            } else {
15182                s.clear_pending();
15183            }
15184        });
15185        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15186    }
15187
15188    fn push_to_selection_history(&mut self) {
15189        self.selection_history.push(SelectionHistoryEntry {
15190            selections: self.selections.disjoint_anchors(),
15191            select_next_state: self.select_next_state.clone(),
15192            select_prev_state: self.select_prev_state.clone(),
15193            add_selections_state: self.add_selections_state.clone(),
15194        });
15195    }
15196
15197    pub fn transact(
15198        &mut self,
15199        window: &mut Window,
15200        cx: &mut Context<Self>,
15201        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15202    ) -> Option<TransactionId> {
15203        self.start_transaction_at(Instant::now(), window, cx);
15204        update(self, window, cx);
15205        self.end_transaction_at(Instant::now(), cx)
15206    }
15207
15208    pub fn start_transaction_at(
15209        &mut self,
15210        now: Instant,
15211        window: &mut Window,
15212        cx: &mut Context<Self>,
15213    ) {
15214        self.end_selection(window, cx);
15215        if let Some(tx_id) = self
15216            .buffer
15217            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15218        {
15219            self.selection_history
15220                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15221            cx.emit(EditorEvent::TransactionBegun {
15222                transaction_id: tx_id,
15223            })
15224        }
15225    }
15226
15227    pub fn end_transaction_at(
15228        &mut self,
15229        now: Instant,
15230        cx: &mut Context<Self>,
15231    ) -> Option<TransactionId> {
15232        if let Some(transaction_id) = self
15233            .buffer
15234            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15235        {
15236            if let Some((_, end_selections)) =
15237                self.selection_history.transaction_mut(transaction_id)
15238            {
15239                *end_selections = Some(self.selections.disjoint_anchors());
15240            } else {
15241                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15242            }
15243
15244            cx.emit(EditorEvent::Edited { transaction_id });
15245            Some(transaction_id)
15246        } else {
15247            None
15248        }
15249    }
15250
15251    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15252        if self.selection_mark_mode {
15253            self.change_selections(None, window, cx, |s| {
15254                s.move_with(|_, sel| {
15255                    sel.collapse_to(sel.head(), SelectionGoal::None);
15256                });
15257            })
15258        }
15259        self.selection_mark_mode = true;
15260        cx.notify();
15261    }
15262
15263    pub fn swap_selection_ends(
15264        &mut self,
15265        _: &actions::SwapSelectionEnds,
15266        window: &mut Window,
15267        cx: &mut Context<Self>,
15268    ) {
15269        self.change_selections(None, window, cx, |s| {
15270            s.move_with(|_, sel| {
15271                if sel.start != sel.end {
15272                    sel.reversed = !sel.reversed
15273                }
15274            });
15275        });
15276        self.request_autoscroll(Autoscroll::newest(), cx);
15277        cx.notify();
15278    }
15279
15280    pub fn toggle_fold(
15281        &mut self,
15282        _: &actions::ToggleFold,
15283        window: &mut Window,
15284        cx: &mut Context<Self>,
15285    ) {
15286        if self.is_singleton(cx) {
15287            let selection = self.selections.newest::<Point>(cx);
15288
15289            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15290            let range = if selection.is_empty() {
15291                let point = selection.head().to_display_point(&display_map);
15292                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15293                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15294                    .to_point(&display_map);
15295                start..end
15296            } else {
15297                selection.range()
15298            };
15299            if display_map.folds_in_range(range).next().is_some() {
15300                self.unfold_lines(&Default::default(), window, cx)
15301            } else {
15302                self.fold(&Default::default(), window, cx)
15303            }
15304        } else {
15305            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15306            let buffer_ids: HashSet<_> = self
15307                .selections
15308                .disjoint_anchor_ranges()
15309                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15310                .collect();
15311
15312            let should_unfold = buffer_ids
15313                .iter()
15314                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15315
15316            for buffer_id in buffer_ids {
15317                if should_unfold {
15318                    self.unfold_buffer(buffer_id, cx);
15319                } else {
15320                    self.fold_buffer(buffer_id, cx);
15321                }
15322            }
15323        }
15324    }
15325
15326    pub fn toggle_fold_recursive(
15327        &mut self,
15328        _: &actions::ToggleFoldRecursive,
15329        window: &mut Window,
15330        cx: &mut Context<Self>,
15331    ) {
15332        let selection = self.selections.newest::<Point>(cx);
15333
15334        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15335        let range = if selection.is_empty() {
15336            let point = selection.head().to_display_point(&display_map);
15337            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15338            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15339                .to_point(&display_map);
15340            start..end
15341        } else {
15342            selection.range()
15343        };
15344        if display_map.folds_in_range(range).next().is_some() {
15345            self.unfold_recursive(&Default::default(), window, cx)
15346        } else {
15347            self.fold_recursive(&Default::default(), window, cx)
15348        }
15349    }
15350
15351    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15352        if self.is_singleton(cx) {
15353            let mut to_fold = Vec::new();
15354            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15355            let selections = self.selections.all_adjusted(cx);
15356
15357            for selection in selections {
15358                let range = selection.range().sorted();
15359                let buffer_start_row = range.start.row;
15360
15361                if range.start.row != range.end.row {
15362                    let mut found = false;
15363                    let mut row = range.start.row;
15364                    while row <= range.end.row {
15365                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15366                        {
15367                            found = true;
15368                            row = crease.range().end.row + 1;
15369                            to_fold.push(crease);
15370                        } else {
15371                            row += 1
15372                        }
15373                    }
15374                    if found {
15375                        continue;
15376                    }
15377                }
15378
15379                for row in (0..=range.start.row).rev() {
15380                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15381                        if crease.range().end.row >= buffer_start_row {
15382                            to_fold.push(crease);
15383                            if row <= range.start.row {
15384                                break;
15385                            }
15386                        }
15387                    }
15388                }
15389            }
15390
15391            self.fold_creases(to_fold, true, window, cx);
15392        } else {
15393            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15394            let buffer_ids = self
15395                .selections
15396                .disjoint_anchor_ranges()
15397                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15398                .collect::<HashSet<_>>();
15399            for buffer_id in buffer_ids {
15400                self.fold_buffer(buffer_id, cx);
15401            }
15402        }
15403    }
15404
15405    fn fold_at_level(
15406        &mut self,
15407        fold_at: &FoldAtLevel,
15408        window: &mut Window,
15409        cx: &mut Context<Self>,
15410    ) {
15411        if !self.buffer.read(cx).is_singleton() {
15412            return;
15413        }
15414
15415        let fold_at_level = fold_at.0;
15416        let snapshot = self.buffer.read(cx).snapshot(cx);
15417        let mut to_fold = Vec::new();
15418        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15419
15420        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15421            while start_row < end_row {
15422                match self
15423                    .snapshot(window, cx)
15424                    .crease_for_buffer_row(MultiBufferRow(start_row))
15425                {
15426                    Some(crease) => {
15427                        let nested_start_row = crease.range().start.row + 1;
15428                        let nested_end_row = crease.range().end.row;
15429
15430                        if current_level < fold_at_level {
15431                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15432                        } else if current_level == fold_at_level {
15433                            to_fold.push(crease);
15434                        }
15435
15436                        start_row = nested_end_row + 1;
15437                    }
15438                    None => start_row += 1,
15439                }
15440            }
15441        }
15442
15443        self.fold_creases(to_fold, true, window, cx);
15444    }
15445
15446    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15447        if self.buffer.read(cx).is_singleton() {
15448            let mut fold_ranges = Vec::new();
15449            let snapshot = self.buffer.read(cx).snapshot(cx);
15450
15451            for row in 0..snapshot.max_row().0 {
15452                if let Some(foldable_range) = self
15453                    .snapshot(window, cx)
15454                    .crease_for_buffer_row(MultiBufferRow(row))
15455                {
15456                    fold_ranges.push(foldable_range);
15457                }
15458            }
15459
15460            self.fold_creases(fold_ranges, true, window, cx);
15461        } else {
15462            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15463                editor
15464                    .update_in(cx, |editor, _, cx| {
15465                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15466                            editor.fold_buffer(buffer_id, cx);
15467                        }
15468                    })
15469                    .ok();
15470            });
15471        }
15472    }
15473
15474    pub fn fold_function_bodies(
15475        &mut self,
15476        _: &actions::FoldFunctionBodies,
15477        window: &mut Window,
15478        cx: &mut Context<Self>,
15479    ) {
15480        let snapshot = self.buffer.read(cx).snapshot(cx);
15481
15482        let ranges = snapshot
15483            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15484            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15485            .collect::<Vec<_>>();
15486
15487        let creases = ranges
15488            .into_iter()
15489            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15490            .collect();
15491
15492        self.fold_creases(creases, true, window, cx);
15493    }
15494
15495    pub fn fold_recursive(
15496        &mut self,
15497        _: &actions::FoldRecursive,
15498        window: &mut Window,
15499        cx: &mut Context<Self>,
15500    ) {
15501        let mut to_fold = Vec::new();
15502        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15503        let selections = self.selections.all_adjusted(cx);
15504
15505        for selection in selections {
15506            let range = selection.range().sorted();
15507            let buffer_start_row = range.start.row;
15508
15509            if range.start.row != range.end.row {
15510                let mut found = false;
15511                for row in range.start.row..=range.end.row {
15512                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15513                        found = true;
15514                        to_fold.push(crease);
15515                    }
15516                }
15517                if found {
15518                    continue;
15519                }
15520            }
15521
15522            for row in (0..=range.start.row).rev() {
15523                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15524                    if crease.range().end.row >= buffer_start_row {
15525                        to_fold.push(crease);
15526                    } else {
15527                        break;
15528                    }
15529                }
15530            }
15531        }
15532
15533        self.fold_creases(to_fold, true, window, cx);
15534    }
15535
15536    pub fn fold_at(
15537        &mut self,
15538        buffer_row: MultiBufferRow,
15539        window: &mut Window,
15540        cx: &mut Context<Self>,
15541    ) {
15542        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15543
15544        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15545            let autoscroll = self
15546                .selections
15547                .all::<Point>(cx)
15548                .iter()
15549                .any(|selection| crease.range().overlaps(&selection.range()));
15550
15551            self.fold_creases(vec![crease], autoscroll, window, cx);
15552        }
15553    }
15554
15555    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15556        if self.is_singleton(cx) {
15557            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15558            let buffer = &display_map.buffer_snapshot;
15559            let selections = self.selections.all::<Point>(cx);
15560            let ranges = selections
15561                .iter()
15562                .map(|s| {
15563                    let range = s.display_range(&display_map).sorted();
15564                    let mut start = range.start.to_point(&display_map);
15565                    let mut end = range.end.to_point(&display_map);
15566                    start.column = 0;
15567                    end.column = buffer.line_len(MultiBufferRow(end.row));
15568                    start..end
15569                })
15570                .collect::<Vec<_>>();
15571
15572            self.unfold_ranges(&ranges, true, true, cx);
15573        } else {
15574            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15575            let buffer_ids = self
15576                .selections
15577                .disjoint_anchor_ranges()
15578                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15579                .collect::<HashSet<_>>();
15580            for buffer_id in buffer_ids {
15581                self.unfold_buffer(buffer_id, cx);
15582            }
15583        }
15584    }
15585
15586    pub fn unfold_recursive(
15587        &mut self,
15588        _: &UnfoldRecursive,
15589        _window: &mut Window,
15590        cx: &mut Context<Self>,
15591    ) {
15592        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15593        let selections = self.selections.all::<Point>(cx);
15594        let ranges = selections
15595            .iter()
15596            .map(|s| {
15597                let mut range = s.display_range(&display_map).sorted();
15598                *range.start.column_mut() = 0;
15599                *range.end.column_mut() = display_map.line_len(range.end.row());
15600                let start = range.start.to_point(&display_map);
15601                let end = range.end.to_point(&display_map);
15602                start..end
15603            })
15604            .collect::<Vec<_>>();
15605
15606        self.unfold_ranges(&ranges, true, true, cx);
15607    }
15608
15609    pub fn unfold_at(
15610        &mut self,
15611        buffer_row: MultiBufferRow,
15612        _window: &mut Window,
15613        cx: &mut Context<Self>,
15614    ) {
15615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15616
15617        let intersection_range = Point::new(buffer_row.0, 0)
15618            ..Point::new(
15619                buffer_row.0,
15620                display_map.buffer_snapshot.line_len(buffer_row),
15621            );
15622
15623        let autoscroll = self
15624            .selections
15625            .all::<Point>(cx)
15626            .iter()
15627            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15628
15629        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15630    }
15631
15632    pub fn unfold_all(
15633        &mut self,
15634        _: &actions::UnfoldAll,
15635        _window: &mut Window,
15636        cx: &mut Context<Self>,
15637    ) {
15638        if self.buffer.read(cx).is_singleton() {
15639            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15640            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15641        } else {
15642            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15643                editor
15644                    .update(cx, |editor, cx| {
15645                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15646                            editor.unfold_buffer(buffer_id, cx);
15647                        }
15648                    })
15649                    .ok();
15650            });
15651        }
15652    }
15653
15654    pub fn fold_selected_ranges(
15655        &mut self,
15656        _: &FoldSelectedRanges,
15657        window: &mut Window,
15658        cx: &mut Context<Self>,
15659    ) {
15660        let selections = self.selections.all_adjusted(cx);
15661        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15662        let ranges = selections
15663            .into_iter()
15664            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15665            .collect::<Vec<_>>();
15666        self.fold_creases(ranges, true, window, cx);
15667    }
15668
15669    pub fn fold_ranges<T: ToOffset + Clone>(
15670        &mut self,
15671        ranges: Vec<Range<T>>,
15672        auto_scroll: bool,
15673        window: &mut Window,
15674        cx: &mut Context<Self>,
15675    ) {
15676        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15677        let ranges = ranges
15678            .into_iter()
15679            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15680            .collect::<Vec<_>>();
15681        self.fold_creases(ranges, auto_scroll, window, cx);
15682    }
15683
15684    pub fn fold_creases<T: ToOffset + Clone>(
15685        &mut self,
15686        creases: Vec<Crease<T>>,
15687        auto_scroll: bool,
15688        _window: &mut Window,
15689        cx: &mut Context<Self>,
15690    ) {
15691        if creases.is_empty() {
15692            return;
15693        }
15694
15695        let mut buffers_affected = HashSet::default();
15696        let multi_buffer = self.buffer().read(cx);
15697        for crease in &creases {
15698            if let Some((_, buffer, _)) =
15699                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15700            {
15701                buffers_affected.insert(buffer.read(cx).remote_id());
15702            };
15703        }
15704
15705        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15706
15707        if auto_scroll {
15708            self.request_autoscroll(Autoscroll::fit(), cx);
15709        }
15710
15711        cx.notify();
15712
15713        self.scrollbar_marker_state.dirty = true;
15714        self.folds_did_change(cx);
15715    }
15716
15717    /// Removes any folds whose ranges intersect any of the given ranges.
15718    pub fn unfold_ranges<T: ToOffset + Clone>(
15719        &mut self,
15720        ranges: &[Range<T>],
15721        inclusive: bool,
15722        auto_scroll: bool,
15723        cx: &mut Context<Self>,
15724    ) {
15725        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15726            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15727        });
15728        self.folds_did_change(cx);
15729    }
15730
15731    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15732        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15733            return;
15734        }
15735        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15736        self.display_map.update(cx, |display_map, cx| {
15737            display_map.fold_buffers([buffer_id], cx)
15738        });
15739        cx.emit(EditorEvent::BufferFoldToggled {
15740            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15741            folded: true,
15742        });
15743        cx.notify();
15744    }
15745
15746    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15747        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15748            return;
15749        }
15750        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15751        self.display_map.update(cx, |display_map, cx| {
15752            display_map.unfold_buffers([buffer_id], cx);
15753        });
15754        cx.emit(EditorEvent::BufferFoldToggled {
15755            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15756            folded: false,
15757        });
15758        cx.notify();
15759    }
15760
15761    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15762        self.display_map.read(cx).is_buffer_folded(buffer)
15763    }
15764
15765    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15766        self.display_map.read(cx).folded_buffers()
15767    }
15768
15769    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15770        self.display_map.update(cx, |display_map, cx| {
15771            display_map.disable_header_for_buffer(buffer_id, cx);
15772        });
15773        cx.notify();
15774    }
15775
15776    /// Removes any folds with the given ranges.
15777    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15778        &mut self,
15779        ranges: &[Range<T>],
15780        type_id: TypeId,
15781        auto_scroll: bool,
15782        cx: &mut Context<Self>,
15783    ) {
15784        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15785            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15786        });
15787        self.folds_did_change(cx);
15788    }
15789
15790    fn remove_folds_with<T: ToOffset + Clone>(
15791        &mut self,
15792        ranges: &[Range<T>],
15793        auto_scroll: bool,
15794        cx: &mut Context<Self>,
15795        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15796    ) {
15797        if ranges.is_empty() {
15798            return;
15799        }
15800
15801        let mut buffers_affected = HashSet::default();
15802        let multi_buffer = self.buffer().read(cx);
15803        for range in ranges {
15804            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15805                buffers_affected.insert(buffer.read(cx).remote_id());
15806            };
15807        }
15808
15809        self.display_map.update(cx, update);
15810
15811        if auto_scroll {
15812            self.request_autoscroll(Autoscroll::fit(), cx);
15813        }
15814
15815        cx.notify();
15816        self.scrollbar_marker_state.dirty = true;
15817        self.active_indent_guides_state.dirty = true;
15818    }
15819
15820    pub fn update_fold_widths(
15821        &mut self,
15822        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15823        cx: &mut Context<Self>,
15824    ) -> bool {
15825        self.display_map
15826            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15827    }
15828
15829    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15830        self.display_map.read(cx).fold_placeholder.clone()
15831    }
15832
15833    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15834        self.buffer.update(cx, |buffer, cx| {
15835            buffer.set_all_diff_hunks_expanded(cx);
15836        });
15837    }
15838
15839    pub fn expand_all_diff_hunks(
15840        &mut self,
15841        _: &ExpandAllDiffHunks,
15842        _window: &mut Window,
15843        cx: &mut Context<Self>,
15844    ) {
15845        self.buffer.update(cx, |buffer, cx| {
15846            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15847        });
15848    }
15849
15850    pub fn toggle_selected_diff_hunks(
15851        &mut self,
15852        _: &ToggleSelectedDiffHunks,
15853        _window: &mut Window,
15854        cx: &mut Context<Self>,
15855    ) {
15856        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15857        self.toggle_diff_hunks_in_ranges(ranges, cx);
15858    }
15859
15860    pub fn diff_hunks_in_ranges<'a>(
15861        &'a self,
15862        ranges: &'a [Range<Anchor>],
15863        buffer: &'a MultiBufferSnapshot,
15864    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15865        ranges.iter().flat_map(move |range| {
15866            let end_excerpt_id = range.end.excerpt_id;
15867            let range = range.to_point(buffer);
15868            let mut peek_end = range.end;
15869            if range.end.row < buffer.max_row().0 {
15870                peek_end = Point::new(range.end.row + 1, 0);
15871            }
15872            buffer
15873                .diff_hunks_in_range(range.start..peek_end)
15874                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15875        })
15876    }
15877
15878    pub fn has_stageable_diff_hunks_in_ranges(
15879        &self,
15880        ranges: &[Range<Anchor>],
15881        snapshot: &MultiBufferSnapshot,
15882    ) -> bool {
15883        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15884        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15885    }
15886
15887    pub fn toggle_staged_selected_diff_hunks(
15888        &mut self,
15889        _: &::git::ToggleStaged,
15890        _: &mut Window,
15891        cx: &mut Context<Self>,
15892    ) {
15893        let snapshot = self.buffer.read(cx).snapshot(cx);
15894        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15895        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15896        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15897    }
15898
15899    pub fn set_render_diff_hunk_controls(
15900        &mut self,
15901        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15902        cx: &mut Context<Self>,
15903    ) {
15904        self.render_diff_hunk_controls = render_diff_hunk_controls;
15905        cx.notify();
15906    }
15907
15908    pub fn stage_and_next(
15909        &mut self,
15910        _: &::git::StageAndNext,
15911        window: &mut Window,
15912        cx: &mut Context<Self>,
15913    ) {
15914        self.do_stage_or_unstage_and_next(true, window, cx);
15915    }
15916
15917    pub fn unstage_and_next(
15918        &mut self,
15919        _: &::git::UnstageAndNext,
15920        window: &mut Window,
15921        cx: &mut Context<Self>,
15922    ) {
15923        self.do_stage_or_unstage_and_next(false, window, cx);
15924    }
15925
15926    pub fn stage_or_unstage_diff_hunks(
15927        &mut self,
15928        stage: bool,
15929        ranges: Vec<Range<Anchor>>,
15930        cx: &mut Context<Self>,
15931    ) {
15932        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15933        cx.spawn(async move |this, cx| {
15934            task.await?;
15935            this.update(cx, |this, cx| {
15936                let snapshot = this.buffer.read(cx).snapshot(cx);
15937                let chunk_by = this
15938                    .diff_hunks_in_ranges(&ranges, &snapshot)
15939                    .chunk_by(|hunk| hunk.buffer_id);
15940                for (buffer_id, hunks) in &chunk_by {
15941                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15942                }
15943            })
15944        })
15945        .detach_and_log_err(cx);
15946    }
15947
15948    fn save_buffers_for_ranges_if_needed(
15949        &mut self,
15950        ranges: &[Range<Anchor>],
15951        cx: &mut Context<Editor>,
15952    ) -> Task<Result<()>> {
15953        let multibuffer = self.buffer.read(cx);
15954        let snapshot = multibuffer.read(cx);
15955        let buffer_ids: HashSet<_> = ranges
15956            .iter()
15957            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15958            .collect();
15959        drop(snapshot);
15960
15961        let mut buffers = HashSet::default();
15962        for buffer_id in buffer_ids {
15963            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15964                let buffer = buffer_entity.read(cx);
15965                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15966                {
15967                    buffers.insert(buffer_entity);
15968                }
15969            }
15970        }
15971
15972        if let Some(project) = &self.project {
15973            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15974        } else {
15975            Task::ready(Ok(()))
15976        }
15977    }
15978
15979    fn do_stage_or_unstage_and_next(
15980        &mut self,
15981        stage: bool,
15982        window: &mut Window,
15983        cx: &mut Context<Self>,
15984    ) {
15985        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15986
15987        if ranges.iter().any(|range| range.start != range.end) {
15988            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15989            return;
15990        }
15991
15992        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15993        let snapshot = self.snapshot(window, cx);
15994        let position = self.selections.newest::<Point>(cx).head();
15995        let mut row = snapshot
15996            .buffer_snapshot
15997            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15998            .find(|hunk| hunk.row_range.start.0 > position.row)
15999            .map(|hunk| hunk.row_range.start);
16000
16001        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16002        // Outside of the project diff editor, wrap around to the beginning.
16003        if !all_diff_hunks_expanded {
16004            row = row.or_else(|| {
16005                snapshot
16006                    .buffer_snapshot
16007                    .diff_hunks_in_range(Point::zero()..position)
16008                    .find(|hunk| hunk.row_range.end.0 < position.row)
16009                    .map(|hunk| hunk.row_range.start)
16010            });
16011        }
16012
16013        if let Some(row) = row {
16014            let destination = Point::new(row.0, 0);
16015            let autoscroll = Autoscroll::center();
16016
16017            self.unfold_ranges(&[destination..destination], false, false, cx);
16018            self.change_selections(Some(autoscroll), window, cx, |s| {
16019                s.select_ranges([destination..destination]);
16020            });
16021        }
16022    }
16023
16024    fn do_stage_or_unstage(
16025        &self,
16026        stage: bool,
16027        buffer_id: BufferId,
16028        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16029        cx: &mut App,
16030    ) -> Option<()> {
16031        let project = self.project.as_ref()?;
16032        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16033        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16034        let buffer_snapshot = buffer.read(cx).snapshot();
16035        let file_exists = buffer_snapshot
16036            .file()
16037            .is_some_and(|file| file.disk_state().exists());
16038        diff.update(cx, |diff, cx| {
16039            diff.stage_or_unstage_hunks(
16040                stage,
16041                &hunks
16042                    .map(|hunk| buffer_diff::DiffHunk {
16043                        buffer_range: hunk.buffer_range,
16044                        diff_base_byte_range: hunk.diff_base_byte_range,
16045                        secondary_status: hunk.secondary_status,
16046                        range: Point::zero()..Point::zero(), // unused
16047                    })
16048                    .collect::<Vec<_>>(),
16049                &buffer_snapshot,
16050                file_exists,
16051                cx,
16052            )
16053        });
16054        None
16055    }
16056
16057    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16058        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16059        self.buffer
16060            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16061    }
16062
16063    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16064        self.buffer.update(cx, |buffer, cx| {
16065            let ranges = vec![Anchor::min()..Anchor::max()];
16066            if !buffer.all_diff_hunks_expanded()
16067                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16068            {
16069                buffer.collapse_diff_hunks(ranges, cx);
16070                true
16071            } else {
16072                false
16073            }
16074        })
16075    }
16076
16077    fn toggle_diff_hunks_in_ranges(
16078        &mut self,
16079        ranges: Vec<Range<Anchor>>,
16080        cx: &mut Context<Editor>,
16081    ) {
16082        self.buffer.update(cx, |buffer, cx| {
16083            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16084            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16085        })
16086    }
16087
16088    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16089        self.buffer.update(cx, |buffer, cx| {
16090            let snapshot = buffer.snapshot(cx);
16091            let excerpt_id = range.end.excerpt_id;
16092            let point_range = range.to_point(&snapshot);
16093            let expand = !buffer.single_hunk_is_expanded(range, cx);
16094            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16095        })
16096    }
16097
16098    pub(crate) fn apply_all_diff_hunks(
16099        &mut self,
16100        _: &ApplyAllDiffHunks,
16101        window: &mut Window,
16102        cx: &mut Context<Self>,
16103    ) {
16104        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16105
16106        let buffers = self.buffer.read(cx).all_buffers();
16107        for branch_buffer in buffers {
16108            branch_buffer.update(cx, |branch_buffer, cx| {
16109                branch_buffer.merge_into_base(Vec::new(), cx);
16110            });
16111        }
16112
16113        if let Some(project) = self.project.clone() {
16114            self.save(true, project, window, cx).detach_and_log_err(cx);
16115        }
16116    }
16117
16118    pub(crate) fn apply_selected_diff_hunks(
16119        &mut self,
16120        _: &ApplyDiffHunk,
16121        window: &mut Window,
16122        cx: &mut Context<Self>,
16123    ) {
16124        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16125        let snapshot = self.snapshot(window, cx);
16126        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16127        let mut ranges_by_buffer = HashMap::default();
16128        self.transact(window, cx, |editor, _window, cx| {
16129            for hunk in hunks {
16130                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16131                    ranges_by_buffer
16132                        .entry(buffer.clone())
16133                        .or_insert_with(Vec::new)
16134                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16135                }
16136            }
16137
16138            for (buffer, ranges) in ranges_by_buffer {
16139                buffer.update(cx, |buffer, cx| {
16140                    buffer.merge_into_base(ranges, cx);
16141                });
16142            }
16143        });
16144
16145        if let Some(project) = self.project.clone() {
16146            self.save(true, project, window, cx).detach_and_log_err(cx);
16147        }
16148    }
16149
16150    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16151        if hovered != self.gutter_hovered {
16152            self.gutter_hovered = hovered;
16153            cx.notify();
16154        }
16155    }
16156
16157    pub fn insert_blocks(
16158        &mut self,
16159        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16160        autoscroll: Option<Autoscroll>,
16161        cx: &mut Context<Self>,
16162    ) -> Vec<CustomBlockId> {
16163        let blocks = self
16164            .display_map
16165            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16166        if let Some(autoscroll) = autoscroll {
16167            self.request_autoscroll(autoscroll, cx);
16168        }
16169        cx.notify();
16170        blocks
16171    }
16172
16173    pub fn resize_blocks(
16174        &mut self,
16175        heights: HashMap<CustomBlockId, u32>,
16176        autoscroll: Option<Autoscroll>,
16177        cx: &mut Context<Self>,
16178    ) {
16179        self.display_map
16180            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16181        if let Some(autoscroll) = autoscroll {
16182            self.request_autoscroll(autoscroll, cx);
16183        }
16184        cx.notify();
16185    }
16186
16187    pub fn replace_blocks(
16188        &mut self,
16189        renderers: HashMap<CustomBlockId, RenderBlock>,
16190        autoscroll: Option<Autoscroll>,
16191        cx: &mut Context<Self>,
16192    ) {
16193        self.display_map
16194            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16195        if let Some(autoscroll) = autoscroll {
16196            self.request_autoscroll(autoscroll, cx);
16197        }
16198        cx.notify();
16199    }
16200
16201    pub fn remove_blocks(
16202        &mut self,
16203        block_ids: HashSet<CustomBlockId>,
16204        autoscroll: Option<Autoscroll>,
16205        cx: &mut Context<Self>,
16206    ) {
16207        self.display_map.update(cx, |display_map, cx| {
16208            display_map.remove_blocks(block_ids, cx)
16209        });
16210        if let Some(autoscroll) = autoscroll {
16211            self.request_autoscroll(autoscroll, cx);
16212        }
16213        cx.notify();
16214    }
16215
16216    pub fn row_for_block(
16217        &self,
16218        block_id: CustomBlockId,
16219        cx: &mut Context<Self>,
16220    ) -> Option<DisplayRow> {
16221        self.display_map
16222            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16223    }
16224
16225    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16226        self.focused_block = Some(focused_block);
16227    }
16228
16229    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16230        self.focused_block.take()
16231    }
16232
16233    pub fn insert_creases(
16234        &mut self,
16235        creases: impl IntoIterator<Item = Crease<Anchor>>,
16236        cx: &mut Context<Self>,
16237    ) -> Vec<CreaseId> {
16238        self.display_map
16239            .update(cx, |map, cx| map.insert_creases(creases, cx))
16240    }
16241
16242    pub fn remove_creases(
16243        &mut self,
16244        ids: impl IntoIterator<Item = CreaseId>,
16245        cx: &mut Context<Self>,
16246    ) -> Vec<(CreaseId, Range<Anchor>)> {
16247        self.display_map
16248            .update(cx, |map, cx| map.remove_creases(ids, cx))
16249    }
16250
16251    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16252        self.display_map
16253            .update(cx, |map, cx| map.snapshot(cx))
16254            .longest_row()
16255    }
16256
16257    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16258        self.display_map
16259            .update(cx, |map, cx| map.snapshot(cx))
16260            .max_point()
16261    }
16262
16263    pub fn text(&self, cx: &App) -> String {
16264        self.buffer.read(cx).read(cx).text()
16265    }
16266
16267    pub fn is_empty(&self, cx: &App) -> bool {
16268        self.buffer.read(cx).read(cx).is_empty()
16269    }
16270
16271    pub fn text_option(&self, cx: &App) -> Option<String> {
16272        let text = self.text(cx);
16273        let text = text.trim();
16274
16275        if text.is_empty() {
16276            return None;
16277        }
16278
16279        Some(text.to_string())
16280    }
16281
16282    pub fn set_text(
16283        &mut self,
16284        text: impl Into<Arc<str>>,
16285        window: &mut Window,
16286        cx: &mut Context<Self>,
16287    ) {
16288        self.transact(window, cx, |this, _, cx| {
16289            this.buffer
16290                .read(cx)
16291                .as_singleton()
16292                .expect("you can only call set_text on editors for singleton buffers")
16293                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16294        });
16295    }
16296
16297    pub fn display_text(&self, cx: &mut App) -> String {
16298        self.display_map
16299            .update(cx, |map, cx| map.snapshot(cx))
16300            .text()
16301    }
16302
16303    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16304        let mut wrap_guides = smallvec::smallvec![];
16305
16306        if self.show_wrap_guides == Some(false) {
16307            return wrap_guides;
16308        }
16309
16310        let settings = self.buffer.read(cx).language_settings(cx);
16311        if settings.show_wrap_guides {
16312            match self.soft_wrap_mode(cx) {
16313                SoftWrap::Column(soft_wrap) => {
16314                    wrap_guides.push((soft_wrap as usize, true));
16315                }
16316                SoftWrap::Bounded(soft_wrap) => {
16317                    wrap_guides.push((soft_wrap as usize, true));
16318                }
16319                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16320            }
16321            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16322        }
16323
16324        wrap_guides
16325    }
16326
16327    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16328        let settings = self.buffer.read(cx).language_settings(cx);
16329        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16330        match mode {
16331            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16332                SoftWrap::None
16333            }
16334            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16335            language_settings::SoftWrap::PreferredLineLength => {
16336                SoftWrap::Column(settings.preferred_line_length)
16337            }
16338            language_settings::SoftWrap::Bounded => {
16339                SoftWrap::Bounded(settings.preferred_line_length)
16340            }
16341        }
16342    }
16343
16344    pub fn set_soft_wrap_mode(
16345        &mut self,
16346        mode: language_settings::SoftWrap,
16347
16348        cx: &mut Context<Self>,
16349    ) {
16350        self.soft_wrap_mode_override = Some(mode);
16351        cx.notify();
16352    }
16353
16354    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16355        self.hard_wrap = hard_wrap;
16356        cx.notify();
16357    }
16358
16359    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16360        self.text_style_refinement = Some(style);
16361    }
16362
16363    /// called by the Element so we know what style we were most recently rendered with.
16364    pub(crate) fn set_style(
16365        &mut self,
16366        style: EditorStyle,
16367        window: &mut Window,
16368        cx: &mut Context<Self>,
16369    ) {
16370        let rem_size = window.rem_size();
16371        self.display_map.update(cx, |map, cx| {
16372            map.set_font(
16373                style.text.font(),
16374                style.text.font_size.to_pixels(rem_size),
16375                cx,
16376            )
16377        });
16378        self.style = Some(style);
16379    }
16380
16381    pub fn style(&self) -> Option<&EditorStyle> {
16382        self.style.as_ref()
16383    }
16384
16385    // Called by the element. This method is not designed to be called outside of the editor
16386    // element's layout code because it does not notify when rewrapping is computed synchronously.
16387    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16388        self.display_map
16389            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16390    }
16391
16392    pub fn set_soft_wrap(&mut self) {
16393        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16394    }
16395
16396    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16397        if self.soft_wrap_mode_override.is_some() {
16398            self.soft_wrap_mode_override.take();
16399        } else {
16400            let soft_wrap = match self.soft_wrap_mode(cx) {
16401                SoftWrap::GitDiff => return,
16402                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16403                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16404                    language_settings::SoftWrap::None
16405                }
16406            };
16407            self.soft_wrap_mode_override = Some(soft_wrap);
16408        }
16409        cx.notify();
16410    }
16411
16412    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16413        let Some(workspace) = self.workspace() else {
16414            return;
16415        };
16416        let fs = workspace.read(cx).app_state().fs.clone();
16417        let current_show = TabBarSettings::get_global(cx).show;
16418        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16419            setting.show = Some(!current_show);
16420        });
16421    }
16422
16423    pub fn toggle_indent_guides(
16424        &mut self,
16425        _: &ToggleIndentGuides,
16426        _: &mut Window,
16427        cx: &mut Context<Self>,
16428    ) {
16429        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16430            self.buffer
16431                .read(cx)
16432                .language_settings(cx)
16433                .indent_guides
16434                .enabled
16435        });
16436        self.show_indent_guides = Some(!currently_enabled);
16437        cx.notify();
16438    }
16439
16440    fn should_show_indent_guides(&self) -> Option<bool> {
16441        self.show_indent_guides
16442    }
16443
16444    pub fn toggle_line_numbers(
16445        &mut self,
16446        _: &ToggleLineNumbers,
16447        _: &mut Window,
16448        cx: &mut Context<Self>,
16449    ) {
16450        let mut editor_settings = EditorSettings::get_global(cx).clone();
16451        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16452        EditorSettings::override_global(editor_settings, cx);
16453    }
16454
16455    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16456        if let Some(show_line_numbers) = self.show_line_numbers {
16457            return show_line_numbers;
16458        }
16459        EditorSettings::get_global(cx).gutter.line_numbers
16460    }
16461
16462    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16463        self.use_relative_line_numbers
16464            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16465    }
16466
16467    pub fn toggle_relative_line_numbers(
16468        &mut self,
16469        _: &ToggleRelativeLineNumbers,
16470        _: &mut Window,
16471        cx: &mut Context<Self>,
16472    ) {
16473        let is_relative = self.should_use_relative_line_numbers(cx);
16474        self.set_relative_line_number(Some(!is_relative), cx)
16475    }
16476
16477    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16478        self.use_relative_line_numbers = is_relative;
16479        cx.notify();
16480    }
16481
16482    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16483        self.show_gutter = show_gutter;
16484        cx.notify();
16485    }
16486
16487    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16488        self.show_scrollbars = show_scrollbars;
16489        cx.notify();
16490    }
16491
16492    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16493        self.show_line_numbers = Some(show_line_numbers);
16494        cx.notify();
16495    }
16496
16497    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16498        self.disable_expand_excerpt_buttons = true;
16499        cx.notify();
16500    }
16501
16502    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16503        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16504        cx.notify();
16505    }
16506
16507    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16508        self.show_code_actions = Some(show_code_actions);
16509        cx.notify();
16510    }
16511
16512    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16513        self.show_runnables = Some(show_runnables);
16514        cx.notify();
16515    }
16516
16517    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16518        self.show_breakpoints = Some(show_breakpoints);
16519        cx.notify();
16520    }
16521
16522    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16523        if self.display_map.read(cx).masked != masked {
16524            self.display_map.update(cx, |map, _| map.masked = masked);
16525        }
16526        cx.notify()
16527    }
16528
16529    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16530        self.show_wrap_guides = Some(show_wrap_guides);
16531        cx.notify();
16532    }
16533
16534    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16535        self.show_indent_guides = Some(show_indent_guides);
16536        cx.notify();
16537    }
16538
16539    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16540        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16541            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16542                if let Some(dir) = file.abs_path(cx).parent() {
16543                    return Some(dir.to_owned());
16544                }
16545            }
16546
16547            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16548                return Some(project_path.path.to_path_buf());
16549            }
16550        }
16551
16552        None
16553    }
16554
16555    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16556        self.active_excerpt(cx)?
16557            .1
16558            .read(cx)
16559            .file()
16560            .and_then(|f| f.as_local())
16561    }
16562
16563    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16564        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16565            let buffer = buffer.read(cx);
16566            if let Some(project_path) = buffer.project_path(cx) {
16567                let project = self.project.as_ref()?.read(cx);
16568                project.absolute_path(&project_path, cx)
16569            } else {
16570                buffer
16571                    .file()
16572                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16573            }
16574        })
16575    }
16576
16577    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16578        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16579            let project_path = buffer.read(cx).project_path(cx)?;
16580            let project = self.project.as_ref()?.read(cx);
16581            let entry = project.entry_for_path(&project_path, cx)?;
16582            let path = entry.path.to_path_buf();
16583            Some(path)
16584        })
16585    }
16586
16587    pub fn reveal_in_finder(
16588        &mut self,
16589        _: &RevealInFileManager,
16590        _window: &mut Window,
16591        cx: &mut Context<Self>,
16592    ) {
16593        if let Some(target) = self.target_file(cx) {
16594            cx.reveal_path(&target.abs_path(cx));
16595        }
16596    }
16597
16598    pub fn copy_path(
16599        &mut self,
16600        _: &zed_actions::workspace::CopyPath,
16601        _window: &mut Window,
16602        cx: &mut Context<Self>,
16603    ) {
16604        if let Some(path) = self.target_file_abs_path(cx) {
16605            if let Some(path) = path.to_str() {
16606                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16607            }
16608        }
16609    }
16610
16611    pub fn copy_relative_path(
16612        &mut self,
16613        _: &zed_actions::workspace::CopyRelativePath,
16614        _window: &mut Window,
16615        cx: &mut Context<Self>,
16616    ) {
16617        if let Some(path) = self.target_file_path(cx) {
16618            if let Some(path) = path.to_str() {
16619                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16620            }
16621        }
16622    }
16623
16624    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16625        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16626            buffer.read(cx).project_path(cx)
16627        } else {
16628            None
16629        }
16630    }
16631
16632    // Returns true if the editor handled a go-to-line request
16633    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16634        maybe!({
16635            let breakpoint_store = self.breakpoint_store.as_ref()?;
16636
16637            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16638            else {
16639                self.clear_row_highlights::<ActiveDebugLine>();
16640                return None;
16641            };
16642
16643            let position = active_stack_frame.position;
16644            let buffer_id = position.buffer_id?;
16645            let snapshot = self
16646                .project
16647                .as_ref()?
16648                .read(cx)
16649                .buffer_for_id(buffer_id, cx)?
16650                .read(cx)
16651                .snapshot();
16652
16653            let mut handled = false;
16654            for (id, ExcerptRange { context, .. }) in
16655                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16656            {
16657                if context.start.cmp(&position, &snapshot).is_ge()
16658                    || context.end.cmp(&position, &snapshot).is_lt()
16659                {
16660                    continue;
16661                }
16662                let snapshot = self.buffer.read(cx).snapshot(cx);
16663                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16664
16665                handled = true;
16666                self.clear_row_highlights::<ActiveDebugLine>();
16667                self.go_to_line::<ActiveDebugLine>(
16668                    multibuffer_anchor,
16669                    Some(cx.theme().colors().editor_debugger_active_line_background),
16670                    window,
16671                    cx,
16672                );
16673
16674                cx.notify();
16675            }
16676
16677            handled.then_some(())
16678        })
16679        .is_some()
16680    }
16681
16682    pub fn copy_file_name_without_extension(
16683        &mut self,
16684        _: &CopyFileNameWithoutExtension,
16685        _: &mut Window,
16686        cx: &mut Context<Self>,
16687    ) {
16688        if let Some(file) = self.target_file(cx) {
16689            if let Some(file_stem) = file.path().file_stem() {
16690                if let Some(name) = file_stem.to_str() {
16691                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16692                }
16693            }
16694        }
16695    }
16696
16697    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16698        if let Some(file) = self.target_file(cx) {
16699            if let Some(file_name) = file.path().file_name() {
16700                if let Some(name) = file_name.to_str() {
16701                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16702                }
16703            }
16704        }
16705    }
16706
16707    pub fn toggle_git_blame(
16708        &mut self,
16709        _: &::git::Blame,
16710        window: &mut Window,
16711        cx: &mut Context<Self>,
16712    ) {
16713        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16714
16715        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16716            self.start_git_blame(true, window, cx);
16717        }
16718
16719        cx.notify();
16720    }
16721
16722    pub fn toggle_git_blame_inline(
16723        &mut self,
16724        _: &ToggleGitBlameInline,
16725        window: &mut Window,
16726        cx: &mut Context<Self>,
16727    ) {
16728        self.toggle_git_blame_inline_internal(true, window, cx);
16729        cx.notify();
16730    }
16731
16732    pub fn open_git_blame_commit(
16733        &mut self,
16734        _: &OpenGitBlameCommit,
16735        window: &mut Window,
16736        cx: &mut Context<Self>,
16737    ) {
16738        self.open_git_blame_commit_internal(window, cx);
16739    }
16740
16741    fn open_git_blame_commit_internal(
16742        &mut self,
16743        window: &mut Window,
16744        cx: &mut Context<Self>,
16745    ) -> Option<()> {
16746        let blame = self.blame.as_ref()?;
16747        let snapshot = self.snapshot(window, cx);
16748        let cursor = self.selections.newest::<Point>(cx).head();
16749        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16750        let blame_entry = blame
16751            .update(cx, |blame, cx| {
16752                blame
16753                    .blame_for_rows(
16754                        &[RowInfo {
16755                            buffer_id: Some(buffer.remote_id()),
16756                            buffer_row: Some(point.row),
16757                            ..Default::default()
16758                        }],
16759                        cx,
16760                    )
16761                    .next()
16762            })
16763            .flatten()?;
16764        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16765        let repo = blame.read(cx).repository(cx)?;
16766        let workspace = self.workspace()?.downgrade();
16767        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16768        None
16769    }
16770
16771    pub fn git_blame_inline_enabled(&self) -> bool {
16772        self.git_blame_inline_enabled
16773    }
16774
16775    pub fn toggle_selection_menu(
16776        &mut self,
16777        _: &ToggleSelectionMenu,
16778        _: &mut Window,
16779        cx: &mut Context<Self>,
16780    ) {
16781        self.show_selection_menu = self
16782            .show_selection_menu
16783            .map(|show_selections_menu| !show_selections_menu)
16784            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16785
16786        cx.notify();
16787    }
16788
16789    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16790        self.show_selection_menu
16791            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16792    }
16793
16794    fn start_git_blame(
16795        &mut self,
16796        user_triggered: bool,
16797        window: &mut Window,
16798        cx: &mut Context<Self>,
16799    ) {
16800        if let Some(project) = self.project.as_ref() {
16801            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16802                return;
16803            };
16804
16805            if buffer.read(cx).file().is_none() {
16806                return;
16807            }
16808
16809            let focused = self.focus_handle(cx).contains_focused(window, cx);
16810
16811            let project = project.clone();
16812            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16813            self.blame_subscription =
16814                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16815            self.blame = Some(blame);
16816        }
16817    }
16818
16819    fn toggle_git_blame_inline_internal(
16820        &mut self,
16821        user_triggered: bool,
16822        window: &mut Window,
16823        cx: &mut Context<Self>,
16824    ) {
16825        if self.git_blame_inline_enabled {
16826            self.git_blame_inline_enabled = false;
16827            self.show_git_blame_inline = false;
16828            self.show_git_blame_inline_delay_task.take();
16829        } else {
16830            self.git_blame_inline_enabled = true;
16831            self.start_git_blame_inline(user_triggered, window, cx);
16832        }
16833
16834        cx.notify();
16835    }
16836
16837    fn start_git_blame_inline(
16838        &mut self,
16839        user_triggered: bool,
16840        window: &mut Window,
16841        cx: &mut Context<Self>,
16842    ) {
16843        self.start_git_blame(user_triggered, window, cx);
16844
16845        if ProjectSettings::get_global(cx)
16846            .git
16847            .inline_blame_delay()
16848            .is_some()
16849        {
16850            self.start_inline_blame_timer(window, cx);
16851        } else {
16852            self.show_git_blame_inline = true
16853        }
16854    }
16855
16856    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16857        self.blame.as_ref()
16858    }
16859
16860    pub fn show_git_blame_gutter(&self) -> bool {
16861        self.show_git_blame_gutter
16862    }
16863
16864    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16865        self.show_git_blame_gutter && self.has_blame_entries(cx)
16866    }
16867
16868    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16869        self.show_git_blame_inline
16870            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16871            && !self.newest_selection_head_on_empty_line(cx)
16872            && self.has_blame_entries(cx)
16873    }
16874
16875    fn has_blame_entries(&self, cx: &App) -> bool {
16876        self.blame()
16877            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16878    }
16879
16880    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16881        let cursor_anchor = self.selections.newest_anchor().head();
16882
16883        let snapshot = self.buffer.read(cx).snapshot(cx);
16884        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16885
16886        snapshot.line_len(buffer_row) == 0
16887    }
16888
16889    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16890        let buffer_and_selection = maybe!({
16891            let selection = self.selections.newest::<Point>(cx);
16892            let selection_range = selection.range();
16893
16894            let multi_buffer = self.buffer().read(cx);
16895            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16896            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16897
16898            let (buffer, range, _) = if selection.reversed {
16899                buffer_ranges.first()
16900            } else {
16901                buffer_ranges.last()
16902            }?;
16903
16904            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16905                ..text::ToPoint::to_point(&range.end, &buffer).row;
16906            Some((
16907                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16908                selection,
16909            ))
16910        });
16911
16912        let Some((buffer, selection)) = buffer_and_selection else {
16913            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16914        };
16915
16916        let Some(project) = self.project.as_ref() else {
16917            return Task::ready(Err(anyhow!("editor does not have project")));
16918        };
16919
16920        project.update(cx, |project, cx| {
16921            project.get_permalink_to_line(&buffer, selection, cx)
16922        })
16923    }
16924
16925    pub fn copy_permalink_to_line(
16926        &mut self,
16927        _: &CopyPermalinkToLine,
16928        window: &mut Window,
16929        cx: &mut Context<Self>,
16930    ) {
16931        let permalink_task = self.get_permalink_to_line(cx);
16932        let workspace = self.workspace();
16933
16934        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16935            Ok(permalink) => {
16936                cx.update(|_, cx| {
16937                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16938                })
16939                .ok();
16940            }
16941            Err(err) => {
16942                let message = format!("Failed to copy permalink: {err}");
16943
16944                Err::<(), anyhow::Error>(err).log_err();
16945
16946                if let Some(workspace) = workspace {
16947                    workspace
16948                        .update_in(cx, |workspace, _, cx| {
16949                            struct CopyPermalinkToLine;
16950
16951                            workspace.show_toast(
16952                                Toast::new(
16953                                    NotificationId::unique::<CopyPermalinkToLine>(),
16954                                    message,
16955                                ),
16956                                cx,
16957                            )
16958                        })
16959                        .ok();
16960                }
16961            }
16962        })
16963        .detach();
16964    }
16965
16966    pub fn copy_file_location(
16967        &mut self,
16968        _: &CopyFileLocation,
16969        _: &mut Window,
16970        cx: &mut Context<Self>,
16971    ) {
16972        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16973        if let Some(file) = self.target_file(cx) {
16974            if let Some(path) = file.path().to_str() {
16975                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16976            }
16977        }
16978    }
16979
16980    pub fn open_permalink_to_line(
16981        &mut self,
16982        _: &OpenPermalinkToLine,
16983        window: &mut Window,
16984        cx: &mut Context<Self>,
16985    ) {
16986        let permalink_task = self.get_permalink_to_line(cx);
16987        let workspace = self.workspace();
16988
16989        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16990            Ok(permalink) => {
16991                cx.update(|_, cx| {
16992                    cx.open_url(permalink.as_ref());
16993                })
16994                .ok();
16995            }
16996            Err(err) => {
16997                let message = format!("Failed to open permalink: {err}");
16998
16999                Err::<(), anyhow::Error>(err).log_err();
17000
17001                if let Some(workspace) = workspace {
17002                    workspace
17003                        .update(cx, |workspace, cx| {
17004                            struct OpenPermalinkToLine;
17005
17006                            workspace.show_toast(
17007                                Toast::new(
17008                                    NotificationId::unique::<OpenPermalinkToLine>(),
17009                                    message,
17010                                ),
17011                                cx,
17012                            )
17013                        })
17014                        .ok();
17015                }
17016            }
17017        })
17018        .detach();
17019    }
17020
17021    pub fn insert_uuid_v4(
17022        &mut self,
17023        _: &InsertUuidV4,
17024        window: &mut Window,
17025        cx: &mut Context<Self>,
17026    ) {
17027        self.insert_uuid(UuidVersion::V4, window, cx);
17028    }
17029
17030    pub fn insert_uuid_v7(
17031        &mut self,
17032        _: &InsertUuidV7,
17033        window: &mut Window,
17034        cx: &mut Context<Self>,
17035    ) {
17036        self.insert_uuid(UuidVersion::V7, window, cx);
17037    }
17038
17039    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17040        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17041        self.transact(window, cx, |this, window, cx| {
17042            let edits = this
17043                .selections
17044                .all::<Point>(cx)
17045                .into_iter()
17046                .map(|selection| {
17047                    let uuid = match version {
17048                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17049                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17050                    };
17051
17052                    (selection.range(), uuid.to_string())
17053                });
17054            this.edit(edits, cx);
17055            this.refresh_inline_completion(true, false, window, cx);
17056        });
17057    }
17058
17059    pub fn open_selections_in_multibuffer(
17060        &mut self,
17061        _: &OpenSelectionsInMultibuffer,
17062        window: &mut Window,
17063        cx: &mut Context<Self>,
17064    ) {
17065        let multibuffer = self.buffer.read(cx);
17066
17067        let Some(buffer) = multibuffer.as_singleton() else {
17068            return;
17069        };
17070
17071        let Some(workspace) = self.workspace() else {
17072            return;
17073        };
17074
17075        let locations = self
17076            .selections
17077            .disjoint_anchors()
17078            .iter()
17079            .map(|range| Location {
17080                buffer: buffer.clone(),
17081                range: range.start.text_anchor..range.end.text_anchor,
17082            })
17083            .collect::<Vec<_>>();
17084
17085        let title = multibuffer.title(cx).to_string();
17086
17087        cx.spawn_in(window, async move |_, cx| {
17088            workspace.update_in(cx, |workspace, window, cx| {
17089                Self::open_locations_in_multibuffer(
17090                    workspace,
17091                    locations,
17092                    format!("Selections for '{title}'"),
17093                    false,
17094                    MultibufferSelectionMode::All,
17095                    window,
17096                    cx,
17097                );
17098            })
17099        })
17100        .detach();
17101    }
17102
17103    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17104    /// last highlight added will be used.
17105    ///
17106    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17107    pub fn highlight_rows<T: 'static>(
17108        &mut self,
17109        range: Range<Anchor>,
17110        color: Hsla,
17111        options: RowHighlightOptions,
17112        cx: &mut Context<Self>,
17113    ) {
17114        let snapshot = self.buffer().read(cx).snapshot(cx);
17115        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17116        let ix = row_highlights.binary_search_by(|highlight| {
17117            Ordering::Equal
17118                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17119                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17120        });
17121
17122        if let Err(mut ix) = ix {
17123            let index = post_inc(&mut self.highlight_order);
17124
17125            // If this range intersects with the preceding highlight, then merge it with
17126            // the preceding highlight. Otherwise insert a new highlight.
17127            let mut merged = false;
17128            if ix > 0 {
17129                let prev_highlight = &mut row_highlights[ix - 1];
17130                if prev_highlight
17131                    .range
17132                    .end
17133                    .cmp(&range.start, &snapshot)
17134                    .is_ge()
17135                {
17136                    ix -= 1;
17137                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17138                        prev_highlight.range.end = range.end;
17139                    }
17140                    merged = true;
17141                    prev_highlight.index = index;
17142                    prev_highlight.color = color;
17143                    prev_highlight.options = options;
17144                }
17145            }
17146
17147            if !merged {
17148                row_highlights.insert(
17149                    ix,
17150                    RowHighlight {
17151                        range: range.clone(),
17152                        index,
17153                        color,
17154                        options,
17155                        type_id: TypeId::of::<T>(),
17156                    },
17157                );
17158            }
17159
17160            // If any of the following highlights intersect with this one, merge them.
17161            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17162                let highlight = &row_highlights[ix];
17163                if next_highlight
17164                    .range
17165                    .start
17166                    .cmp(&highlight.range.end, &snapshot)
17167                    .is_le()
17168                {
17169                    if next_highlight
17170                        .range
17171                        .end
17172                        .cmp(&highlight.range.end, &snapshot)
17173                        .is_gt()
17174                    {
17175                        row_highlights[ix].range.end = next_highlight.range.end;
17176                    }
17177                    row_highlights.remove(ix + 1);
17178                } else {
17179                    break;
17180                }
17181            }
17182        }
17183    }
17184
17185    /// Remove any highlighted row ranges of the given type that intersect the
17186    /// given ranges.
17187    pub fn remove_highlighted_rows<T: 'static>(
17188        &mut self,
17189        ranges_to_remove: Vec<Range<Anchor>>,
17190        cx: &mut Context<Self>,
17191    ) {
17192        let snapshot = self.buffer().read(cx).snapshot(cx);
17193        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17194        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17195        row_highlights.retain(|highlight| {
17196            while let Some(range_to_remove) = ranges_to_remove.peek() {
17197                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17198                    Ordering::Less | Ordering::Equal => {
17199                        ranges_to_remove.next();
17200                    }
17201                    Ordering::Greater => {
17202                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17203                            Ordering::Less | Ordering::Equal => {
17204                                return false;
17205                            }
17206                            Ordering::Greater => break,
17207                        }
17208                    }
17209                }
17210            }
17211
17212            true
17213        })
17214    }
17215
17216    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17217    pub fn clear_row_highlights<T: 'static>(&mut self) {
17218        self.highlighted_rows.remove(&TypeId::of::<T>());
17219    }
17220
17221    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17222    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17223        self.highlighted_rows
17224            .get(&TypeId::of::<T>())
17225            .map_or(&[] as &[_], |vec| vec.as_slice())
17226            .iter()
17227            .map(|highlight| (highlight.range.clone(), highlight.color))
17228    }
17229
17230    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17231    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17232    /// Allows to ignore certain kinds of highlights.
17233    pub fn highlighted_display_rows(
17234        &self,
17235        window: &mut Window,
17236        cx: &mut App,
17237    ) -> BTreeMap<DisplayRow, LineHighlight> {
17238        let snapshot = self.snapshot(window, cx);
17239        let mut used_highlight_orders = HashMap::default();
17240        self.highlighted_rows
17241            .iter()
17242            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17243            .fold(
17244                BTreeMap::<DisplayRow, LineHighlight>::new(),
17245                |mut unique_rows, highlight| {
17246                    let start = highlight.range.start.to_display_point(&snapshot);
17247                    let end = highlight.range.end.to_display_point(&snapshot);
17248                    let start_row = start.row().0;
17249                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17250                        && end.column() == 0
17251                    {
17252                        end.row().0.saturating_sub(1)
17253                    } else {
17254                        end.row().0
17255                    };
17256                    for row in start_row..=end_row {
17257                        let used_index =
17258                            used_highlight_orders.entry(row).or_insert(highlight.index);
17259                        if highlight.index >= *used_index {
17260                            *used_index = highlight.index;
17261                            unique_rows.insert(
17262                                DisplayRow(row),
17263                                LineHighlight {
17264                                    include_gutter: highlight.options.include_gutter,
17265                                    border: None,
17266                                    background: highlight.color.into(),
17267                                    type_id: Some(highlight.type_id),
17268                                },
17269                            );
17270                        }
17271                    }
17272                    unique_rows
17273                },
17274            )
17275    }
17276
17277    pub fn highlighted_display_row_for_autoscroll(
17278        &self,
17279        snapshot: &DisplaySnapshot,
17280    ) -> Option<DisplayRow> {
17281        self.highlighted_rows
17282            .values()
17283            .flat_map(|highlighted_rows| highlighted_rows.iter())
17284            .filter_map(|highlight| {
17285                if highlight.options.autoscroll {
17286                    Some(highlight.range.start.to_display_point(snapshot).row())
17287                } else {
17288                    None
17289                }
17290            })
17291            .min()
17292    }
17293
17294    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17295        self.highlight_background::<SearchWithinRange>(
17296            ranges,
17297            |colors| colors.editor_document_highlight_read_background,
17298            cx,
17299        )
17300    }
17301
17302    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17303        self.breadcrumb_header = Some(new_header);
17304    }
17305
17306    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17307        self.clear_background_highlights::<SearchWithinRange>(cx);
17308    }
17309
17310    pub fn highlight_background<T: 'static>(
17311        &mut self,
17312        ranges: &[Range<Anchor>],
17313        color_fetcher: fn(&ThemeColors) -> Hsla,
17314        cx: &mut Context<Self>,
17315    ) {
17316        self.background_highlights
17317            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17318        self.scrollbar_marker_state.dirty = true;
17319        cx.notify();
17320    }
17321
17322    pub fn clear_background_highlights<T: 'static>(
17323        &mut self,
17324        cx: &mut Context<Self>,
17325    ) -> Option<BackgroundHighlight> {
17326        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17327        if !text_highlights.1.is_empty() {
17328            self.scrollbar_marker_state.dirty = true;
17329            cx.notify();
17330        }
17331        Some(text_highlights)
17332    }
17333
17334    pub fn highlight_gutter<T: 'static>(
17335        &mut self,
17336        ranges: &[Range<Anchor>],
17337        color_fetcher: fn(&App) -> Hsla,
17338        cx: &mut Context<Self>,
17339    ) {
17340        self.gutter_highlights
17341            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17342        cx.notify();
17343    }
17344
17345    pub fn clear_gutter_highlights<T: 'static>(
17346        &mut self,
17347        cx: &mut Context<Self>,
17348    ) -> Option<GutterHighlight> {
17349        cx.notify();
17350        self.gutter_highlights.remove(&TypeId::of::<T>())
17351    }
17352
17353    #[cfg(feature = "test-support")]
17354    pub fn all_text_background_highlights(
17355        &self,
17356        window: &mut Window,
17357        cx: &mut Context<Self>,
17358    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17359        let snapshot = self.snapshot(window, cx);
17360        let buffer = &snapshot.buffer_snapshot;
17361        let start = buffer.anchor_before(0);
17362        let end = buffer.anchor_after(buffer.len());
17363        let theme = cx.theme().colors();
17364        self.background_highlights_in_range(start..end, &snapshot, theme)
17365    }
17366
17367    #[cfg(feature = "test-support")]
17368    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17369        let snapshot = self.buffer().read(cx).snapshot(cx);
17370
17371        let highlights = self
17372            .background_highlights
17373            .get(&TypeId::of::<items::BufferSearchHighlights>());
17374
17375        if let Some((_color, ranges)) = highlights {
17376            ranges
17377                .iter()
17378                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17379                .collect_vec()
17380        } else {
17381            vec![]
17382        }
17383    }
17384
17385    fn document_highlights_for_position<'a>(
17386        &'a self,
17387        position: Anchor,
17388        buffer: &'a MultiBufferSnapshot,
17389    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17390        let read_highlights = self
17391            .background_highlights
17392            .get(&TypeId::of::<DocumentHighlightRead>())
17393            .map(|h| &h.1);
17394        let write_highlights = self
17395            .background_highlights
17396            .get(&TypeId::of::<DocumentHighlightWrite>())
17397            .map(|h| &h.1);
17398        let left_position = position.bias_left(buffer);
17399        let right_position = position.bias_right(buffer);
17400        read_highlights
17401            .into_iter()
17402            .chain(write_highlights)
17403            .flat_map(move |ranges| {
17404                let start_ix = match ranges.binary_search_by(|probe| {
17405                    let cmp = probe.end.cmp(&left_position, buffer);
17406                    if cmp.is_ge() {
17407                        Ordering::Greater
17408                    } else {
17409                        Ordering::Less
17410                    }
17411                }) {
17412                    Ok(i) | Err(i) => i,
17413                };
17414
17415                ranges[start_ix..]
17416                    .iter()
17417                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17418            })
17419    }
17420
17421    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17422        self.background_highlights
17423            .get(&TypeId::of::<T>())
17424            .map_or(false, |(_, highlights)| !highlights.is_empty())
17425    }
17426
17427    pub fn background_highlights_in_range(
17428        &self,
17429        search_range: Range<Anchor>,
17430        display_snapshot: &DisplaySnapshot,
17431        theme: &ThemeColors,
17432    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17433        let mut results = Vec::new();
17434        for (color_fetcher, ranges) in self.background_highlights.values() {
17435            let color = color_fetcher(theme);
17436            let start_ix = match ranges.binary_search_by(|probe| {
17437                let cmp = probe
17438                    .end
17439                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17440                if cmp.is_gt() {
17441                    Ordering::Greater
17442                } else {
17443                    Ordering::Less
17444                }
17445            }) {
17446                Ok(i) | Err(i) => i,
17447            };
17448            for range in &ranges[start_ix..] {
17449                if range
17450                    .start
17451                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17452                    .is_ge()
17453                {
17454                    break;
17455                }
17456
17457                let start = range.start.to_display_point(display_snapshot);
17458                let end = range.end.to_display_point(display_snapshot);
17459                results.push((start..end, color))
17460            }
17461        }
17462        results
17463    }
17464
17465    pub fn background_highlight_row_ranges<T: 'static>(
17466        &self,
17467        search_range: Range<Anchor>,
17468        display_snapshot: &DisplaySnapshot,
17469        count: usize,
17470    ) -> Vec<RangeInclusive<DisplayPoint>> {
17471        let mut results = Vec::new();
17472        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17473            return vec![];
17474        };
17475
17476        let start_ix = match ranges.binary_search_by(|probe| {
17477            let cmp = probe
17478                .end
17479                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17480            if cmp.is_gt() {
17481                Ordering::Greater
17482            } else {
17483                Ordering::Less
17484            }
17485        }) {
17486            Ok(i) | Err(i) => i,
17487        };
17488        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17489            if let (Some(start_display), Some(end_display)) = (start, end) {
17490                results.push(
17491                    start_display.to_display_point(display_snapshot)
17492                        ..=end_display.to_display_point(display_snapshot),
17493                );
17494            }
17495        };
17496        let mut start_row: Option<Point> = None;
17497        let mut end_row: Option<Point> = None;
17498        if ranges.len() > count {
17499            return Vec::new();
17500        }
17501        for range in &ranges[start_ix..] {
17502            if range
17503                .start
17504                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17505                .is_ge()
17506            {
17507                break;
17508            }
17509            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17510            if let Some(current_row) = &end_row {
17511                if end.row == current_row.row {
17512                    continue;
17513                }
17514            }
17515            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17516            if start_row.is_none() {
17517                assert_eq!(end_row, None);
17518                start_row = Some(start);
17519                end_row = Some(end);
17520                continue;
17521            }
17522            if let Some(current_end) = end_row.as_mut() {
17523                if start.row > current_end.row + 1 {
17524                    push_region(start_row, end_row);
17525                    start_row = Some(start);
17526                    end_row = Some(end);
17527                } else {
17528                    // Merge two hunks.
17529                    *current_end = end;
17530                }
17531            } else {
17532                unreachable!();
17533            }
17534        }
17535        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17536        push_region(start_row, end_row);
17537        results
17538    }
17539
17540    pub fn gutter_highlights_in_range(
17541        &self,
17542        search_range: Range<Anchor>,
17543        display_snapshot: &DisplaySnapshot,
17544        cx: &App,
17545    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17546        let mut results = Vec::new();
17547        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17548            let color = color_fetcher(cx);
17549            let start_ix = match ranges.binary_search_by(|probe| {
17550                let cmp = probe
17551                    .end
17552                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17553                if cmp.is_gt() {
17554                    Ordering::Greater
17555                } else {
17556                    Ordering::Less
17557                }
17558            }) {
17559                Ok(i) | Err(i) => i,
17560            };
17561            for range in &ranges[start_ix..] {
17562                if range
17563                    .start
17564                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17565                    .is_ge()
17566                {
17567                    break;
17568                }
17569
17570                let start = range.start.to_display_point(display_snapshot);
17571                let end = range.end.to_display_point(display_snapshot);
17572                results.push((start..end, color))
17573            }
17574        }
17575        results
17576    }
17577
17578    /// Get the text ranges corresponding to the redaction query
17579    pub fn redacted_ranges(
17580        &self,
17581        search_range: Range<Anchor>,
17582        display_snapshot: &DisplaySnapshot,
17583        cx: &App,
17584    ) -> Vec<Range<DisplayPoint>> {
17585        display_snapshot
17586            .buffer_snapshot
17587            .redacted_ranges(search_range, |file| {
17588                if let Some(file) = file {
17589                    file.is_private()
17590                        && EditorSettings::get(
17591                            Some(SettingsLocation {
17592                                worktree_id: file.worktree_id(cx),
17593                                path: file.path().as_ref(),
17594                            }),
17595                            cx,
17596                        )
17597                        .redact_private_values
17598                } else {
17599                    false
17600                }
17601            })
17602            .map(|range| {
17603                range.start.to_display_point(display_snapshot)
17604                    ..range.end.to_display_point(display_snapshot)
17605            })
17606            .collect()
17607    }
17608
17609    pub fn highlight_text<T: 'static>(
17610        &mut self,
17611        ranges: Vec<Range<Anchor>>,
17612        style: HighlightStyle,
17613        cx: &mut Context<Self>,
17614    ) {
17615        self.display_map.update(cx, |map, _| {
17616            map.highlight_text(TypeId::of::<T>(), ranges, style)
17617        });
17618        cx.notify();
17619    }
17620
17621    pub(crate) fn highlight_inlays<T: 'static>(
17622        &mut self,
17623        highlights: Vec<InlayHighlight>,
17624        style: HighlightStyle,
17625        cx: &mut Context<Self>,
17626    ) {
17627        self.display_map.update(cx, |map, _| {
17628            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17629        });
17630        cx.notify();
17631    }
17632
17633    pub fn text_highlights<'a, T: 'static>(
17634        &'a self,
17635        cx: &'a App,
17636    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17637        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17638    }
17639
17640    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17641        let cleared = self
17642            .display_map
17643            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17644        if cleared {
17645            cx.notify();
17646        }
17647    }
17648
17649    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17650        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17651            && self.focus_handle.is_focused(window)
17652    }
17653
17654    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17655        self.show_cursor_when_unfocused = is_enabled;
17656        cx.notify();
17657    }
17658
17659    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17660        cx.notify();
17661    }
17662
17663    fn on_debug_session_event(
17664        &mut self,
17665        _session: Entity<Session>,
17666        event: &SessionEvent,
17667        cx: &mut Context<Self>,
17668    ) {
17669        match event {
17670            SessionEvent::InvalidateInlineValue => {
17671                self.refresh_inline_values(cx);
17672            }
17673            _ => {}
17674        }
17675    }
17676
17677    fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17678        let Some(project) = self.project.clone() else {
17679            return;
17680        };
17681        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17682            return;
17683        };
17684        if !self.inline_value_cache.enabled {
17685            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17686            self.splice_inlays(&inlays, Vec::new(), cx);
17687            return;
17688        }
17689
17690        let current_execution_position = self
17691            .highlighted_rows
17692            .get(&TypeId::of::<ActiveDebugLine>())
17693            .and_then(|lines| lines.last().map(|line| line.range.start));
17694
17695        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17696            let snapshot = editor
17697                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17698                .ok()?;
17699
17700            let inline_values = editor
17701                .update(cx, |_, cx| {
17702                    let Some(current_execution_position) = current_execution_position else {
17703                        return Some(Task::ready(Ok(Vec::new())));
17704                    };
17705
17706                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17707                    // anchor is in the same buffer
17708                    let range =
17709                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17710                    project.inline_values(buffer, range, cx)
17711                })
17712                .ok()
17713                .flatten()?
17714                .await
17715                .context("refreshing debugger inlays")
17716                .log_err()?;
17717
17718            let (excerpt_id, buffer_id) = snapshot
17719                .excerpts()
17720                .next()
17721                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17722            editor
17723                .update(cx, |editor, cx| {
17724                    let new_inlays = inline_values
17725                        .into_iter()
17726                        .map(|debugger_value| {
17727                            Inlay::debugger_hint(
17728                                post_inc(&mut editor.next_inlay_id),
17729                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17730                                debugger_value.text(),
17731                            )
17732                        })
17733                        .collect::<Vec<_>>();
17734                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17735                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17736
17737                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17738                })
17739                .ok()?;
17740            Some(())
17741        });
17742    }
17743
17744    fn on_buffer_event(
17745        &mut self,
17746        multibuffer: &Entity<MultiBuffer>,
17747        event: &multi_buffer::Event,
17748        window: &mut Window,
17749        cx: &mut Context<Self>,
17750    ) {
17751        match event {
17752            multi_buffer::Event::Edited {
17753                singleton_buffer_edited,
17754                edited_buffer: buffer_edited,
17755            } => {
17756                self.scrollbar_marker_state.dirty = true;
17757                self.active_indent_guides_state.dirty = true;
17758                self.refresh_active_diagnostics(cx);
17759                self.refresh_code_actions(window, cx);
17760                self.refresh_selected_text_highlights(true, window, cx);
17761                refresh_matching_bracket_highlights(self, window, cx);
17762                if self.has_active_inline_completion() {
17763                    self.update_visible_inline_completion(window, cx);
17764                }
17765                if let Some(buffer) = buffer_edited {
17766                    let buffer_id = buffer.read(cx).remote_id();
17767                    if !self.registered_buffers.contains_key(&buffer_id) {
17768                        if let Some(project) = self.project.as_ref() {
17769                            project.update(cx, |project, cx| {
17770                                self.registered_buffers.insert(
17771                                    buffer_id,
17772                                    project.register_buffer_with_language_servers(&buffer, cx),
17773                                );
17774                            })
17775                        }
17776                    }
17777                }
17778                cx.emit(EditorEvent::BufferEdited);
17779                cx.emit(SearchEvent::MatchesInvalidated);
17780                if *singleton_buffer_edited {
17781                    if let Some(project) = &self.project {
17782                        #[allow(clippy::mutable_key_type)]
17783                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17784                            multibuffer
17785                                .all_buffers()
17786                                .into_iter()
17787                                .filter_map(|buffer| {
17788                                    buffer.update(cx, |buffer, cx| {
17789                                        let language = buffer.language()?;
17790                                        let should_discard = project.update(cx, |project, cx| {
17791                                            project.is_local()
17792                                                && !project.has_language_servers_for(buffer, cx)
17793                                        });
17794                                        should_discard.not().then_some(language.clone())
17795                                    })
17796                                })
17797                                .collect::<HashSet<_>>()
17798                        });
17799                        if !languages_affected.is_empty() {
17800                            self.refresh_inlay_hints(
17801                                InlayHintRefreshReason::BufferEdited(languages_affected),
17802                                cx,
17803                            );
17804                        }
17805                    }
17806                }
17807
17808                let Some(project) = &self.project else { return };
17809                let (telemetry, is_via_ssh) = {
17810                    let project = project.read(cx);
17811                    let telemetry = project.client().telemetry().clone();
17812                    let is_via_ssh = project.is_via_ssh();
17813                    (telemetry, is_via_ssh)
17814                };
17815                refresh_linked_ranges(self, window, cx);
17816                telemetry.log_edit_event("editor", is_via_ssh);
17817            }
17818            multi_buffer::Event::ExcerptsAdded {
17819                buffer,
17820                predecessor,
17821                excerpts,
17822            } => {
17823                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17824                let buffer_id = buffer.read(cx).remote_id();
17825                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17826                    if let Some(project) = &self.project {
17827                        update_uncommitted_diff_for_buffer(
17828                            cx.entity(),
17829                            project,
17830                            [buffer.clone()],
17831                            self.buffer.clone(),
17832                            cx,
17833                        )
17834                        .detach();
17835                    }
17836                }
17837                cx.emit(EditorEvent::ExcerptsAdded {
17838                    buffer: buffer.clone(),
17839                    predecessor: *predecessor,
17840                    excerpts: excerpts.clone(),
17841                });
17842                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17843            }
17844            multi_buffer::Event::ExcerptsRemoved {
17845                ids,
17846                removed_buffer_ids,
17847            } => {
17848                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17849                let buffer = self.buffer.read(cx);
17850                self.registered_buffers
17851                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17852                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17853                cx.emit(EditorEvent::ExcerptsRemoved {
17854                    ids: ids.clone(),
17855                    removed_buffer_ids: removed_buffer_ids.clone(),
17856                })
17857            }
17858            multi_buffer::Event::ExcerptsEdited {
17859                excerpt_ids,
17860                buffer_ids,
17861            } => {
17862                self.display_map.update(cx, |map, cx| {
17863                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17864                });
17865                cx.emit(EditorEvent::ExcerptsEdited {
17866                    ids: excerpt_ids.clone(),
17867                })
17868            }
17869            multi_buffer::Event::ExcerptsExpanded { ids } => {
17870                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17871                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17872            }
17873            multi_buffer::Event::Reparsed(buffer_id) => {
17874                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17875                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17876
17877                cx.emit(EditorEvent::Reparsed(*buffer_id));
17878            }
17879            multi_buffer::Event::DiffHunksToggled => {
17880                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17881            }
17882            multi_buffer::Event::LanguageChanged(buffer_id) => {
17883                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17884                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17885                cx.emit(EditorEvent::Reparsed(*buffer_id));
17886                cx.notify();
17887            }
17888            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17889            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17890            multi_buffer::Event::FileHandleChanged
17891            | multi_buffer::Event::Reloaded
17892            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17893            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17894            multi_buffer::Event::DiagnosticsUpdated => {
17895                self.refresh_active_diagnostics(cx);
17896                self.refresh_inline_diagnostics(true, window, cx);
17897                self.scrollbar_marker_state.dirty = true;
17898                cx.notify();
17899            }
17900            _ => {}
17901        };
17902    }
17903
17904    pub fn start_temporary_diff_override(&mut self) {
17905        self.load_diff_task.take();
17906        self.temporary_diff_override = true;
17907    }
17908
17909    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17910        self.temporary_diff_override = false;
17911        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17912        self.buffer.update(cx, |buffer, cx| {
17913            buffer.set_all_diff_hunks_collapsed(cx);
17914        });
17915
17916        if let Some(project) = self.project.clone() {
17917            self.load_diff_task = Some(
17918                update_uncommitted_diff_for_buffer(
17919                    cx.entity(),
17920                    &project,
17921                    self.buffer.read(cx).all_buffers(),
17922                    self.buffer.clone(),
17923                    cx,
17924                )
17925                .shared(),
17926            );
17927        }
17928    }
17929
17930    fn on_display_map_changed(
17931        &mut self,
17932        _: Entity<DisplayMap>,
17933        _: &mut Window,
17934        cx: &mut Context<Self>,
17935    ) {
17936        cx.notify();
17937    }
17938
17939    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17940        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17941        self.update_edit_prediction_settings(cx);
17942        self.refresh_inline_completion(true, false, window, cx);
17943        self.refresh_inlay_hints(
17944            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17945                self.selections.newest_anchor().head(),
17946                &self.buffer.read(cx).snapshot(cx),
17947                cx,
17948            )),
17949            cx,
17950        );
17951
17952        let old_cursor_shape = self.cursor_shape;
17953
17954        {
17955            let editor_settings = EditorSettings::get_global(cx);
17956            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17957            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17958            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17959            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17960        }
17961
17962        if old_cursor_shape != self.cursor_shape {
17963            cx.emit(EditorEvent::CursorShapeChanged);
17964        }
17965
17966        let project_settings = ProjectSettings::get_global(cx);
17967        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17968
17969        if self.mode.is_full() {
17970            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17971            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17972            if self.show_inline_diagnostics != show_inline_diagnostics {
17973                self.show_inline_diagnostics = show_inline_diagnostics;
17974                self.refresh_inline_diagnostics(false, window, cx);
17975            }
17976
17977            if self.git_blame_inline_enabled != inline_blame_enabled {
17978                self.toggle_git_blame_inline_internal(false, window, cx);
17979            }
17980        }
17981
17982        cx.notify();
17983    }
17984
17985    pub fn set_searchable(&mut self, searchable: bool) {
17986        self.searchable = searchable;
17987    }
17988
17989    pub fn searchable(&self) -> bool {
17990        self.searchable
17991    }
17992
17993    fn open_proposed_changes_editor(
17994        &mut self,
17995        _: &OpenProposedChangesEditor,
17996        window: &mut Window,
17997        cx: &mut Context<Self>,
17998    ) {
17999        let Some(workspace) = self.workspace() else {
18000            cx.propagate();
18001            return;
18002        };
18003
18004        let selections = self.selections.all::<usize>(cx);
18005        let multi_buffer = self.buffer.read(cx);
18006        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18007        let mut new_selections_by_buffer = HashMap::default();
18008        for selection in selections {
18009            for (buffer, range, _) in
18010                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18011            {
18012                let mut range = range.to_point(buffer);
18013                range.start.column = 0;
18014                range.end.column = buffer.line_len(range.end.row);
18015                new_selections_by_buffer
18016                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18017                    .or_insert(Vec::new())
18018                    .push(range)
18019            }
18020        }
18021
18022        let proposed_changes_buffers = new_selections_by_buffer
18023            .into_iter()
18024            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18025            .collect::<Vec<_>>();
18026        let proposed_changes_editor = cx.new(|cx| {
18027            ProposedChangesEditor::new(
18028                "Proposed changes",
18029                proposed_changes_buffers,
18030                self.project.clone(),
18031                window,
18032                cx,
18033            )
18034        });
18035
18036        window.defer(cx, move |window, cx| {
18037            workspace.update(cx, |workspace, cx| {
18038                workspace.active_pane().update(cx, |pane, cx| {
18039                    pane.add_item(
18040                        Box::new(proposed_changes_editor),
18041                        true,
18042                        true,
18043                        None,
18044                        window,
18045                        cx,
18046                    );
18047                });
18048            });
18049        });
18050    }
18051
18052    pub fn open_excerpts_in_split(
18053        &mut self,
18054        _: &OpenExcerptsSplit,
18055        window: &mut Window,
18056        cx: &mut Context<Self>,
18057    ) {
18058        self.open_excerpts_common(None, true, window, cx)
18059    }
18060
18061    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18062        self.open_excerpts_common(None, false, window, cx)
18063    }
18064
18065    fn open_excerpts_common(
18066        &mut self,
18067        jump_data: Option<JumpData>,
18068        split: bool,
18069        window: &mut Window,
18070        cx: &mut Context<Self>,
18071    ) {
18072        let Some(workspace) = self.workspace() else {
18073            cx.propagate();
18074            return;
18075        };
18076
18077        if self.buffer.read(cx).is_singleton() {
18078            cx.propagate();
18079            return;
18080        }
18081
18082        let mut new_selections_by_buffer = HashMap::default();
18083        match &jump_data {
18084            Some(JumpData::MultiBufferPoint {
18085                excerpt_id,
18086                position,
18087                anchor,
18088                line_offset_from_top,
18089            }) => {
18090                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18091                if let Some(buffer) = multi_buffer_snapshot
18092                    .buffer_id_for_excerpt(*excerpt_id)
18093                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18094                {
18095                    let buffer_snapshot = buffer.read(cx).snapshot();
18096                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18097                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18098                    } else {
18099                        buffer_snapshot.clip_point(*position, Bias::Left)
18100                    };
18101                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18102                    new_selections_by_buffer.insert(
18103                        buffer,
18104                        (
18105                            vec![jump_to_offset..jump_to_offset],
18106                            Some(*line_offset_from_top),
18107                        ),
18108                    );
18109                }
18110            }
18111            Some(JumpData::MultiBufferRow {
18112                row,
18113                line_offset_from_top,
18114            }) => {
18115                let point = MultiBufferPoint::new(row.0, 0);
18116                if let Some((buffer, buffer_point, _)) =
18117                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18118                {
18119                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18120                    new_selections_by_buffer
18121                        .entry(buffer)
18122                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18123                        .0
18124                        .push(buffer_offset..buffer_offset)
18125                }
18126            }
18127            None => {
18128                let selections = self.selections.all::<usize>(cx);
18129                let multi_buffer = self.buffer.read(cx);
18130                for selection in selections {
18131                    for (snapshot, range, _, anchor) in multi_buffer
18132                        .snapshot(cx)
18133                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18134                    {
18135                        if let Some(anchor) = anchor {
18136                            // selection is in a deleted hunk
18137                            let Some(buffer_id) = anchor.buffer_id else {
18138                                continue;
18139                            };
18140                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18141                                continue;
18142                            };
18143                            let offset = text::ToOffset::to_offset(
18144                                &anchor.text_anchor,
18145                                &buffer_handle.read(cx).snapshot(),
18146                            );
18147                            let range = offset..offset;
18148                            new_selections_by_buffer
18149                                .entry(buffer_handle)
18150                                .or_insert((Vec::new(), None))
18151                                .0
18152                                .push(range)
18153                        } else {
18154                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18155                            else {
18156                                continue;
18157                            };
18158                            new_selections_by_buffer
18159                                .entry(buffer_handle)
18160                                .or_insert((Vec::new(), None))
18161                                .0
18162                                .push(range)
18163                        }
18164                    }
18165                }
18166            }
18167        }
18168
18169        new_selections_by_buffer
18170            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18171
18172        if new_selections_by_buffer.is_empty() {
18173            return;
18174        }
18175
18176        // We defer the pane interaction because we ourselves are a workspace item
18177        // and activating a new item causes the pane to call a method on us reentrantly,
18178        // which panics if we're on the stack.
18179        window.defer(cx, move |window, cx| {
18180            workspace.update(cx, |workspace, cx| {
18181                let pane = if split {
18182                    workspace.adjacent_pane(window, cx)
18183                } else {
18184                    workspace.active_pane().clone()
18185                };
18186
18187                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18188                    let editor = buffer
18189                        .read(cx)
18190                        .file()
18191                        .is_none()
18192                        .then(|| {
18193                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18194                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18195                            // Instead, we try to activate the existing editor in the pane first.
18196                            let (editor, pane_item_index) =
18197                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18198                                    let editor = item.downcast::<Editor>()?;
18199                                    let singleton_buffer =
18200                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18201                                    if singleton_buffer == buffer {
18202                                        Some((editor, i))
18203                                    } else {
18204                                        None
18205                                    }
18206                                })?;
18207                            pane.update(cx, |pane, cx| {
18208                                pane.activate_item(pane_item_index, true, true, window, cx)
18209                            });
18210                            Some(editor)
18211                        })
18212                        .flatten()
18213                        .unwrap_or_else(|| {
18214                            workspace.open_project_item::<Self>(
18215                                pane.clone(),
18216                                buffer,
18217                                true,
18218                                true,
18219                                window,
18220                                cx,
18221                            )
18222                        });
18223
18224                    editor.update(cx, |editor, cx| {
18225                        let autoscroll = match scroll_offset {
18226                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18227                            None => Autoscroll::newest(),
18228                        };
18229                        let nav_history = editor.nav_history.take();
18230                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18231                            s.select_ranges(ranges);
18232                        });
18233                        editor.nav_history = nav_history;
18234                    });
18235                }
18236            })
18237        });
18238    }
18239
18240    // For now, don't allow opening excerpts in buffers that aren't backed by
18241    // regular project files.
18242    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18243        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18244    }
18245
18246    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18247        let snapshot = self.buffer.read(cx).read(cx);
18248        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18249        Some(
18250            ranges
18251                .iter()
18252                .map(move |range| {
18253                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18254                })
18255                .collect(),
18256        )
18257    }
18258
18259    fn selection_replacement_ranges(
18260        &self,
18261        range: Range<OffsetUtf16>,
18262        cx: &mut App,
18263    ) -> Vec<Range<OffsetUtf16>> {
18264        let selections = self.selections.all::<OffsetUtf16>(cx);
18265        let newest_selection = selections
18266            .iter()
18267            .max_by_key(|selection| selection.id)
18268            .unwrap();
18269        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18270        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18271        let snapshot = self.buffer.read(cx).read(cx);
18272        selections
18273            .into_iter()
18274            .map(|mut selection| {
18275                selection.start.0 =
18276                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18277                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18278                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18279                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18280            })
18281            .collect()
18282    }
18283
18284    fn report_editor_event(
18285        &self,
18286        event_type: &'static str,
18287        file_extension: Option<String>,
18288        cx: &App,
18289    ) {
18290        if cfg!(any(test, feature = "test-support")) {
18291            return;
18292        }
18293
18294        let Some(project) = &self.project else { return };
18295
18296        // If None, we are in a file without an extension
18297        let file = self
18298            .buffer
18299            .read(cx)
18300            .as_singleton()
18301            .and_then(|b| b.read(cx).file());
18302        let file_extension = file_extension.or(file
18303            .as_ref()
18304            .and_then(|file| Path::new(file.file_name(cx)).extension())
18305            .and_then(|e| e.to_str())
18306            .map(|a| a.to_string()));
18307
18308        let vim_mode = vim_enabled(cx);
18309
18310        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18311        let copilot_enabled = edit_predictions_provider
18312            == language::language_settings::EditPredictionProvider::Copilot;
18313        let copilot_enabled_for_language = self
18314            .buffer
18315            .read(cx)
18316            .language_settings(cx)
18317            .show_edit_predictions;
18318
18319        let project = project.read(cx);
18320        telemetry::event!(
18321            event_type,
18322            file_extension,
18323            vim_mode,
18324            copilot_enabled,
18325            copilot_enabled_for_language,
18326            edit_predictions_provider,
18327            is_via_ssh = project.is_via_ssh(),
18328        );
18329    }
18330
18331    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18332    /// with each line being an array of {text, highlight} objects.
18333    fn copy_highlight_json(
18334        &mut self,
18335        _: &CopyHighlightJson,
18336        window: &mut Window,
18337        cx: &mut Context<Self>,
18338    ) {
18339        #[derive(Serialize)]
18340        struct Chunk<'a> {
18341            text: String,
18342            highlight: Option<&'a str>,
18343        }
18344
18345        let snapshot = self.buffer.read(cx).snapshot(cx);
18346        let range = self
18347            .selected_text_range(false, window, cx)
18348            .and_then(|selection| {
18349                if selection.range.is_empty() {
18350                    None
18351                } else {
18352                    Some(selection.range)
18353                }
18354            })
18355            .unwrap_or_else(|| 0..snapshot.len());
18356
18357        let chunks = snapshot.chunks(range, true);
18358        let mut lines = Vec::new();
18359        let mut line: VecDeque<Chunk> = VecDeque::new();
18360
18361        let Some(style) = self.style.as_ref() else {
18362            return;
18363        };
18364
18365        for chunk in chunks {
18366            let highlight = chunk
18367                .syntax_highlight_id
18368                .and_then(|id| id.name(&style.syntax));
18369            let mut chunk_lines = chunk.text.split('\n').peekable();
18370            while let Some(text) = chunk_lines.next() {
18371                let mut merged_with_last_token = false;
18372                if let Some(last_token) = line.back_mut() {
18373                    if last_token.highlight == highlight {
18374                        last_token.text.push_str(text);
18375                        merged_with_last_token = true;
18376                    }
18377                }
18378
18379                if !merged_with_last_token {
18380                    line.push_back(Chunk {
18381                        text: text.into(),
18382                        highlight,
18383                    });
18384                }
18385
18386                if chunk_lines.peek().is_some() {
18387                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18388                        line.pop_front();
18389                    }
18390                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18391                        line.pop_back();
18392                    }
18393
18394                    lines.push(mem::take(&mut line));
18395                }
18396            }
18397        }
18398
18399        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18400            return;
18401        };
18402        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18403    }
18404
18405    pub fn open_context_menu(
18406        &mut self,
18407        _: &OpenContextMenu,
18408        window: &mut Window,
18409        cx: &mut Context<Self>,
18410    ) {
18411        self.request_autoscroll(Autoscroll::newest(), cx);
18412        let position = self.selections.newest_display(cx).start;
18413        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18414    }
18415
18416    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18417        &self.inlay_hint_cache
18418    }
18419
18420    pub fn replay_insert_event(
18421        &mut self,
18422        text: &str,
18423        relative_utf16_range: Option<Range<isize>>,
18424        window: &mut Window,
18425        cx: &mut Context<Self>,
18426    ) {
18427        if !self.input_enabled {
18428            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18429            return;
18430        }
18431        if let Some(relative_utf16_range) = relative_utf16_range {
18432            let selections = self.selections.all::<OffsetUtf16>(cx);
18433            self.change_selections(None, window, cx, |s| {
18434                let new_ranges = selections.into_iter().map(|range| {
18435                    let start = OffsetUtf16(
18436                        range
18437                            .head()
18438                            .0
18439                            .saturating_add_signed(relative_utf16_range.start),
18440                    );
18441                    let end = OffsetUtf16(
18442                        range
18443                            .head()
18444                            .0
18445                            .saturating_add_signed(relative_utf16_range.end),
18446                    );
18447                    start..end
18448                });
18449                s.select_ranges(new_ranges);
18450            });
18451        }
18452
18453        self.handle_input(text, window, cx);
18454    }
18455
18456    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18457        let Some(provider) = self.semantics_provider.as_ref() else {
18458            return false;
18459        };
18460
18461        let mut supports = false;
18462        self.buffer().update(cx, |this, cx| {
18463            this.for_each_buffer(|buffer| {
18464                supports |= provider.supports_inlay_hints(buffer, cx);
18465            });
18466        });
18467
18468        supports
18469    }
18470
18471    pub fn is_focused(&self, window: &Window) -> bool {
18472        self.focus_handle.is_focused(window)
18473    }
18474
18475    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18476        cx.emit(EditorEvent::Focused);
18477
18478        if let Some(descendant) = self
18479            .last_focused_descendant
18480            .take()
18481            .and_then(|descendant| descendant.upgrade())
18482        {
18483            window.focus(&descendant);
18484        } else {
18485            if let Some(blame) = self.blame.as_ref() {
18486                blame.update(cx, GitBlame::focus)
18487            }
18488
18489            self.blink_manager.update(cx, BlinkManager::enable);
18490            self.show_cursor_names(window, cx);
18491            self.buffer.update(cx, |buffer, cx| {
18492                buffer.finalize_last_transaction(cx);
18493                if self.leader_id.is_none() {
18494                    buffer.set_active_selections(
18495                        &self.selections.disjoint_anchors(),
18496                        self.selections.line_mode,
18497                        self.cursor_shape,
18498                        cx,
18499                    );
18500                }
18501            });
18502        }
18503    }
18504
18505    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18506        cx.emit(EditorEvent::FocusedIn)
18507    }
18508
18509    fn handle_focus_out(
18510        &mut self,
18511        event: FocusOutEvent,
18512        _window: &mut Window,
18513        cx: &mut Context<Self>,
18514    ) {
18515        if event.blurred != self.focus_handle {
18516            self.last_focused_descendant = Some(event.blurred);
18517        }
18518        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18519    }
18520
18521    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18522        self.blink_manager.update(cx, BlinkManager::disable);
18523        self.buffer
18524            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18525
18526        if let Some(blame) = self.blame.as_ref() {
18527            blame.update(cx, GitBlame::blur)
18528        }
18529        if !self.hover_state.focused(window, cx) {
18530            hide_hover(self, cx);
18531        }
18532        if !self
18533            .context_menu
18534            .borrow()
18535            .as_ref()
18536            .is_some_and(|context_menu| context_menu.focused(window, cx))
18537        {
18538            self.hide_context_menu(window, cx);
18539        }
18540        self.discard_inline_completion(false, cx);
18541        cx.emit(EditorEvent::Blurred);
18542        cx.notify();
18543    }
18544
18545    pub fn register_action<A: Action>(
18546        &mut self,
18547        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18548    ) -> Subscription {
18549        let id = self.next_editor_action_id.post_inc();
18550        let listener = Arc::new(listener);
18551        self.editor_actions.borrow_mut().insert(
18552            id,
18553            Box::new(move |window, _| {
18554                let listener = listener.clone();
18555                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18556                    let action = action.downcast_ref().unwrap();
18557                    if phase == DispatchPhase::Bubble {
18558                        listener(action, window, cx)
18559                    }
18560                })
18561            }),
18562        );
18563
18564        let editor_actions = self.editor_actions.clone();
18565        Subscription::new(move || {
18566            editor_actions.borrow_mut().remove(&id);
18567        })
18568    }
18569
18570    pub fn file_header_size(&self) -> u32 {
18571        FILE_HEADER_HEIGHT
18572    }
18573
18574    pub fn restore(
18575        &mut self,
18576        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18577        window: &mut Window,
18578        cx: &mut Context<Self>,
18579    ) {
18580        let workspace = self.workspace();
18581        let project = self.project.as_ref();
18582        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18583            let mut tasks = Vec::new();
18584            for (buffer_id, changes) in revert_changes {
18585                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18586                    buffer.update(cx, |buffer, cx| {
18587                        buffer.edit(
18588                            changes
18589                                .into_iter()
18590                                .map(|(range, text)| (range, text.to_string())),
18591                            None,
18592                            cx,
18593                        );
18594                    });
18595
18596                    if let Some(project) =
18597                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18598                    {
18599                        project.update(cx, |project, cx| {
18600                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18601                        })
18602                    }
18603                }
18604            }
18605            tasks
18606        });
18607        cx.spawn_in(window, async move |_, cx| {
18608            for (buffer, task) in save_tasks {
18609                let result = task.await;
18610                if result.is_err() {
18611                    let Some(path) = buffer
18612                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18613                        .ok()
18614                    else {
18615                        continue;
18616                    };
18617                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18618                        let Some(task) = cx
18619                            .update_window_entity(&workspace, |workspace, window, cx| {
18620                                workspace
18621                                    .open_path_preview(path, None, false, false, false, window, cx)
18622                            })
18623                            .ok()
18624                        else {
18625                            continue;
18626                        };
18627                        task.await.log_err();
18628                    }
18629                }
18630            }
18631        })
18632        .detach();
18633        self.change_selections(None, window, cx, |selections| selections.refresh());
18634    }
18635
18636    pub fn to_pixel_point(
18637        &self,
18638        source: multi_buffer::Anchor,
18639        editor_snapshot: &EditorSnapshot,
18640        window: &mut Window,
18641    ) -> Option<gpui::Point<Pixels>> {
18642        let source_point = source.to_display_point(editor_snapshot);
18643        self.display_to_pixel_point(source_point, editor_snapshot, window)
18644    }
18645
18646    pub fn display_to_pixel_point(
18647        &self,
18648        source: DisplayPoint,
18649        editor_snapshot: &EditorSnapshot,
18650        window: &mut Window,
18651    ) -> Option<gpui::Point<Pixels>> {
18652        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18653        let text_layout_details = self.text_layout_details(window);
18654        let scroll_top = text_layout_details
18655            .scroll_anchor
18656            .scroll_position(editor_snapshot)
18657            .y;
18658
18659        if source.row().as_f32() < scroll_top.floor() {
18660            return None;
18661        }
18662        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18663        let source_y = line_height * (source.row().as_f32() - scroll_top);
18664        Some(gpui::Point::new(source_x, source_y))
18665    }
18666
18667    pub fn has_visible_completions_menu(&self) -> bool {
18668        !self.edit_prediction_preview_is_active()
18669            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18670                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18671            })
18672    }
18673
18674    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18675        self.addons
18676            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18677    }
18678
18679    pub fn unregister_addon<T: Addon>(&mut self) {
18680        self.addons.remove(&std::any::TypeId::of::<T>());
18681    }
18682
18683    pub fn addon<T: Addon>(&self) -> Option<&T> {
18684        let type_id = std::any::TypeId::of::<T>();
18685        self.addons
18686            .get(&type_id)
18687            .and_then(|item| item.to_any().downcast_ref::<T>())
18688    }
18689
18690    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18691        let type_id = std::any::TypeId::of::<T>();
18692        self.addons
18693            .get_mut(&type_id)
18694            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18695    }
18696
18697    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18698        let text_layout_details = self.text_layout_details(window);
18699        let style = &text_layout_details.editor_style;
18700        let font_id = window.text_system().resolve_font(&style.text.font());
18701        let font_size = style.text.font_size.to_pixels(window.rem_size());
18702        let line_height = style.text.line_height_in_pixels(window.rem_size());
18703        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18704
18705        gpui::Size::new(em_width, line_height)
18706    }
18707
18708    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18709        self.load_diff_task.clone()
18710    }
18711
18712    fn read_metadata_from_db(
18713        &mut self,
18714        item_id: u64,
18715        workspace_id: WorkspaceId,
18716        window: &mut Window,
18717        cx: &mut Context<Editor>,
18718    ) {
18719        if self.is_singleton(cx)
18720            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18721        {
18722            let buffer_snapshot = OnceCell::new();
18723
18724            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18725                if !folds.is_empty() {
18726                    let snapshot =
18727                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18728                    self.fold_ranges(
18729                        folds
18730                            .into_iter()
18731                            .map(|(start, end)| {
18732                                snapshot.clip_offset(start, Bias::Left)
18733                                    ..snapshot.clip_offset(end, Bias::Right)
18734                            })
18735                            .collect(),
18736                        false,
18737                        window,
18738                        cx,
18739                    );
18740                }
18741            }
18742
18743            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18744                if !selections.is_empty() {
18745                    let snapshot =
18746                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18747                    self.change_selections(None, window, cx, |s| {
18748                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18749                            snapshot.clip_offset(start, Bias::Left)
18750                                ..snapshot.clip_offset(end, Bias::Right)
18751                        }));
18752                    });
18753                }
18754            };
18755        }
18756
18757        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18758    }
18759}
18760
18761fn vim_enabled(cx: &App) -> bool {
18762    cx.global::<SettingsStore>()
18763        .raw_user_settings()
18764        .get("vim_mode")
18765        == Some(&serde_json::Value::Bool(true))
18766}
18767
18768// Consider user intent and default settings
18769fn choose_completion_range(
18770    completion: &Completion,
18771    intent: CompletionIntent,
18772    buffer: &Entity<Buffer>,
18773    cx: &mut Context<Editor>,
18774) -> Range<usize> {
18775    fn should_replace(
18776        completion: &Completion,
18777        insert_range: &Range<text::Anchor>,
18778        intent: CompletionIntent,
18779        completion_mode_setting: LspInsertMode,
18780        buffer: &Buffer,
18781    ) -> bool {
18782        // specific actions take precedence over settings
18783        match intent {
18784            CompletionIntent::CompleteWithInsert => return false,
18785            CompletionIntent::CompleteWithReplace => return true,
18786            CompletionIntent::Complete | CompletionIntent::Compose => {}
18787        }
18788
18789        match completion_mode_setting {
18790            LspInsertMode::Insert => false,
18791            LspInsertMode::Replace => true,
18792            LspInsertMode::ReplaceSubsequence => {
18793                let mut text_to_replace = buffer.chars_for_range(
18794                    buffer.anchor_before(completion.replace_range.start)
18795                        ..buffer.anchor_after(completion.replace_range.end),
18796                );
18797                let mut completion_text = completion.new_text.chars();
18798
18799                // is `text_to_replace` a subsequence of `completion_text`
18800                text_to_replace
18801                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18802            }
18803            LspInsertMode::ReplaceSuffix => {
18804                let range_after_cursor = insert_range.end..completion.replace_range.end;
18805
18806                let text_after_cursor = buffer
18807                    .text_for_range(
18808                        buffer.anchor_before(range_after_cursor.start)
18809                            ..buffer.anchor_after(range_after_cursor.end),
18810                    )
18811                    .collect::<String>();
18812                completion.new_text.ends_with(&text_after_cursor)
18813            }
18814        }
18815    }
18816
18817    let buffer = buffer.read(cx);
18818
18819    if let CompletionSource::Lsp {
18820        insert_range: Some(insert_range),
18821        ..
18822    } = &completion.source
18823    {
18824        let completion_mode_setting =
18825            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18826                .completions
18827                .lsp_insert_mode;
18828
18829        if !should_replace(
18830            completion,
18831            &insert_range,
18832            intent,
18833            completion_mode_setting,
18834            buffer,
18835        ) {
18836            return insert_range.to_offset(buffer);
18837        }
18838    }
18839
18840    completion.replace_range.to_offset(buffer)
18841}
18842
18843fn insert_extra_newline_brackets(
18844    buffer: &MultiBufferSnapshot,
18845    range: Range<usize>,
18846    language: &language::LanguageScope,
18847) -> bool {
18848    let leading_whitespace_len = buffer
18849        .reversed_chars_at(range.start)
18850        .take_while(|c| c.is_whitespace() && *c != '\n')
18851        .map(|c| c.len_utf8())
18852        .sum::<usize>();
18853    let trailing_whitespace_len = buffer
18854        .chars_at(range.end)
18855        .take_while(|c| c.is_whitespace() && *c != '\n')
18856        .map(|c| c.len_utf8())
18857        .sum::<usize>();
18858    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18859
18860    language.brackets().any(|(pair, enabled)| {
18861        let pair_start = pair.start.trim_end();
18862        let pair_end = pair.end.trim_start();
18863
18864        enabled
18865            && pair.newline
18866            && buffer.contains_str_at(range.end, pair_end)
18867            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18868    })
18869}
18870
18871fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18872    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18873        [(buffer, range, _)] => (*buffer, range.clone()),
18874        _ => return false,
18875    };
18876    let pair = {
18877        let mut result: Option<BracketMatch> = None;
18878
18879        for pair in buffer
18880            .all_bracket_ranges(range.clone())
18881            .filter(move |pair| {
18882                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18883            })
18884        {
18885            let len = pair.close_range.end - pair.open_range.start;
18886
18887            if let Some(existing) = &result {
18888                let existing_len = existing.close_range.end - existing.open_range.start;
18889                if len > existing_len {
18890                    continue;
18891                }
18892            }
18893
18894            result = Some(pair);
18895        }
18896
18897        result
18898    };
18899    let Some(pair) = pair else {
18900        return false;
18901    };
18902    pair.newline_only
18903        && buffer
18904            .chars_for_range(pair.open_range.end..range.start)
18905            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18906            .all(|c| c.is_whitespace() && c != '\n')
18907}
18908
18909fn update_uncommitted_diff_for_buffer(
18910    editor: Entity<Editor>,
18911    project: &Entity<Project>,
18912    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18913    buffer: Entity<MultiBuffer>,
18914    cx: &mut App,
18915) -> Task<()> {
18916    let mut tasks = Vec::new();
18917    project.update(cx, |project, cx| {
18918        for buffer in buffers {
18919            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18920                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18921            }
18922        }
18923    });
18924    cx.spawn(async move |cx| {
18925        let diffs = future::join_all(tasks).await;
18926        if editor
18927            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18928            .unwrap_or(false)
18929        {
18930            return;
18931        }
18932
18933        buffer
18934            .update(cx, |buffer, cx| {
18935                for diff in diffs.into_iter().flatten() {
18936                    buffer.add_diff(diff, cx);
18937                }
18938            })
18939            .ok();
18940    })
18941}
18942
18943fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18944    let tab_size = tab_size.get() as usize;
18945    let mut width = offset;
18946
18947    for ch in text.chars() {
18948        width += if ch == '\t' {
18949            tab_size - (width % tab_size)
18950        } else {
18951            1
18952        };
18953    }
18954
18955    width - offset
18956}
18957
18958#[cfg(test)]
18959mod tests {
18960    use super::*;
18961
18962    #[test]
18963    fn test_string_size_with_expanded_tabs() {
18964        let nz = |val| NonZeroU32::new(val).unwrap();
18965        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18966        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18967        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18968        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18969        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18970        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18971        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18972        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18973    }
18974}
18975
18976/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18977struct WordBreakingTokenizer<'a> {
18978    input: &'a str,
18979}
18980
18981impl<'a> WordBreakingTokenizer<'a> {
18982    fn new(input: &'a str) -> Self {
18983        Self { input }
18984    }
18985}
18986
18987fn is_char_ideographic(ch: char) -> bool {
18988    use unicode_script::Script::*;
18989    use unicode_script::UnicodeScript;
18990    matches!(ch.script(), Han | Tangut | Yi)
18991}
18992
18993fn is_grapheme_ideographic(text: &str) -> bool {
18994    text.chars().any(is_char_ideographic)
18995}
18996
18997fn is_grapheme_whitespace(text: &str) -> bool {
18998    text.chars().any(|x| x.is_whitespace())
18999}
19000
19001fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19002    text.chars().next().map_or(false, |ch| {
19003        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19004    })
19005}
19006
19007#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19008enum WordBreakToken<'a> {
19009    Word { token: &'a str, grapheme_len: usize },
19010    InlineWhitespace { token: &'a str, grapheme_len: usize },
19011    Newline,
19012}
19013
19014impl<'a> Iterator for WordBreakingTokenizer<'a> {
19015    /// Yields a span, the count of graphemes in the token, and whether it was
19016    /// whitespace. Note that it also breaks at word boundaries.
19017    type Item = WordBreakToken<'a>;
19018
19019    fn next(&mut self) -> Option<Self::Item> {
19020        use unicode_segmentation::UnicodeSegmentation;
19021        if self.input.is_empty() {
19022            return None;
19023        }
19024
19025        let mut iter = self.input.graphemes(true).peekable();
19026        let mut offset = 0;
19027        let mut grapheme_len = 0;
19028        if let Some(first_grapheme) = iter.next() {
19029            let is_newline = first_grapheme == "\n";
19030            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19031            offset += first_grapheme.len();
19032            grapheme_len += 1;
19033            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19034                if let Some(grapheme) = iter.peek().copied() {
19035                    if should_stay_with_preceding_ideograph(grapheme) {
19036                        offset += grapheme.len();
19037                        grapheme_len += 1;
19038                    }
19039                }
19040            } else {
19041                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19042                let mut next_word_bound = words.peek().copied();
19043                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19044                    next_word_bound = words.next();
19045                }
19046                while let Some(grapheme) = iter.peek().copied() {
19047                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19048                        break;
19049                    };
19050                    if is_grapheme_whitespace(grapheme) != is_whitespace
19051                        || (grapheme == "\n") != is_newline
19052                    {
19053                        break;
19054                    };
19055                    offset += grapheme.len();
19056                    grapheme_len += 1;
19057                    iter.next();
19058                }
19059            }
19060            let token = &self.input[..offset];
19061            self.input = &self.input[offset..];
19062            if token == "\n" {
19063                Some(WordBreakToken::Newline)
19064            } else if is_whitespace {
19065                Some(WordBreakToken::InlineWhitespace {
19066                    token,
19067                    grapheme_len,
19068                })
19069            } else {
19070                Some(WordBreakToken::Word {
19071                    token,
19072                    grapheme_len,
19073                })
19074            }
19075        } else {
19076            None
19077        }
19078    }
19079}
19080
19081#[test]
19082fn test_word_breaking_tokenizer() {
19083    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19084        ("", &[]),
19085        ("  ", &[whitespace("  ", 2)]),
19086        ("Ʒ", &[word("Ʒ", 1)]),
19087        ("Ǽ", &[word("Ǽ", 1)]),
19088        ("", &[word("", 1)]),
19089        ("⋑⋑", &[word("⋑⋑", 2)]),
19090        (
19091            "原理,进而",
19092            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19093        ),
19094        (
19095            "hello world",
19096            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19097        ),
19098        (
19099            "hello, world",
19100            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19101        ),
19102        (
19103            "  hello world",
19104            &[
19105                whitespace("  ", 2),
19106                word("hello", 5),
19107                whitespace(" ", 1),
19108                word("world", 5),
19109            ],
19110        ),
19111        (
19112            "这是什么 \n 钢笔",
19113            &[
19114                word("", 1),
19115                word("", 1),
19116                word("", 1),
19117                word("", 1),
19118                whitespace(" ", 1),
19119                newline(),
19120                whitespace(" ", 1),
19121                word("", 1),
19122                word("", 1),
19123            ],
19124        ),
19125        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19126    ];
19127
19128    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19129        WordBreakToken::Word {
19130            token,
19131            grapheme_len,
19132        }
19133    }
19134
19135    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19136        WordBreakToken::InlineWhitespace {
19137            token,
19138            grapheme_len,
19139        }
19140    }
19141
19142    fn newline() -> WordBreakToken<'static> {
19143        WordBreakToken::Newline
19144    }
19145
19146    for (input, result) in tests {
19147        assert_eq!(
19148            WordBreakingTokenizer::new(input)
19149                .collect::<Vec<_>>()
19150                .as_slice(),
19151            *result,
19152        );
19153    }
19154}
19155
19156fn wrap_with_prefix(
19157    line_prefix: String,
19158    unwrapped_text: String,
19159    wrap_column: usize,
19160    tab_size: NonZeroU32,
19161    preserve_existing_whitespace: bool,
19162) -> String {
19163    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19164    let mut wrapped_text = String::new();
19165    let mut current_line = line_prefix.clone();
19166
19167    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19168    let mut current_line_len = line_prefix_len;
19169    let mut in_whitespace = false;
19170    for token in tokenizer {
19171        let have_preceding_whitespace = in_whitespace;
19172        match token {
19173            WordBreakToken::Word {
19174                token,
19175                grapheme_len,
19176            } => {
19177                in_whitespace = false;
19178                if current_line_len + grapheme_len > wrap_column
19179                    && current_line_len != line_prefix_len
19180                {
19181                    wrapped_text.push_str(current_line.trim_end());
19182                    wrapped_text.push('\n');
19183                    current_line.truncate(line_prefix.len());
19184                    current_line_len = line_prefix_len;
19185                }
19186                current_line.push_str(token);
19187                current_line_len += grapheme_len;
19188            }
19189            WordBreakToken::InlineWhitespace {
19190                mut token,
19191                mut grapheme_len,
19192            } => {
19193                in_whitespace = true;
19194                if have_preceding_whitespace && !preserve_existing_whitespace {
19195                    continue;
19196                }
19197                if !preserve_existing_whitespace {
19198                    token = " ";
19199                    grapheme_len = 1;
19200                }
19201                if current_line_len + grapheme_len > wrap_column {
19202                    wrapped_text.push_str(current_line.trim_end());
19203                    wrapped_text.push('\n');
19204                    current_line.truncate(line_prefix.len());
19205                    current_line_len = line_prefix_len;
19206                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19207                    current_line.push_str(token);
19208                    current_line_len += grapheme_len;
19209                }
19210            }
19211            WordBreakToken::Newline => {
19212                in_whitespace = true;
19213                if preserve_existing_whitespace {
19214                    wrapped_text.push_str(current_line.trim_end());
19215                    wrapped_text.push('\n');
19216                    current_line.truncate(line_prefix.len());
19217                    current_line_len = line_prefix_len;
19218                } else if have_preceding_whitespace {
19219                    continue;
19220                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19221                {
19222                    wrapped_text.push_str(current_line.trim_end());
19223                    wrapped_text.push('\n');
19224                    current_line.truncate(line_prefix.len());
19225                    current_line_len = line_prefix_len;
19226                } else if current_line_len != line_prefix_len {
19227                    current_line.push(' ');
19228                    current_line_len += 1;
19229                }
19230            }
19231        }
19232    }
19233
19234    if !current_line.is_empty() {
19235        wrapped_text.push_str(&current_line);
19236    }
19237    wrapped_text
19238}
19239
19240#[test]
19241fn test_wrap_with_prefix() {
19242    assert_eq!(
19243        wrap_with_prefix(
19244            "# ".to_string(),
19245            "abcdefg".to_string(),
19246            4,
19247            NonZeroU32::new(4).unwrap(),
19248            false,
19249        ),
19250        "# abcdefg"
19251    );
19252    assert_eq!(
19253        wrap_with_prefix(
19254            "".to_string(),
19255            "\thello world".to_string(),
19256            8,
19257            NonZeroU32::new(4).unwrap(),
19258            false,
19259        ),
19260        "hello\nworld"
19261    );
19262    assert_eq!(
19263        wrap_with_prefix(
19264            "// ".to_string(),
19265            "xx \nyy zz aa bb cc".to_string(),
19266            12,
19267            NonZeroU32::new(4).unwrap(),
19268            false,
19269        ),
19270        "// xx yy zz\n// aa bb cc"
19271    );
19272    assert_eq!(
19273        wrap_with_prefix(
19274            String::new(),
19275            "这是什么 \n 钢笔".to_string(),
19276            3,
19277            NonZeroU32::new(4).unwrap(),
19278            false,
19279        ),
19280        "这是什\n么 钢\n"
19281    );
19282}
19283
19284pub trait CollaborationHub {
19285    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19286    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19287    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19288}
19289
19290impl CollaborationHub for Entity<Project> {
19291    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19292        self.read(cx).collaborators()
19293    }
19294
19295    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19296        self.read(cx).user_store().read(cx).participant_indices()
19297    }
19298
19299    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19300        let this = self.read(cx);
19301        let user_ids = this.collaborators().values().map(|c| c.user_id);
19302        this.user_store().read_with(cx, |user_store, cx| {
19303            user_store.participant_names(user_ids, cx)
19304        })
19305    }
19306}
19307
19308pub trait SemanticsProvider {
19309    fn hover(
19310        &self,
19311        buffer: &Entity<Buffer>,
19312        position: text::Anchor,
19313        cx: &mut App,
19314    ) -> Option<Task<Vec<project::Hover>>>;
19315
19316    fn inline_values(
19317        &self,
19318        buffer_handle: Entity<Buffer>,
19319        range: Range<text::Anchor>,
19320        cx: &mut App,
19321    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19322
19323    fn inlay_hints(
19324        &self,
19325        buffer_handle: Entity<Buffer>,
19326        range: Range<text::Anchor>,
19327        cx: &mut App,
19328    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19329
19330    fn resolve_inlay_hint(
19331        &self,
19332        hint: InlayHint,
19333        buffer_handle: Entity<Buffer>,
19334        server_id: LanguageServerId,
19335        cx: &mut App,
19336    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19337
19338    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19339
19340    fn document_highlights(
19341        &self,
19342        buffer: &Entity<Buffer>,
19343        position: text::Anchor,
19344        cx: &mut App,
19345    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19346
19347    fn definitions(
19348        &self,
19349        buffer: &Entity<Buffer>,
19350        position: text::Anchor,
19351        kind: GotoDefinitionKind,
19352        cx: &mut App,
19353    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19354
19355    fn range_for_rename(
19356        &self,
19357        buffer: &Entity<Buffer>,
19358        position: text::Anchor,
19359        cx: &mut App,
19360    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19361
19362    fn perform_rename(
19363        &self,
19364        buffer: &Entity<Buffer>,
19365        position: text::Anchor,
19366        new_name: String,
19367        cx: &mut App,
19368    ) -> Option<Task<Result<ProjectTransaction>>>;
19369}
19370
19371pub trait CompletionProvider {
19372    fn completions(
19373        &self,
19374        excerpt_id: ExcerptId,
19375        buffer: &Entity<Buffer>,
19376        buffer_position: text::Anchor,
19377        trigger: CompletionContext,
19378        window: &mut Window,
19379        cx: &mut Context<Editor>,
19380    ) -> Task<Result<Option<Vec<Completion>>>>;
19381
19382    fn resolve_completions(
19383        &self,
19384        buffer: Entity<Buffer>,
19385        completion_indices: Vec<usize>,
19386        completions: Rc<RefCell<Box<[Completion]>>>,
19387        cx: &mut Context<Editor>,
19388    ) -> Task<Result<bool>>;
19389
19390    fn apply_additional_edits_for_completion(
19391        &self,
19392        _buffer: Entity<Buffer>,
19393        _completions: Rc<RefCell<Box<[Completion]>>>,
19394        _completion_index: usize,
19395        _push_to_history: bool,
19396        _cx: &mut Context<Editor>,
19397    ) -> Task<Result<Option<language::Transaction>>> {
19398        Task::ready(Ok(None))
19399    }
19400
19401    fn is_completion_trigger(
19402        &self,
19403        buffer: &Entity<Buffer>,
19404        position: language::Anchor,
19405        text: &str,
19406        trigger_in_words: bool,
19407        cx: &mut Context<Editor>,
19408    ) -> bool;
19409
19410    fn sort_completions(&self) -> bool {
19411        true
19412    }
19413
19414    fn filter_completions(&self) -> bool {
19415        true
19416    }
19417}
19418
19419pub trait CodeActionProvider {
19420    fn id(&self) -> Arc<str>;
19421
19422    fn code_actions(
19423        &self,
19424        buffer: &Entity<Buffer>,
19425        range: Range<text::Anchor>,
19426        window: &mut Window,
19427        cx: &mut App,
19428    ) -> Task<Result<Vec<CodeAction>>>;
19429
19430    fn apply_code_action(
19431        &self,
19432        buffer_handle: Entity<Buffer>,
19433        action: CodeAction,
19434        excerpt_id: ExcerptId,
19435        push_to_history: bool,
19436        window: &mut Window,
19437        cx: &mut App,
19438    ) -> Task<Result<ProjectTransaction>>;
19439}
19440
19441impl CodeActionProvider for Entity<Project> {
19442    fn id(&self) -> Arc<str> {
19443        "project".into()
19444    }
19445
19446    fn code_actions(
19447        &self,
19448        buffer: &Entity<Buffer>,
19449        range: Range<text::Anchor>,
19450        _window: &mut Window,
19451        cx: &mut App,
19452    ) -> Task<Result<Vec<CodeAction>>> {
19453        self.update(cx, |project, cx| {
19454            let code_lens = project.code_lens(buffer, range.clone(), cx);
19455            let code_actions = project.code_actions(buffer, range, None, cx);
19456            cx.background_spawn(async move {
19457                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19458                Ok(code_lens
19459                    .context("code lens fetch")?
19460                    .into_iter()
19461                    .chain(code_actions.context("code action fetch")?)
19462                    .collect())
19463            })
19464        })
19465    }
19466
19467    fn apply_code_action(
19468        &self,
19469        buffer_handle: Entity<Buffer>,
19470        action: CodeAction,
19471        _excerpt_id: ExcerptId,
19472        push_to_history: bool,
19473        _window: &mut Window,
19474        cx: &mut App,
19475    ) -> Task<Result<ProjectTransaction>> {
19476        self.update(cx, |project, cx| {
19477            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19478        })
19479    }
19480}
19481
19482fn snippet_completions(
19483    project: &Project,
19484    buffer: &Entity<Buffer>,
19485    buffer_position: text::Anchor,
19486    cx: &mut App,
19487) -> Task<Result<Vec<Completion>>> {
19488    let languages = buffer.read(cx).languages_at(buffer_position);
19489    let snippet_store = project.snippets().read(cx);
19490
19491    let scopes: Vec<_> = languages
19492        .iter()
19493        .filter_map(|language| {
19494            let language_name = language.lsp_id();
19495            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19496
19497            if snippets.is_empty() {
19498                None
19499            } else {
19500                Some((language.default_scope(), snippets))
19501            }
19502        })
19503        .collect();
19504
19505    if scopes.is_empty() {
19506        return Task::ready(Ok(vec![]));
19507    }
19508
19509    let snapshot = buffer.read(cx).text_snapshot();
19510    let chars: String = snapshot
19511        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19512        .collect();
19513    let executor = cx.background_executor().clone();
19514
19515    cx.background_spawn(async move {
19516        let mut all_results: Vec<Completion> = Vec::new();
19517        for (scope, snippets) in scopes.into_iter() {
19518            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19519            let mut last_word = chars
19520                .chars()
19521                .take_while(|c| classifier.is_word(*c))
19522                .collect::<String>();
19523            last_word = last_word.chars().rev().collect();
19524
19525            if last_word.is_empty() {
19526                return Ok(vec![]);
19527            }
19528
19529            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19530            let to_lsp = |point: &text::Anchor| {
19531                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19532                point_to_lsp(end)
19533            };
19534            let lsp_end = to_lsp(&buffer_position);
19535
19536            let candidates = snippets
19537                .iter()
19538                .enumerate()
19539                .flat_map(|(ix, snippet)| {
19540                    snippet
19541                        .prefix
19542                        .iter()
19543                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19544                })
19545                .collect::<Vec<StringMatchCandidate>>();
19546
19547            let mut matches = fuzzy::match_strings(
19548                &candidates,
19549                &last_word,
19550                last_word.chars().any(|c| c.is_uppercase()),
19551                100,
19552                &Default::default(),
19553                executor.clone(),
19554            )
19555            .await;
19556
19557            // Remove all candidates where the query's start does not match the start of any word in the candidate
19558            if let Some(query_start) = last_word.chars().next() {
19559                matches.retain(|string_match| {
19560                    split_words(&string_match.string).any(|word| {
19561                        // Check that the first codepoint of the word as lowercase matches the first
19562                        // codepoint of the query as lowercase
19563                        word.chars()
19564                            .flat_map(|codepoint| codepoint.to_lowercase())
19565                            .zip(query_start.to_lowercase())
19566                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19567                    })
19568                });
19569            }
19570
19571            let matched_strings = matches
19572                .into_iter()
19573                .map(|m| m.string)
19574                .collect::<HashSet<_>>();
19575
19576            let mut result: Vec<Completion> = snippets
19577                .iter()
19578                .filter_map(|snippet| {
19579                    let matching_prefix = snippet
19580                        .prefix
19581                        .iter()
19582                        .find(|prefix| matched_strings.contains(*prefix))?;
19583                    let start = as_offset - last_word.len();
19584                    let start = snapshot.anchor_before(start);
19585                    let range = start..buffer_position;
19586                    let lsp_start = to_lsp(&start);
19587                    let lsp_range = lsp::Range {
19588                        start: lsp_start,
19589                        end: lsp_end,
19590                    };
19591                    Some(Completion {
19592                        replace_range: range,
19593                        new_text: snippet.body.clone(),
19594                        source: CompletionSource::Lsp {
19595                            insert_range: None,
19596                            server_id: LanguageServerId(usize::MAX),
19597                            resolved: true,
19598                            lsp_completion: Box::new(lsp::CompletionItem {
19599                                label: snippet.prefix.first().unwrap().clone(),
19600                                kind: Some(CompletionItemKind::SNIPPET),
19601                                label_details: snippet.description.as_ref().map(|description| {
19602                                    lsp::CompletionItemLabelDetails {
19603                                        detail: Some(description.clone()),
19604                                        description: None,
19605                                    }
19606                                }),
19607                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19608                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19609                                    lsp::InsertReplaceEdit {
19610                                        new_text: snippet.body.clone(),
19611                                        insert: lsp_range,
19612                                        replace: lsp_range,
19613                                    },
19614                                )),
19615                                filter_text: Some(snippet.body.clone()),
19616                                sort_text: Some(char::MAX.to_string()),
19617                                ..lsp::CompletionItem::default()
19618                            }),
19619                            lsp_defaults: None,
19620                        },
19621                        label: CodeLabel {
19622                            text: matching_prefix.clone(),
19623                            runs: Vec::new(),
19624                            filter_range: 0..matching_prefix.len(),
19625                        },
19626                        icon_path: None,
19627                        documentation: snippet.description.clone().map(|description| {
19628                            CompletionDocumentation::SingleLine(description.into())
19629                        }),
19630                        insert_text_mode: None,
19631                        confirm: None,
19632                    })
19633                })
19634                .collect();
19635
19636            all_results.append(&mut result);
19637        }
19638
19639        Ok(all_results)
19640    })
19641}
19642
19643impl CompletionProvider for Entity<Project> {
19644    fn completions(
19645        &self,
19646        _excerpt_id: ExcerptId,
19647        buffer: &Entity<Buffer>,
19648        buffer_position: text::Anchor,
19649        options: CompletionContext,
19650        _window: &mut Window,
19651        cx: &mut Context<Editor>,
19652    ) -> Task<Result<Option<Vec<Completion>>>> {
19653        self.update(cx, |project, cx| {
19654            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19655            let project_completions = project.completions(buffer, buffer_position, options, cx);
19656            cx.background_spawn(async move {
19657                let snippets_completions = snippets.await?;
19658                match project_completions.await? {
19659                    Some(mut completions) => {
19660                        completions.extend(snippets_completions);
19661                        Ok(Some(completions))
19662                    }
19663                    None => {
19664                        if snippets_completions.is_empty() {
19665                            Ok(None)
19666                        } else {
19667                            Ok(Some(snippets_completions))
19668                        }
19669                    }
19670                }
19671            })
19672        })
19673    }
19674
19675    fn resolve_completions(
19676        &self,
19677        buffer: Entity<Buffer>,
19678        completion_indices: Vec<usize>,
19679        completions: Rc<RefCell<Box<[Completion]>>>,
19680        cx: &mut Context<Editor>,
19681    ) -> Task<Result<bool>> {
19682        self.update(cx, |project, cx| {
19683            project.lsp_store().update(cx, |lsp_store, cx| {
19684                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19685            })
19686        })
19687    }
19688
19689    fn apply_additional_edits_for_completion(
19690        &self,
19691        buffer: Entity<Buffer>,
19692        completions: Rc<RefCell<Box<[Completion]>>>,
19693        completion_index: usize,
19694        push_to_history: bool,
19695        cx: &mut Context<Editor>,
19696    ) -> Task<Result<Option<language::Transaction>>> {
19697        self.update(cx, |project, cx| {
19698            project.lsp_store().update(cx, |lsp_store, cx| {
19699                lsp_store.apply_additional_edits_for_completion(
19700                    buffer,
19701                    completions,
19702                    completion_index,
19703                    push_to_history,
19704                    cx,
19705                )
19706            })
19707        })
19708    }
19709
19710    fn is_completion_trigger(
19711        &self,
19712        buffer: &Entity<Buffer>,
19713        position: language::Anchor,
19714        text: &str,
19715        trigger_in_words: bool,
19716        cx: &mut Context<Editor>,
19717    ) -> bool {
19718        let mut chars = text.chars();
19719        let char = if let Some(char) = chars.next() {
19720            char
19721        } else {
19722            return false;
19723        };
19724        if chars.next().is_some() {
19725            return false;
19726        }
19727
19728        let buffer = buffer.read(cx);
19729        let snapshot = buffer.snapshot();
19730        if !snapshot.settings_at(position, cx).show_completions_on_input {
19731            return false;
19732        }
19733        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19734        if trigger_in_words && classifier.is_word(char) {
19735            return true;
19736        }
19737
19738        buffer.completion_triggers().contains(text)
19739    }
19740}
19741
19742impl SemanticsProvider for Entity<Project> {
19743    fn hover(
19744        &self,
19745        buffer: &Entity<Buffer>,
19746        position: text::Anchor,
19747        cx: &mut App,
19748    ) -> Option<Task<Vec<project::Hover>>> {
19749        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19750    }
19751
19752    fn document_highlights(
19753        &self,
19754        buffer: &Entity<Buffer>,
19755        position: text::Anchor,
19756        cx: &mut App,
19757    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19758        Some(self.update(cx, |project, cx| {
19759            project.document_highlights(buffer, position, cx)
19760        }))
19761    }
19762
19763    fn definitions(
19764        &self,
19765        buffer: &Entity<Buffer>,
19766        position: text::Anchor,
19767        kind: GotoDefinitionKind,
19768        cx: &mut App,
19769    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19770        Some(self.update(cx, |project, cx| match kind {
19771            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19772            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19773            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19774            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19775        }))
19776    }
19777
19778    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19779        // TODO: make this work for remote projects
19780        self.update(cx, |project, cx| {
19781            if project
19782                .active_debug_session(cx)
19783                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19784            {
19785                return true;
19786            }
19787
19788            buffer.update(cx, |buffer, cx| {
19789                project.any_language_server_supports_inlay_hints(buffer, cx)
19790            })
19791        })
19792    }
19793
19794    fn inline_values(
19795        &self,
19796        buffer_handle: Entity<Buffer>,
19797        range: Range<text::Anchor>,
19798        cx: &mut App,
19799    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19800        self.update(cx, |project, cx| {
19801            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19802
19803            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19804        })
19805    }
19806
19807    fn inlay_hints(
19808        &self,
19809        buffer_handle: Entity<Buffer>,
19810        range: Range<text::Anchor>,
19811        cx: &mut App,
19812    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19813        Some(self.update(cx, |project, cx| {
19814            project.inlay_hints(buffer_handle, range, cx)
19815        }))
19816    }
19817
19818    fn resolve_inlay_hint(
19819        &self,
19820        hint: InlayHint,
19821        buffer_handle: Entity<Buffer>,
19822        server_id: LanguageServerId,
19823        cx: &mut App,
19824    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19825        Some(self.update(cx, |project, cx| {
19826            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19827        }))
19828    }
19829
19830    fn range_for_rename(
19831        &self,
19832        buffer: &Entity<Buffer>,
19833        position: text::Anchor,
19834        cx: &mut App,
19835    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19836        Some(self.update(cx, |project, cx| {
19837            let buffer = buffer.clone();
19838            let task = project.prepare_rename(buffer.clone(), position, cx);
19839            cx.spawn(async move |_, cx| {
19840                Ok(match task.await? {
19841                    PrepareRenameResponse::Success(range) => Some(range),
19842                    PrepareRenameResponse::InvalidPosition => None,
19843                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19844                        // Fallback on using TreeSitter info to determine identifier range
19845                        buffer.update(cx, |buffer, _| {
19846                            let snapshot = buffer.snapshot();
19847                            let (range, kind) = snapshot.surrounding_word(position);
19848                            if kind != Some(CharKind::Word) {
19849                                return None;
19850                            }
19851                            Some(
19852                                snapshot.anchor_before(range.start)
19853                                    ..snapshot.anchor_after(range.end),
19854                            )
19855                        })?
19856                    }
19857                })
19858            })
19859        }))
19860    }
19861
19862    fn perform_rename(
19863        &self,
19864        buffer: &Entity<Buffer>,
19865        position: text::Anchor,
19866        new_name: String,
19867        cx: &mut App,
19868    ) -> Option<Task<Result<ProjectTransaction>>> {
19869        Some(self.update(cx, |project, cx| {
19870            project.perform_rename(buffer.clone(), position, new_name, cx)
19871        }))
19872    }
19873}
19874
19875fn inlay_hint_settings(
19876    location: Anchor,
19877    snapshot: &MultiBufferSnapshot,
19878    cx: &mut Context<Editor>,
19879) -> InlayHintSettings {
19880    let file = snapshot.file_at(location);
19881    let language = snapshot.language_at(location).map(|l| l.name());
19882    language_settings(language, file, cx).inlay_hints
19883}
19884
19885fn consume_contiguous_rows(
19886    contiguous_row_selections: &mut Vec<Selection<Point>>,
19887    selection: &Selection<Point>,
19888    display_map: &DisplaySnapshot,
19889    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19890) -> (MultiBufferRow, MultiBufferRow) {
19891    contiguous_row_selections.push(selection.clone());
19892    let start_row = MultiBufferRow(selection.start.row);
19893    let mut end_row = ending_row(selection, display_map);
19894
19895    while let Some(next_selection) = selections.peek() {
19896        if next_selection.start.row <= end_row.0 {
19897            end_row = ending_row(next_selection, display_map);
19898            contiguous_row_selections.push(selections.next().unwrap().clone());
19899        } else {
19900            break;
19901        }
19902    }
19903    (start_row, end_row)
19904}
19905
19906fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19907    if next_selection.end.column > 0 || next_selection.is_empty() {
19908        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19909    } else {
19910        MultiBufferRow(next_selection.end.row)
19911    }
19912}
19913
19914impl EditorSnapshot {
19915    pub fn remote_selections_in_range<'a>(
19916        &'a self,
19917        range: &'a Range<Anchor>,
19918        collaboration_hub: &dyn CollaborationHub,
19919        cx: &'a App,
19920    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19921        let participant_names = collaboration_hub.user_names(cx);
19922        let participant_indices = collaboration_hub.user_participant_indices(cx);
19923        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19924        let collaborators_by_replica_id = collaborators_by_peer_id
19925            .iter()
19926            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19927            .collect::<HashMap<_, _>>();
19928        self.buffer_snapshot
19929            .selections_in_range(range, false)
19930            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19931                if replica_id == AGENT_REPLICA_ID {
19932                    Some(RemoteSelection {
19933                        replica_id,
19934                        selection,
19935                        cursor_shape,
19936                        line_mode,
19937                        collaborator_id: CollaboratorId::Agent,
19938                        user_name: Some("Agent".into()),
19939                        color: cx.theme().players().agent(),
19940                    })
19941                } else {
19942                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19943                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19944                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19945                    Some(RemoteSelection {
19946                        replica_id,
19947                        selection,
19948                        cursor_shape,
19949                        line_mode,
19950                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19951                        user_name,
19952                        color: if let Some(index) = participant_index {
19953                            cx.theme().players().color_for_participant(index.0)
19954                        } else {
19955                            cx.theme().players().absent()
19956                        },
19957                    })
19958                }
19959            })
19960    }
19961
19962    pub fn hunks_for_ranges(
19963        &self,
19964        ranges: impl IntoIterator<Item = Range<Point>>,
19965    ) -> Vec<MultiBufferDiffHunk> {
19966        let mut hunks = Vec::new();
19967        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19968            HashMap::default();
19969        for query_range in ranges {
19970            let query_rows =
19971                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19972            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19973                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19974            ) {
19975                // Include deleted hunks that are adjacent to the query range, because
19976                // otherwise they would be missed.
19977                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19978                if hunk.status().is_deleted() {
19979                    intersects_range |= hunk.row_range.start == query_rows.end;
19980                    intersects_range |= hunk.row_range.end == query_rows.start;
19981                }
19982                if intersects_range {
19983                    if !processed_buffer_rows
19984                        .entry(hunk.buffer_id)
19985                        .or_default()
19986                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19987                    {
19988                        continue;
19989                    }
19990                    hunks.push(hunk);
19991                }
19992            }
19993        }
19994
19995        hunks
19996    }
19997
19998    fn display_diff_hunks_for_rows<'a>(
19999        &'a self,
20000        display_rows: Range<DisplayRow>,
20001        folded_buffers: &'a HashSet<BufferId>,
20002    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20003        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20004        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20005
20006        self.buffer_snapshot
20007            .diff_hunks_in_range(buffer_start..buffer_end)
20008            .filter_map(|hunk| {
20009                if folded_buffers.contains(&hunk.buffer_id) {
20010                    return None;
20011                }
20012
20013                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20014                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20015
20016                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20017                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20018
20019                let display_hunk = if hunk_display_start.column() != 0 {
20020                    DisplayDiffHunk::Folded {
20021                        display_row: hunk_display_start.row(),
20022                    }
20023                } else {
20024                    let mut end_row = hunk_display_end.row();
20025                    if hunk_display_end.column() > 0 {
20026                        end_row.0 += 1;
20027                    }
20028                    let is_created_file = hunk.is_created_file();
20029                    DisplayDiffHunk::Unfolded {
20030                        status: hunk.status(),
20031                        diff_base_byte_range: hunk.diff_base_byte_range,
20032                        display_row_range: hunk_display_start.row()..end_row,
20033                        multi_buffer_range: Anchor::range_in_buffer(
20034                            hunk.excerpt_id,
20035                            hunk.buffer_id,
20036                            hunk.buffer_range,
20037                        ),
20038                        is_created_file,
20039                    }
20040                };
20041
20042                Some(display_hunk)
20043            })
20044    }
20045
20046    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20047        self.display_snapshot.buffer_snapshot.language_at(position)
20048    }
20049
20050    pub fn is_focused(&self) -> bool {
20051        self.is_focused
20052    }
20053
20054    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20055        self.placeholder_text.as_ref()
20056    }
20057
20058    pub fn scroll_position(&self) -> gpui::Point<f32> {
20059        self.scroll_anchor.scroll_position(&self.display_snapshot)
20060    }
20061
20062    fn gutter_dimensions(
20063        &self,
20064        font_id: FontId,
20065        font_size: Pixels,
20066        max_line_number_width: Pixels,
20067        cx: &App,
20068    ) -> Option<GutterDimensions> {
20069        if !self.show_gutter {
20070            return None;
20071        }
20072
20073        let descent = cx.text_system().descent(font_id, font_size);
20074        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20075        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20076
20077        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20078            matches!(
20079                ProjectSettings::get_global(cx).git.git_gutter,
20080                Some(GitGutterSetting::TrackedFiles)
20081            )
20082        });
20083        let gutter_settings = EditorSettings::get_global(cx).gutter;
20084        let show_line_numbers = self
20085            .show_line_numbers
20086            .unwrap_or(gutter_settings.line_numbers);
20087        let line_gutter_width = if show_line_numbers {
20088            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20089            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20090            max_line_number_width.max(min_width_for_number_on_gutter)
20091        } else {
20092            0.0.into()
20093        };
20094
20095        let show_code_actions = self
20096            .show_code_actions
20097            .unwrap_or(gutter_settings.code_actions);
20098
20099        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20100        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20101
20102        let git_blame_entries_width =
20103            self.git_blame_gutter_max_author_length
20104                .map(|max_author_length| {
20105                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20106                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20107
20108                    /// The number of characters to dedicate to gaps and margins.
20109                    const SPACING_WIDTH: usize = 4;
20110
20111                    let max_char_count = max_author_length.min(renderer.max_author_length())
20112                        + ::git::SHORT_SHA_LENGTH
20113                        + MAX_RELATIVE_TIMESTAMP.len()
20114                        + SPACING_WIDTH;
20115
20116                    em_advance * max_char_count
20117                });
20118
20119        let is_singleton = self.buffer_snapshot.is_singleton();
20120
20121        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20122        left_padding += if !is_singleton {
20123            em_width * 4.0
20124        } else if show_code_actions || show_runnables || show_breakpoints {
20125            em_width * 3.0
20126        } else if show_git_gutter && show_line_numbers {
20127            em_width * 2.0
20128        } else if show_git_gutter || show_line_numbers {
20129            em_width
20130        } else {
20131            px(0.)
20132        };
20133
20134        let shows_folds = is_singleton && gutter_settings.folds;
20135
20136        let right_padding = if shows_folds && show_line_numbers {
20137            em_width * 4.0
20138        } else if shows_folds || (!is_singleton && show_line_numbers) {
20139            em_width * 3.0
20140        } else if show_line_numbers {
20141            em_width
20142        } else {
20143            px(0.)
20144        };
20145
20146        Some(GutterDimensions {
20147            left_padding,
20148            right_padding,
20149            width: line_gutter_width + left_padding + right_padding,
20150            margin: -descent,
20151            git_blame_entries_width,
20152        })
20153    }
20154
20155    pub fn render_crease_toggle(
20156        &self,
20157        buffer_row: MultiBufferRow,
20158        row_contains_cursor: bool,
20159        editor: Entity<Editor>,
20160        window: &mut Window,
20161        cx: &mut App,
20162    ) -> Option<AnyElement> {
20163        let folded = self.is_line_folded(buffer_row);
20164        let mut is_foldable = false;
20165
20166        if let Some(crease) = self
20167            .crease_snapshot
20168            .query_row(buffer_row, &self.buffer_snapshot)
20169        {
20170            is_foldable = true;
20171            match crease {
20172                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20173                    if let Some(render_toggle) = render_toggle {
20174                        let toggle_callback =
20175                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20176                                if folded {
20177                                    editor.update(cx, |editor, cx| {
20178                                        editor.fold_at(buffer_row, window, cx)
20179                                    });
20180                                } else {
20181                                    editor.update(cx, |editor, cx| {
20182                                        editor.unfold_at(buffer_row, window, cx)
20183                                    });
20184                                }
20185                            });
20186                        return Some((render_toggle)(
20187                            buffer_row,
20188                            folded,
20189                            toggle_callback,
20190                            window,
20191                            cx,
20192                        ));
20193                    }
20194                }
20195            }
20196        }
20197
20198        is_foldable |= self.starts_indent(buffer_row);
20199
20200        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20201            Some(
20202                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20203                    .toggle_state(folded)
20204                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20205                        if folded {
20206                            this.unfold_at(buffer_row, window, cx);
20207                        } else {
20208                            this.fold_at(buffer_row, window, cx);
20209                        }
20210                    }))
20211                    .into_any_element(),
20212            )
20213        } else {
20214            None
20215        }
20216    }
20217
20218    pub fn render_crease_trailer(
20219        &self,
20220        buffer_row: MultiBufferRow,
20221        window: &mut Window,
20222        cx: &mut App,
20223    ) -> Option<AnyElement> {
20224        let folded = self.is_line_folded(buffer_row);
20225        if let Crease::Inline { render_trailer, .. } = self
20226            .crease_snapshot
20227            .query_row(buffer_row, &self.buffer_snapshot)?
20228        {
20229            let render_trailer = render_trailer.as_ref()?;
20230            Some(render_trailer(buffer_row, folded, window, cx))
20231        } else {
20232            None
20233        }
20234    }
20235}
20236
20237impl Deref for EditorSnapshot {
20238    type Target = DisplaySnapshot;
20239
20240    fn deref(&self) -> &Self::Target {
20241        &self.display_snapshot
20242    }
20243}
20244
20245#[derive(Clone, Debug, PartialEq, Eq)]
20246pub enum EditorEvent {
20247    InputIgnored {
20248        text: Arc<str>,
20249    },
20250    InputHandled {
20251        utf16_range_to_replace: Option<Range<isize>>,
20252        text: Arc<str>,
20253    },
20254    ExcerptsAdded {
20255        buffer: Entity<Buffer>,
20256        predecessor: ExcerptId,
20257        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20258    },
20259    ExcerptsRemoved {
20260        ids: Vec<ExcerptId>,
20261        removed_buffer_ids: Vec<BufferId>,
20262    },
20263    BufferFoldToggled {
20264        ids: Vec<ExcerptId>,
20265        folded: bool,
20266    },
20267    ExcerptsEdited {
20268        ids: Vec<ExcerptId>,
20269    },
20270    ExcerptsExpanded {
20271        ids: Vec<ExcerptId>,
20272    },
20273    BufferEdited,
20274    Edited {
20275        transaction_id: clock::Lamport,
20276    },
20277    Reparsed(BufferId),
20278    Focused,
20279    FocusedIn,
20280    Blurred,
20281    DirtyChanged,
20282    Saved,
20283    TitleChanged,
20284    DiffBaseChanged,
20285    SelectionsChanged {
20286        local: bool,
20287    },
20288    ScrollPositionChanged {
20289        local: bool,
20290        autoscroll: bool,
20291    },
20292    Closed,
20293    TransactionUndone {
20294        transaction_id: clock::Lamport,
20295    },
20296    TransactionBegun {
20297        transaction_id: clock::Lamport,
20298    },
20299    Reloaded,
20300    CursorShapeChanged,
20301    PushedToNavHistory {
20302        anchor: Anchor,
20303        is_deactivate: bool,
20304    },
20305}
20306
20307impl EventEmitter<EditorEvent> for Editor {}
20308
20309impl Focusable for Editor {
20310    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20311        self.focus_handle.clone()
20312    }
20313}
20314
20315impl Render for Editor {
20316    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20317        let settings = ThemeSettings::get_global(cx);
20318
20319        let mut text_style = match self.mode {
20320            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20321                color: cx.theme().colors().editor_foreground,
20322                font_family: settings.ui_font.family.clone(),
20323                font_features: settings.ui_font.features.clone(),
20324                font_fallbacks: settings.ui_font.fallbacks.clone(),
20325                font_size: rems(0.875).into(),
20326                font_weight: settings.ui_font.weight,
20327                line_height: relative(settings.buffer_line_height.value()),
20328                ..Default::default()
20329            },
20330            EditorMode::Full { .. } => TextStyle {
20331                color: cx.theme().colors().editor_foreground,
20332                font_family: settings.buffer_font.family.clone(),
20333                font_features: settings.buffer_font.features.clone(),
20334                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20335                font_size: settings.buffer_font_size(cx).into(),
20336                font_weight: settings.buffer_font.weight,
20337                line_height: relative(settings.buffer_line_height.value()),
20338                ..Default::default()
20339            },
20340        };
20341        if let Some(text_style_refinement) = &self.text_style_refinement {
20342            text_style.refine(text_style_refinement)
20343        }
20344
20345        let background = match self.mode {
20346            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20347            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20348            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20349        };
20350
20351        EditorElement::new(
20352            &cx.entity(),
20353            EditorStyle {
20354                background,
20355                local_player: cx.theme().players().local(),
20356                text: text_style,
20357                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20358                syntax: cx.theme().syntax().clone(),
20359                status: cx.theme().status().clone(),
20360                inlay_hints_style: make_inlay_hints_style(cx),
20361                inline_completion_styles: make_suggestion_styles(cx),
20362                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20363            },
20364        )
20365    }
20366}
20367
20368impl EntityInputHandler for Editor {
20369    fn text_for_range(
20370        &mut self,
20371        range_utf16: Range<usize>,
20372        adjusted_range: &mut Option<Range<usize>>,
20373        _: &mut Window,
20374        cx: &mut Context<Self>,
20375    ) -> Option<String> {
20376        let snapshot = self.buffer.read(cx).read(cx);
20377        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20378        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20379        if (start.0..end.0) != range_utf16 {
20380            adjusted_range.replace(start.0..end.0);
20381        }
20382        Some(snapshot.text_for_range(start..end).collect())
20383    }
20384
20385    fn selected_text_range(
20386        &mut self,
20387        ignore_disabled_input: bool,
20388        _: &mut Window,
20389        cx: &mut Context<Self>,
20390    ) -> Option<UTF16Selection> {
20391        // Prevent the IME menu from appearing when holding down an alphabetic key
20392        // while input is disabled.
20393        if !ignore_disabled_input && !self.input_enabled {
20394            return None;
20395        }
20396
20397        let selection = self.selections.newest::<OffsetUtf16>(cx);
20398        let range = selection.range();
20399
20400        Some(UTF16Selection {
20401            range: range.start.0..range.end.0,
20402            reversed: selection.reversed,
20403        })
20404    }
20405
20406    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20407        let snapshot = self.buffer.read(cx).read(cx);
20408        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20409        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20410    }
20411
20412    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20413        self.clear_highlights::<InputComposition>(cx);
20414        self.ime_transaction.take();
20415    }
20416
20417    fn replace_text_in_range(
20418        &mut self,
20419        range_utf16: Option<Range<usize>>,
20420        text: &str,
20421        window: &mut Window,
20422        cx: &mut Context<Self>,
20423    ) {
20424        if !self.input_enabled {
20425            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20426            return;
20427        }
20428
20429        self.transact(window, cx, |this, window, cx| {
20430            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20431                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20432                Some(this.selection_replacement_ranges(range_utf16, cx))
20433            } else {
20434                this.marked_text_ranges(cx)
20435            };
20436
20437            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20438                let newest_selection_id = this.selections.newest_anchor().id;
20439                this.selections
20440                    .all::<OffsetUtf16>(cx)
20441                    .iter()
20442                    .zip(ranges_to_replace.iter())
20443                    .find_map(|(selection, range)| {
20444                        if selection.id == newest_selection_id {
20445                            Some(
20446                                (range.start.0 as isize - selection.head().0 as isize)
20447                                    ..(range.end.0 as isize - selection.head().0 as isize),
20448                            )
20449                        } else {
20450                            None
20451                        }
20452                    })
20453            });
20454
20455            cx.emit(EditorEvent::InputHandled {
20456                utf16_range_to_replace: range_to_replace,
20457                text: text.into(),
20458            });
20459
20460            if let Some(new_selected_ranges) = new_selected_ranges {
20461                this.change_selections(None, window, cx, |selections| {
20462                    selections.select_ranges(new_selected_ranges)
20463                });
20464                this.backspace(&Default::default(), window, cx);
20465            }
20466
20467            this.handle_input(text, window, cx);
20468        });
20469
20470        if let Some(transaction) = self.ime_transaction {
20471            self.buffer.update(cx, |buffer, cx| {
20472                buffer.group_until_transaction(transaction, cx);
20473            });
20474        }
20475
20476        self.unmark_text(window, cx);
20477    }
20478
20479    fn replace_and_mark_text_in_range(
20480        &mut self,
20481        range_utf16: Option<Range<usize>>,
20482        text: &str,
20483        new_selected_range_utf16: Option<Range<usize>>,
20484        window: &mut Window,
20485        cx: &mut Context<Self>,
20486    ) {
20487        if !self.input_enabled {
20488            return;
20489        }
20490
20491        let transaction = self.transact(window, cx, |this, window, cx| {
20492            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20493                let snapshot = this.buffer.read(cx).read(cx);
20494                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20495                    for marked_range in &mut marked_ranges {
20496                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20497                        marked_range.start.0 += relative_range_utf16.start;
20498                        marked_range.start =
20499                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20500                        marked_range.end =
20501                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20502                    }
20503                }
20504                Some(marked_ranges)
20505            } else if let Some(range_utf16) = range_utf16 {
20506                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20507                Some(this.selection_replacement_ranges(range_utf16, cx))
20508            } else {
20509                None
20510            };
20511
20512            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20513                let newest_selection_id = this.selections.newest_anchor().id;
20514                this.selections
20515                    .all::<OffsetUtf16>(cx)
20516                    .iter()
20517                    .zip(ranges_to_replace.iter())
20518                    .find_map(|(selection, range)| {
20519                        if selection.id == newest_selection_id {
20520                            Some(
20521                                (range.start.0 as isize - selection.head().0 as isize)
20522                                    ..(range.end.0 as isize - selection.head().0 as isize),
20523                            )
20524                        } else {
20525                            None
20526                        }
20527                    })
20528            });
20529
20530            cx.emit(EditorEvent::InputHandled {
20531                utf16_range_to_replace: range_to_replace,
20532                text: text.into(),
20533            });
20534
20535            if let Some(ranges) = ranges_to_replace {
20536                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20537            }
20538
20539            let marked_ranges = {
20540                let snapshot = this.buffer.read(cx).read(cx);
20541                this.selections
20542                    .disjoint_anchors()
20543                    .iter()
20544                    .map(|selection| {
20545                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20546                    })
20547                    .collect::<Vec<_>>()
20548            };
20549
20550            if text.is_empty() {
20551                this.unmark_text(window, cx);
20552            } else {
20553                this.highlight_text::<InputComposition>(
20554                    marked_ranges.clone(),
20555                    HighlightStyle {
20556                        underline: Some(UnderlineStyle {
20557                            thickness: px(1.),
20558                            color: None,
20559                            wavy: false,
20560                        }),
20561                        ..Default::default()
20562                    },
20563                    cx,
20564                );
20565            }
20566
20567            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20568            let use_autoclose = this.use_autoclose;
20569            let use_auto_surround = this.use_auto_surround;
20570            this.set_use_autoclose(false);
20571            this.set_use_auto_surround(false);
20572            this.handle_input(text, window, cx);
20573            this.set_use_autoclose(use_autoclose);
20574            this.set_use_auto_surround(use_auto_surround);
20575
20576            if let Some(new_selected_range) = new_selected_range_utf16 {
20577                let snapshot = this.buffer.read(cx).read(cx);
20578                let new_selected_ranges = marked_ranges
20579                    .into_iter()
20580                    .map(|marked_range| {
20581                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20582                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20583                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20584                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20585                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20586                    })
20587                    .collect::<Vec<_>>();
20588
20589                drop(snapshot);
20590                this.change_selections(None, window, cx, |selections| {
20591                    selections.select_ranges(new_selected_ranges)
20592                });
20593            }
20594        });
20595
20596        self.ime_transaction = self.ime_transaction.or(transaction);
20597        if let Some(transaction) = self.ime_transaction {
20598            self.buffer.update(cx, |buffer, cx| {
20599                buffer.group_until_transaction(transaction, cx);
20600            });
20601        }
20602
20603        if self.text_highlights::<InputComposition>(cx).is_none() {
20604            self.ime_transaction.take();
20605        }
20606    }
20607
20608    fn bounds_for_range(
20609        &mut self,
20610        range_utf16: Range<usize>,
20611        element_bounds: gpui::Bounds<Pixels>,
20612        window: &mut Window,
20613        cx: &mut Context<Self>,
20614    ) -> Option<gpui::Bounds<Pixels>> {
20615        let text_layout_details = self.text_layout_details(window);
20616        let gpui::Size {
20617            width: em_width,
20618            height: line_height,
20619        } = self.character_size(window);
20620
20621        let snapshot = self.snapshot(window, cx);
20622        let scroll_position = snapshot.scroll_position();
20623        let scroll_left = scroll_position.x * em_width;
20624
20625        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20626        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20627            + self.gutter_dimensions.width
20628            + self.gutter_dimensions.margin;
20629        let y = line_height * (start.row().as_f32() - scroll_position.y);
20630
20631        Some(Bounds {
20632            origin: element_bounds.origin + point(x, y),
20633            size: size(em_width, line_height),
20634        })
20635    }
20636
20637    fn character_index_for_point(
20638        &mut self,
20639        point: gpui::Point<Pixels>,
20640        _window: &mut Window,
20641        _cx: &mut Context<Self>,
20642    ) -> Option<usize> {
20643        let position_map = self.last_position_map.as_ref()?;
20644        if !position_map.text_hitbox.contains(&point) {
20645            return None;
20646        }
20647        let display_point = position_map.point_for_position(point).previous_valid;
20648        let anchor = position_map
20649            .snapshot
20650            .display_point_to_anchor(display_point, Bias::Left);
20651        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20652        Some(utf16_offset.0)
20653    }
20654}
20655
20656trait SelectionExt {
20657    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20658    fn spanned_rows(
20659        &self,
20660        include_end_if_at_line_start: bool,
20661        map: &DisplaySnapshot,
20662    ) -> Range<MultiBufferRow>;
20663}
20664
20665impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20666    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20667        let start = self
20668            .start
20669            .to_point(&map.buffer_snapshot)
20670            .to_display_point(map);
20671        let end = self
20672            .end
20673            .to_point(&map.buffer_snapshot)
20674            .to_display_point(map);
20675        if self.reversed {
20676            end..start
20677        } else {
20678            start..end
20679        }
20680    }
20681
20682    fn spanned_rows(
20683        &self,
20684        include_end_if_at_line_start: bool,
20685        map: &DisplaySnapshot,
20686    ) -> Range<MultiBufferRow> {
20687        let start = self.start.to_point(&map.buffer_snapshot);
20688        let mut end = self.end.to_point(&map.buffer_snapshot);
20689        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20690            end.row -= 1;
20691        }
20692
20693        let buffer_start = map.prev_line_boundary(start).0;
20694        let buffer_end = map.next_line_boundary(end).0;
20695        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20696    }
20697}
20698
20699impl<T: InvalidationRegion> InvalidationStack<T> {
20700    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20701    where
20702        S: Clone + ToOffset,
20703    {
20704        while let Some(region) = self.last() {
20705            let all_selections_inside_invalidation_ranges =
20706                if selections.len() == region.ranges().len() {
20707                    selections
20708                        .iter()
20709                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20710                        .all(|(selection, invalidation_range)| {
20711                            let head = selection.head().to_offset(buffer);
20712                            invalidation_range.start <= head && invalidation_range.end >= head
20713                        })
20714                } else {
20715                    false
20716                };
20717
20718            if all_selections_inside_invalidation_ranges {
20719                break;
20720            } else {
20721                self.pop();
20722            }
20723        }
20724    }
20725}
20726
20727impl<T> Default for InvalidationStack<T> {
20728    fn default() -> Self {
20729        Self(Default::default())
20730    }
20731}
20732
20733impl<T> Deref for InvalidationStack<T> {
20734    type Target = Vec<T>;
20735
20736    fn deref(&self) -> &Self::Target {
20737        &self.0
20738    }
20739}
20740
20741impl<T> DerefMut for InvalidationStack<T> {
20742    fn deref_mut(&mut self) -> &mut Self::Target {
20743        &mut self.0
20744    }
20745}
20746
20747impl InvalidationRegion for SnippetState {
20748    fn ranges(&self) -> &[Range<Anchor>] {
20749        &self.ranges[self.active_index]
20750    }
20751}
20752
20753fn inline_completion_edit_text(
20754    current_snapshot: &BufferSnapshot,
20755    edits: &[(Range<Anchor>, String)],
20756    edit_preview: &EditPreview,
20757    include_deletions: bool,
20758    cx: &App,
20759) -> HighlightedText {
20760    let edits = edits
20761        .iter()
20762        .map(|(anchor, text)| {
20763            (
20764                anchor.start.text_anchor..anchor.end.text_anchor,
20765                text.clone(),
20766            )
20767        })
20768        .collect::<Vec<_>>();
20769
20770    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20771}
20772
20773pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20774    match severity {
20775        DiagnosticSeverity::ERROR => colors.error,
20776        DiagnosticSeverity::WARNING => colors.warning,
20777        DiagnosticSeverity::INFORMATION => colors.info,
20778        DiagnosticSeverity::HINT => colors.info,
20779        _ => colors.ignored,
20780    }
20781}
20782
20783pub fn styled_runs_for_code_label<'a>(
20784    label: &'a CodeLabel,
20785    syntax_theme: &'a theme::SyntaxTheme,
20786) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20787    let fade_out = HighlightStyle {
20788        fade_out: Some(0.35),
20789        ..Default::default()
20790    };
20791
20792    let mut prev_end = label.filter_range.end;
20793    label
20794        .runs
20795        .iter()
20796        .enumerate()
20797        .flat_map(move |(ix, (range, highlight_id))| {
20798            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20799                style
20800            } else {
20801                return Default::default();
20802            };
20803            let mut muted_style = style;
20804            muted_style.highlight(fade_out);
20805
20806            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20807            if range.start >= label.filter_range.end {
20808                if range.start > prev_end {
20809                    runs.push((prev_end..range.start, fade_out));
20810                }
20811                runs.push((range.clone(), muted_style));
20812            } else if range.end <= label.filter_range.end {
20813                runs.push((range.clone(), style));
20814            } else {
20815                runs.push((range.start..label.filter_range.end, style));
20816                runs.push((label.filter_range.end..range.end, muted_style));
20817            }
20818            prev_end = cmp::max(prev_end, range.end);
20819
20820            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20821                runs.push((prev_end..label.text.len(), fade_out));
20822            }
20823
20824            runs
20825        })
20826}
20827
20828pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20829    let mut prev_index = 0;
20830    let mut prev_codepoint: Option<char> = None;
20831    text.char_indices()
20832        .chain([(text.len(), '\0')])
20833        .filter_map(move |(index, codepoint)| {
20834            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20835            let is_boundary = index == text.len()
20836                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20837                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20838            if is_boundary {
20839                let chunk = &text[prev_index..index];
20840                prev_index = index;
20841                Some(chunk)
20842            } else {
20843                None
20844            }
20845        })
20846}
20847
20848pub trait RangeToAnchorExt: Sized {
20849    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20850
20851    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20852        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20853        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20854    }
20855}
20856
20857impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20858    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20859        let start_offset = self.start.to_offset(snapshot);
20860        let end_offset = self.end.to_offset(snapshot);
20861        if start_offset == end_offset {
20862            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20863        } else {
20864            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20865        }
20866    }
20867}
20868
20869pub trait RowExt {
20870    fn as_f32(&self) -> f32;
20871
20872    fn next_row(&self) -> Self;
20873
20874    fn previous_row(&self) -> Self;
20875
20876    fn minus(&self, other: Self) -> u32;
20877}
20878
20879impl RowExt for DisplayRow {
20880    fn as_f32(&self) -> f32 {
20881        self.0 as f32
20882    }
20883
20884    fn next_row(&self) -> Self {
20885        Self(self.0 + 1)
20886    }
20887
20888    fn previous_row(&self) -> Self {
20889        Self(self.0.saturating_sub(1))
20890    }
20891
20892    fn minus(&self, other: Self) -> u32 {
20893        self.0 - other.0
20894    }
20895}
20896
20897impl RowExt for MultiBufferRow {
20898    fn as_f32(&self) -> f32 {
20899        self.0 as f32
20900    }
20901
20902    fn next_row(&self) -> Self {
20903        Self(self.0 + 1)
20904    }
20905
20906    fn previous_row(&self) -> Self {
20907        Self(self.0.saturating_sub(1))
20908    }
20909
20910    fn minus(&self, other: Self) -> u32 {
20911        self.0 - other.0
20912    }
20913}
20914
20915trait RowRangeExt {
20916    type Row;
20917
20918    fn len(&self) -> usize;
20919
20920    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20921}
20922
20923impl RowRangeExt for Range<MultiBufferRow> {
20924    type Row = MultiBufferRow;
20925
20926    fn len(&self) -> usize {
20927        (self.end.0 - self.start.0) as usize
20928    }
20929
20930    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20931        (self.start.0..self.end.0).map(MultiBufferRow)
20932    }
20933}
20934
20935impl RowRangeExt for Range<DisplayRow> {
20936    type Row = DisplayRow;
20937
20938    fn len(&self) -> usize {
20939        (self.end.0 - self.start.0) as usize
20940    }
20941
20942    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20943        (self.start.0..self.end.0).map(DisplayRow)
20944    }
20945}
20946
20947/// If select range has more than one line, we
20948/// just point the cursor to range.start.
20949fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20950    if range.start.row == range.end.row {
20951        range
20952    } else {
20953        range.start..range.start
20954    }
20955}
20956pub struct KillRing(ClipboardItem);
20957impl Global for KillRing {}
20958
20959const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20960
20961enum BreakpointPromptEditAction {
20962    Log,
20963    Condition,
20964    HitCondition,
20965}
20966
20967struct BreakpointPromptEditor {
20968    pub(crate) prompt: Entity<Editor>,
20969    editor: WeakEntity<Editor>,
20970    breakpoint_anchor: Anchor,
20971    breakpoint: Breakpoint,
20972    edit_action: BreakpointPromptEditAction,
20973    block_ids: HashSet<CustomBlockId>,
20974    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20975    _subscriptions: Vec<Subscription>,
20976}
20977
20978impl BreakpointPromptEditor {
20979    const MAX_LINES: u8 = 4;
20980
20981    fn new(
20982        editor: WeakEntity<Editor>,
20983        breakpoint_anchor: Anchor,
20984        breakpoint: Breakpoint,
20985        edit_action: BreakpointPromptEditAction,
20986        window: &mut Window,
20987        cx: &mut Context<Self>,
20988    ) -> Self {
20989        let base_text = match edit_action {
20990            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20991            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20992            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20993        }
20994        .map(|msg| msg.to_string())
20995        .unwrap_or_default();
20996
20997        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20998        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20999
21000        let prompt = cx.new(|cx| {
21001            let mut prompt = Editor::new(
21002                EditorMode::AutoHeight {
21003                    max_lines: Self::MAX_LINES as usize,
21004                },
21005                buffer,
21006                None,
21007                window,
21008                cx,
21009            );
21010            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21011            prompt.set_show_cursor_when_unfocused(false, cx);
21012            prompt.set_placeholder_text(
21013                match edit_action {
21014                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21015                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21016                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21017                },
21018                cx,
21019            );
21020
21021            prompt
21022        });
21023
21024        Self {
21025            prompt,
21026            editor,
21027            breakpoint_anchor,
21028            breakpoint,
21029            edit_action,
21030            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21031            block_ids: Default::default(),
21032            _subscriptions: vec![],
21033        }
21034    }
21035
21036    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21037        self.block_ids.extend(block_ids)
21038    }
21039
21040    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21041        if let Some(editor) = self.editor.upgrade() {
21042            let message = self
21043                .prompt
21044                .read(cx)
21045                .buffer
21046                .read(cx)
21047                .as_singleton()
21048                .expect("A multi buffer in breakpoint prompt isn't possible")
21049                .read(cx)
21050                .as_rope()
21051                .to_string();
21052
21053            editor.update(cx, |editor, cx| {
21054                editor.edit_breakpoint_at_anchor(
21055                    self.breakpoint_anchor,
21056                    self.breakpoint.clone(),
21057                    match self.edit_action {
21058                        BreakpointPromptEditAction::Log => {
21059                            BreakpointEditAction::EditLogMessage(message.into())
21060                        }
21061                        BreakpointPromptEditAction::Condition => {
21062                            BreakpointEditAction::EditCondition(message.into())
21063                        }
21064                        BreakpointPromptEditAction::HitCondition => {
21065                            BreakpointEditAction::EditHitCondition(message.into())
21066                        }
21067                    },
21068                    cx,
21069                );
21070
21071                editor.remove_blocks(self.block_ids.clone(), None, cx);
21072                cx.focus_self(window);
21073            });
21074        }
21075    }
21076
21077    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21078        self.editor
21079            .update(cx, |editor, cx| {
21080                editor.remove_blocks(self.block_ids.clone(), None, cx);
21081                window.focus(&editor.focus_handle);
21082            })
21083            .log_err();
21084    }
21085
21086    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21087        let settings = ThemeSettings::get_global(cx);
21088        let text_style = TextStyle {
21089            color: if self.prompt.read(cx).read_only(cx) {
21090                cx.theme().colors().text_disabled
21091            } else {
21092                cx.theme().colors().text
21093            },
21094            font_family: settings.buffer_font.family.clone(),
21095            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21096            font_size: settings.buffer_font_size(cx).into(),
21097            font_weight: settings.buffer_font.weight,
21098            line_height: relative(settings.buffer_line_height.value()),
21099            ..Default::default()
21100        };
21101        EditorElement::new(
21102            &self.prompt,
21103            EditorStyle {
21104                background: cx.theme().colors().editor_background,
21105                local_player: cx.theme().players().local(),
21106                text: text_style,
21107                ..Default::default()
21108            },
21109        )
21110    }
21111}
21112
21113impl Render for BreakpointPromptEditor {
21114    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21115        let gutter_dimensions = *self.gutter_dimensions.lock();
21116        h_flex()
21117            .key_context("Editor")
21118            .bg(cx.theme().colors().editor_background)
21119            .border_y_1()
21120            .border_color(cx.theme().status().info_border)
21121            .size_full()
21122            .py(window.line_height() / 2.5)
21123            .on_action(cx.listener(Self::confirm))
21124            .on_action(cx.listener(Self::cancel))
21125            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21126            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21127    }
21128}
21129
21130impl Focusable for BreakpointPromptEditor {
21131    fn focus_handle(&self, cx: &App) -> FocusHandle {
21132        self.prompt.focus_handle(cx)
21133    }
21134}
21135
21136fn all_edits_insertions_or_deletions(
21137    edits: &Vec<(Range<Anchor>, String)>,
21138    snapshot: &MultiBufferSnapshot,
21139) -> bool {
21140    let mut all_insertions = true;
21141    let mut all_deletions = true;
21142
21143    for (range, new_text) in edits.iter() {
21144        let range_is_empty = range.to_offset(&snapshot).is_empty();
21145        let text_is_empty = new_text.is_empty();
21146
21147        if range_is_empty != text_is_empty {
21148            if range_is_empty {
21149                all_deletions = false;
21150            } else {
21151                all_insertions = false;
21152            }
21153        } else {
21154            return false;
21155        }
21156
21157        if !all_insertions && !all_deletions {
21158            return false;
21159        }
21160    }
21161    all_insertions || all_deletions
21162}
21163
21164struct MissingEditPredictionKeybindingTooltip;
21165
21166impl Render for MissingEditPredictionKeybindingTooltip {
21167    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21168        ui::tooltip_container(window, cx, |container, _, cx| {
21169            container
21170                .flex_shrink_0()
21171                .max_w_80()
21172                .min_h(rems_from_px(124.))
21173                .justify_between()
21174                .child(
21175                    v_flex()
21176                        .flex_1()
21177                        .text_ui_sm(cx)
21178                        .child(Label::new("Conflict with Accept Keybinding"))
21179                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21180                )
21181                .child(
21182                    h_flex()
21183                        .pb_1()
21184                        .gap_1()
21185                        .items_end()
21186                        .w_full()
21187                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21188                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21189                        }))
21190                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21191                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21192                        })),
21193                )
21194        })
21195    }
21196}
21197
21198#[derive(Debug, Clone, Copy, PartialEq)]
21199pub struct LineHighlight {
21200    pub background: Background,
21201    pub border: Option<gpui::Hsla>,
21202    pub include_gutter: bool,
21203    pub type_id: Option<TypeId>,
21204}
21205
21206fn render_diff_hunk_controls(
21207    row: u32,
21208    status: &DiffHunkStatus,
21209    hunk_range: Range<Anchor>,
21210    is_created_file: bool,
21211    line_height: Pixels,
21212    editor: &Entity<Editor>,
21213    _window: &mut Window,
21214    cx: &mut App,
21215) -> AnyElement {
21216    h_flex()
21217        .h(line_height)
21218        .mr_1()
21219        .gap_1()
21220        .px_0p5()
21221        .pb_1()
21222        .border_x_1()
21223        .border_b_1()
21224        .border_color(cx.theme().colors().border_variant)
21225        .rounded_b_lg()
21226        .bg(cx.theme().colors().editor_background)
21227        .gap_1()
21228        .occlude()
21229        .shadow_md()
21230        .child(if status.has_secondary_hunk() {
21231            Button::new(("stage", row as u64), "Stage")
21232                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21233                .tooltip({
21234                    let focus_handle = editor.focus_handle(cx);
21235                    move |window, cx| {
21236                        Tooltip::for_action_in(
21237                            "Stage Hunk",
21238                            &::git::ToggleStaged,
21239                            &focus_handle,
21240                            window,
21241                            cx,
21242                        )
21243                    }
21244                })
21245                .on_click({
21246                    let editor = editor.clone();
21247                    move |_event, _window, cx| {
21248                        editor.update(cx, |editor, cx| {
21249                            editor.stage_or_unstage_diff_hunks(
21250                                true,
21251                                vec![hunk_range.start..hunk_range.start],
21252                                cx,
21253                            );
21254                        });
21255                    }
21256                })
21257        } else {
21258            Button::new(("unstage", row as u64), "Unstage")
21259                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21260                .tooltip({
21261                    let focus_handle = editor.focus_handle(cx);
21262                    move |window, cx| {
21263                        Tooltip::for_action_in(
21264                            "Unstage Hunk",
21265                            &::git::ToggleStaged,
21266                            &focus_handle,
21267                            window,
21268                            cx,
21269                        )
21270                    }
21271                })
21272                .on_click({
21273                    let editor = editor.clone();
21274                    move |_event, _window, cx| {
21275                        editor.update(cx, |editor, cx| {
21276                            editor.stage_or_unstage_diff_hunks(
21277                                false,
21278                                vec![hunk_range.start..hunk_range.start],
21279                                cx,
21280                            );
21281                        });
21282                    }
21283                })
21284        })
21285        .child(
21286            Button::new(("restore", row as u64), "Restore")
21287                .tooltip({
21288                    let focus_handle = editor.focus_handle(cx);
21289                    move |window, cx| {
21290                        Tooltip::for_action_in(
21291                            "Restore Hunk",
21292                            &::git::Restore,
21293                            &focus_handle,
21294                            window,
21295                            cx,
21296                        )
21297                    }
21298                })
21299                .on_click({
21300                    let editor = editor.clone();
21301                    move |_event, window, cx| {
21302                        editor.update(cx, |editor, cx| {
21303                            let snapshot = editor.snapshot(window, cx);
21304                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21305                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21306                        });
21307                    }
21308                })
21309                .disabled(is_created_file),
21310        )
21311        .when(
21312            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21313            |el| {
21314                el.child(
21315                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21316                        .shape(IconButtonShape::Square)
21317                        .icon_size(IconSize::Small)
21318                        // .disabled(!has_multiple_hunks)
21319                        .tooltip({
21320                            let focus_handle = editor.focus_handle(cx);
21321                            move |window, cx| {
21322                                Tooltip::for_action_in(
21323                                    "Next Hunk",
21324                                    &GoToHunk,
21325                                    &focus_handle,
21326                                    window,
21327                                    cx,
21328                                )
21329                            }
21330                        })
21331                        .on_click({
21332                            let editor = editor.clone();
21333                            move |_event, window, cx| {
21334                                editor.update(cx, |editor, cx| {
21335                                    let snapshot = editor.snapshot(window, cx);
21336                                    let position =
21337                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21338                                    editor.go_to_hunk_before_or_after_position(
21339                                        &snapshot,
21340                                        position,
21341                                        Direction::Next,
21342                                        window,
21343                                        cx,
21344                                    );
21345                                    editor.expand_selected_diff_hunks(cx);
21346                                });
21347                            }
21348                        }),
21349                )
21350                .child(
21351                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21352                        .shape(IconButtonShape::Square)
21353                        .icon_size(IconSize::Small)
21354                        // .disabled(!has_multiple_hunks)
21355                        .tooltip({
21356                            let focus_handle = editor.focus_handle(cx);
21357                            move |window, cx| {
21358                                Tooltip::for_action_in(
21359                                    "Previous Hunk",
21360                                    &GoToPreviousHunk,
21361                                    &focus_handle,
21362                                    window,
21363                                    cx,
21364                                )
21365                            }
21366                        })
21367                        .on_click({
21368                            let editor = editor.clone();
21369                            move |_event, window, cx| {
21370                                editor.update(cx, |editor, cx| {
21371                                    let snapshot = editor.snapshot(window, cx);
21372                                    let point =
21373                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21374                                    editor.go_to_hunk_before_or_after_position(
21375                                        &snapshot,
21376                                        point,
21377                                        Direction::Prev,
21378                                        window,
21379                                        cx,
21380                                    );
21381                                    editor.expand_selected_diff_hunks(cx);
21382                                });
21383                            }
21384                        }),
21385                )
21386            },
21387        )
21388        .into_any_element()
21389}