editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132};
  133
  134pub use git::blame::BlameRenderer;
  135pub use proposed_changes_editor::{
  136    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  137};
  138use smallvec::smallvec;
  139use std::{cell::OnceCell, iter::Peekable};
  140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  141
  142pub use lsp::CompletionContext;
  143use lsp::{
  144    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  145    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  146};
  147
  148use language::BufferSnapshot;
  149pub use lsp_ext::lsp_tasks;
  150use movement::TextLayoutDetails;
  151pub use multi_buffer::{
  152    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  153    RowInfo, ToOffset, ToPoint,
  154};
  155use multi_buffer::{
  156    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  157    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  158};
  159use parking_lot::Mutex;
  160use project::{
  161    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  162    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  163    TaskSourceKind,
  164    debugger::breakpoint_store::Breakpoint,
  165    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  166    project_settings::{GitGutterSetting, ProjectSettings},
  167};
  168use rand::prelude::*;
  169use rpc::{ErrorExt, proto::*};
  170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  171use selections_collection::{
  172    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  173};
  174use serde::{Deserialize, Serialize};
  175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  176use smallvec::SmallVec;
  177use snippet::Snippet;
  178use std::sync::Arc;
  179use std::{
  180    any::TypeId,
  181    borrow::Cow,
  182    cell::RefCell,
  183    cmp::{self, Ordering, Reverse},
  184    mem,
  185    num::NonZeroU32,
  186    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  187    path::{Path, PathBuf},
  188    rc::Rc,
  189    time::{Duration, Instant},
  190};
  191pub use sum_tree::Bias;
  192use sum_tree::TreeMap;
  193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  194use theme::{
  195    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  196    observe_buffer_font_size_adjustment,
  197};
  198use ui::{
  199    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  200    IconSize, Key, Tooltip, h_flex, prelude::*,
  201};
  202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  203use workspace::{
  204    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  205    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  206    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  207    item::{ItemHandle, PreviewTabsSettings},
  208    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  209    searchable::SearchEvent,
  210};
  211
  212use crate::hover_links::{find_url, find_url_from_range};
  213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  214
  215pub const FILE_HEADER_HEIGHT: u32 = 2;
  216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  219const MAX_LINE_LEN: usize = 1024;
  220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  223#[doc(hidden)]
  224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  226
  227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  230
  231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  234
  235pub type RenderDiffHunkControlsFn = Arc<
  236    dyn Fn(
  237        u32,
  238        &DiffHunkStatus,
  239        Range<Anchor>,
  240        bool,
  241        Pixels,
  242        &Entity<Editor>,
  243        &mut Window,
  244        &mut App,
  245    ) -> AnyElement,
  246>;
  247
  248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  249    alt: true,
  250    shift: true,
  251    control: false,
  252    platform: false,
  253    function: false,
  254};
  255
  256struct InlineValueCache {
  257    enabled: bool,
  258    inlays: Vec<InlayId>,
  259    refresh_task: Task<Option<()>>,
  260}
  261
  262impl InlineValueCache {
  263    fn new(enabled: bool) -> Self {
  264        Self {
  265            enabled,
  266            inlays: Vec::new(),
  267            refresh_task: Task::ready(None),
  268        }
  269    }
  270}
  271
  272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  273pub enum InlayId {
  274    InlineCompletion(usize),
  275    Hint(usize),
  276    DebuggerValue(usize),
  277}
  278
  279impl InlayId {
  280    fn id(&self) -> usize {
  281        match self {
  282            Self::InlineCompletion(id) => *id,
  283            Self::Hint(id) => *id,
  284            Self::DebuggerValue(id) => *id,
  285        }
  286    }
  287}
  288
  289pub enum ActiveDebugLine {}
  290enum DocumentHighlightRead {}
  291enum DocumentHighlightWrite {}
  292enum InputComposition {}
  293enum SelectedTextHighlight {}
  294
  295pub enum ConflictsOuter {}
  296pub enum ConflictsOurs {}
  297pub enum ConflictsTheirs {}
  298pub enum ConflictsOursMarker {}
  299pub enum ConflictsTheirsMarker {}
  300
  301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  302pub enum Navigated {
  303    Yes,
  304    No,
  305}
  306
  307impl Navigated {
  308    pub fn from_bool(yes: bool) -> Navigated {
  309        if yes { Navigated::Yes } else { Navigated::No }
  310    }
  311}
  312
  313#[derive(Debug, Clone, PartialEq, Eq)]
  314enum DisplayDiffHunk {
  315    Folded {
  316        display_row: DisplayRow,
  317    },
  318    Unfolded {
  319        is_created_file: bool,
  320        diff_base_byte_range: Range<usize>,
  321        display_row_range: Range<DisplayRow>,
  322        multi_buffer_range: Range<Anchor>,
  323        status: DiffHunkStatus,
  324    },
  325}
  326
  327pub enum HideMouseCursorOrigin {
  328    TypingAction,
  329    MovementAction,
  330}
  331
  332pub fn init_settings(cx: &mut App) {
  333    EditorSettings::register(cx);
  334}
  335
  336pub fn init(cx: &mut App) {
  337    init_settings(cx);
  338
  339    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  340
  341    workspace::register_project_item::<Editor>(cx);
  342    workspace::FollowableViewRegistry::register::<Editor>(cx);
  343    workspace::register_serializable_item::<Editor>(cx);
  344
  345    cx.observe_new(
  346        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  347            workspace.register_action(Editor::new_file);
  348            workspace.register_action(Editor::new_file_vertical);
  349            workspace.register_action(Editor::new_file_horizontal);
  350            workspace.register_action(Editor::cancel_language_server_work);
  351        },
  352    )
  353    .detach();
  354
  355    cx.on_action(move |_: &workspace::NewFile, cx| {
  356        let app_state = workspace::AppState::global(cx);
  357        if let Some(app_state) = app_state.upgrade() {
  358            workspace::open_new(
  359                Default::default(),
  360                app_state,
  361                cx,
  362                |workspace, window, cx| {
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369    cx.on_action(move |_: &workspace::NewWindow, cx| {
  370        let app_state = workspace::AppState::global(cx);
  371        if let Some(app_state) = app_state.upgrade() {
  372            workspace::open_new(
  373                Default::default(),
  374                app_state,
  375                cx,
  376                |workspace, window, cx| {
  377                    cx.activate(true);
  378                    Editor::new_file(workspace, &Default::default(), window, cx)
  379                },
  380            )
  381            .detach();
  382        }
  383    });
  384}
  385
  386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  387    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  388}
  389
  390pub trait DiagnosticRenderer {
  391    fn render_group(
  392        &self,
  393        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  394        buffer_id: BufferId,
  395        snapshot: EditorSnapshot,
  396        editor: WeakEntity<Editor>,
  397        cx: &mut App,
  398    ) -> Vec<BlockProperties<Anchor>>;
  399
  400    fn render_hover(
  401        &self,
  402        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  403        range: Range<Point>,
  404        buffer_id: BufferId,
  405        cx: &mut App,
  406    ) -> Option<Entity<markdown::Markdown>>;
  407
  408    fn open_link(
  409        &self,
  410        editor: &mut Editor,
  411        link: SharedString,
  412        window: &mut Window,
  413        cx: &mut Context<Editor>,
  414    );
  415}
  416
  417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  418
  419impl GlobalDiagnosticRenderer {
  420    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  421        cx.try_global::<Self>().map(|g| g.0.clone())
  422    }
  423}
  424
  425impl gpui::Global for GlobalDiagnosticRenderer {}
  426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  427    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  428}
  429
  430pub struct SearchWithinRange;
  431
  432trait InvalidationRegion {
  433    fn ranges(&self) -> &[Range<Anchor>];
  434}
  435
  436#[derive(Clone, Debug, PartialEq)]
  437pub enum SelectPhase {
  438    Begin {
  439        position: DisplayPoint,
  440        add: bool,
  441        click_count: usize,
  442    },
  443    BeginColumnar {
  444        position: DisplayPoint,
  445        reset: bool,
  446        goal_column: u32,
  447    },
  448    Extend {
  449        position: DisplayPoint,
  450        click_count: usize,
  451    },
  452    Update {
  453        position: DisplayPoint,
  454        goal_column: u32,
  455        scroll_delta: gpui::Point<f32>,
  456    },
  457    End,
  458}
  459
  460#[derive(Clone, Debug)]
  461pub enum SelectMode {
  462    Character,
  463    Word(Range<Anchor>),
  464    Line(Range<Anchor>),
  465    All,
  466}
  467
  468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  469pub enum EditorMode {
  470    SingleLine {
  471        auto_width: bool,
  472    },
  473    AutoHeight {
  474        max_lines: usize,
  475    },
  476    Full {
  477        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  478        scale_ui_elements_with_buffer_font_size: bool,
  479        /// When set to `true`, the editor will render a background for the active line.
  480        show_active_line_background: bool,
  481        /// When set to `true`, the editor's height will be determined by its content.
  482        sized_by_content: bool,
  483    },
  484}
  485
  486impl EditorMode {
  487    pub fn full() -> Self {
  488        Self::Full {
  489            scale_ui_elements_with_buffer_font_size: true,
  490            show_active_line_background: true,
  491            sized_by_content: false,
  492        }
  493    }
  494
  495    pub fn is_full(&self) -> bool {
  496        matches!(self, Self::Full { .. })
  497    }
  498}
  499
  500#[derive(Copy, Clone, Debug)]
  501pub enum SoftWrap {
  502    /// Prefer not to wrap at all.
  503    ///
  504    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  505    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  506    GitDiff,
  507    /// Prefer a single line generally, unless an overly long line is encountered.
  508    None,
  509    /// Soft wrap lines that exceed the editor width.
  510    EditorWidth,
  511    /// Soft wrap lines at the preferred line length.
  512    Column(u32),
  513    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  514    Bounded(u32),
  515}
  516
  517#[derive(Clone)]
  518pub struct EditorStyle {
  519    pub background: Hsla,
  520    pub horizontal_padding: Pixels,
  521    pub local_player: PlayerColor,
  522    pub text: TextStyle,
  523    pub scrollbar_width: Pixels,
  524    pub syntax: Arc<SyntaxTheme>,
  525    pub status: StatusColors,
  526    pub inlay_hints_style: HighlightStyle,
  527    pub inline_completion_styles: InlineCompletionStyles,
  528    pub unnecessary_code_fade: f32,
  529}
  530
  531impl Default for EditorStyle {
  532    fn default() -> Self {
  533        Self {
  534            background: Hsla::default(),
  535            horizontal_padding: Pixels::default(),
  536            local_player: PlayerColor::default(),
  537            text: TextStyle::default(),
  538            scrollbar_width: Pixels::default(),
  539            syntax: Default::default(),
  540            // HACK: Status colors don't have a real default.
  541            // We should look into removing the status colors from the editor
  542            // style and retrieve them directly from the theme.
  543            status: StatusColors::dark(),
  544            inlay_hints_style: HighlightStyle::default(),
  545            inline_completion_styles: InlineCompletionStyles {
  546                insertion: HighlightStyle::default(),
  547                whitespace: HighlightStyle::default(),
  548            },
  549            unnecessary_code_fade: Default::default(),
  550        }
  551    }
  552}
  553
  554pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  555    let show_background = language_settings::language_settings(None, None, cx)
  556        .inlay_hints
  557        .show_background;
  558
  559    HighlightStyle {
  560        color: Some(cx.theme().status().hint),
  561        background_color: show_background.then(|| cx.theme().status().hint_background),
  562        ..HighlightStyle::default()
  563    }
  564}
  565
  566pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  567    InlineCompletionStyles {
  568        insertion: HighlightStyle {
  569            color: Some(cx.theme().status().predictive),
  570            ..HighlightStyle::default()
  571        },
  572        whitespace: HighlightStyle {
  573            background_color: Some(cx.theme().status().created_background),
  574            ..HighlightStyle::default()
  575        },
  576    }
  577}
  578
  579type CompletionId = usize;
  580
  581pub(crate) enum EditDisplayMode {
  582    TabAccept,
  583    DiffPopover,
  584    Inline,
  585}
  586
  587enum InlineCompletion {
  588    Edit {
  589        edits: Vec<(Range<Anchor>, String)>,
  590        edit_preview: Option<EditPreview>,
  591        display_mode: EditDisplayMode,
  592        snapshot: BufferSnapshot,
  593    },
  594    Move {
  595        target: Anchor,
  596        snapshot: BufferSnapshot,
  597    },
  598}
  599
  600struct InlineCompletionState {
  601    inlay_ids: Vec<InlayId>,
  602    completion: InlineCompletion,
  603    completion_id: Option<SharedString>,
  604    invalidation_range: Range<Anchor>,
  605}
  606
  607enum EditPredictionSettings {
  608    Disabled,
  609    Enabled {
  610        show_in_menu: bool,
  611        preview_requires_modifier: bool,
  612    },
  613}
  614
  615enum InlineCompletionHighlight {}
  616
  617#[derive(Debug, Clone)]
  618struct InlineDiagnostic {
  619    message: SharedString,
  620    group_id: usize,
  621    is_primary: bool,
  622    start: Point,
  623    severity: DiagnosticSeverity,
  624}
  625
  626pub enum MenuInlineCompletionsPolicy {
  627    Never,
  628    ByProvider,
  629}
  630
  631pub enum EditPredictionPreview {
  632    /// Modifier is not pressed
  633    Inactive { released_too_fast: bool },
  634    /// Modifier pressed
  635    Active {
  636        since: Instant,
  637        previous_scroll_position: Option<ScrollAnchor>,
  638    },
  639}
  640
  641impl EditPredictionPreview {
  642    pub fn released_too_fast(&self) -> bool {
  643        match self {
  644            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  645            EditPredictionPreview::Active { .. } => false,
  646        }
  647    }
  648
  649    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  650        if let EditPredictionPreview::Active {
  651            previous_scroll_position,
  652            ..
  653        } = self
  654        {
  655            *previous_scroll_position = scroll_position;
  656        }
  657    }
  658}
  659
  660pub struct ContextMenuOptions {
  661    pub min_entries_visible: usize,
  662    pub max_entries_visible: usize,
  663    pub placement: Option<ContextMenuPlacement>,
  664}
  665
  666#[derive(Debug, Clone, PartialEq, Eq)]
  667pub enum ContextMenuPlacement {
  668    Above,
  669    Below,
  670}
  671
  672#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  673struct EditorActionId(usize);
  674
  675impl EditorActionId {
  676    pub fn post_inc(&mut self) -> Self {
  677        let answer = self.0;
  678
  679        *self = Self(answer + 1);
  680
  681        Self(answer)
  682    }
  683}
  684
  685// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  686// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  687
  688type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  689type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  690
  691#[derive(Default)]
  692struct ScrollbarMarkerState {
  693    scrollbar_size: Size<Pixels>,
  694    dirty: bool,
  695    markers: Arc<[PaintQuad]>,
  696    pending_refresh: Option<Task<Result<()>>>,
  697}
  698
  699impl ScrollbarMarkerState {
  700    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  701        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  702    }
  703}
  704
  705#[derive(Clone, Debug)]
  706struct RunnableTasks {
  707    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  708    offset: multi_buffer::Anchor,
  709    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  710    column: u32,
  711    // Values of all named captures, including those starting with '_'
  712    extra_variables: HashMap<String, String>,
  713    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  714    context_range: Range<BufferOffset>,
  715}
  716
  717impl RunnableTasks {
  718    fn resolve<'a>(
  719        &'a self,
  720        cx: &'a task::TaskContext,
  721    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  722        self.templates.iter().filter_map(|(kind, template)| {
  723            template
  724                .resolve_task(&kind.to_id_base(), cx)
  725                .map(|task| (kind.clone(), task))
  726        })
  727    }
  728}
  729
  730#[derive(Clone)]
  731struct ResolvedTasks {
  732    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  733    position: Anchor,
  734}
  735
  736#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  737struct BufferOffset(usize);
  738
  739// Addons allow storing per-editor state in other crates (e.g. Vim)
  740pub trait Addon: 'static {
  741    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  742
  743    fn render_buffer_header_controls(
  744        &self,
  745        _: &ExcerptInfo,
  746        _: &Window,
  747        _: &App,
  748    ) -> Option<AnyElement> {
  749        None
  750    }
  751
  752    fn to_any(&self) -> &dyn std::any::Any;
  753
  754    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  755        None
  756    }
  757}
  758
  759/// A set of caret positions, registered when the editor was edited.
  760pub struct ChangeList {
  761    changes: Vec<Vec<Anchor>>,
  762    /// Currently "selected" change.
  763    position: Option<usize>,
  764}
  765
  766impl ChangeList {
  767    pub fn new() -> Self {
  768        Self {
  769            changes: Vec::new(),
  770            position: None,
  771        }
  772    }
  773
  774    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  775    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  776    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  777        if self.changes.is_empty() {
  778            return None;
  779        }
  780
  781        let prev = self.position.unwrap_or(self.changes.len());
  782        let next = if direction == Direction::Prev {
  783            prev.saturating_sub(count)
  784        } else {
  785            (prev + count).min(self.changes.len() - 1)
  786        };
  787        self.position = Some(next);
  788        self.changes.get(next).map(|anchors| anchors.as_slice())
  789    }
  790
  791    /// Adds a new change to the list, resetting the change list position.
  792    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  793        self.position.take();
  794        if pop_state {
  795            self.changes.pop();
  796        }
  797        self.changes.push(new_positions.clone());
  798    }
  799
  800    pub fn last(&self) -> Option<&[Anchor]> {
  801        self.changes.last().map(|anchors| anchors.as_slice())
  802    }
  803}
  804
  805#[derive(Clone)]
  806struct InlineBlamePopoverState {
  807    scroll_handle: ScrollHandle,
  808    commit_message: Option<ParsedCommitMessage>,
  809    markdown: Entity<Markdown>,
  810}
  811
  812struct InlineBlamePopover {
  813    position: gpui::Point<Pixels>,
  814    show_task: Option<Task<()>>,
  815    hide_task: Option<Task<()>>,
  816    popover_bounds: Option<Bounds<Pixels>>,
  817    popover_state: InlineBlamePopoverState,
  818}
  819
  820/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  821/// a breakpoint on them.
  822#[derive(Clone, Copy, Debug)]
  823struct PhantomBreakpointIndicator {
  824    display_row: DisplayRow,
  825    /// There's a small debounce between hovering over the line and showing the indicator.
  826    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  827    is_active: bool,
  828    collides_with_existing_breakpoint: bool,
  829}
  830/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  831///
  832/// See the [module level documentation](self) for more information.
  833pub struct Editor {
  834    focus_handle: FocusHandle,
  835    last_focused_descendant: Option<WeakFocusHandle>,
  836    /// The text buffer being edited
  837    buffer: Entity<MultiBuffer>,
  838    /// Map of how text in the buffer should be displayed.
  839    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  840    pub display_map: Entity<DisplayMap>,
  841    pub selections: SelectionsCollection,
  842    pub scroll_manager: ScrollManager,
  843    /// When inline assist editors are linked, they all render cursors because
  844    /// typing enters text into each of them, even the ones that aren't focused.
  845    pub(crate) show_cursor_when_unfocused: bool,
  846    columnar_selection_tail: Option<Anchor>,
  847    add_selections_state: Option<AddSelectionsState>,
  848    select_next_state: Option<SelectNextState>,
  849    select_prev_state: Option<SelectNextState>,
  850    selection_history: SelectionHistory,
  851    autoclose_regions: Vec<AutocloseRegion>,
  852    snippet_stack: InvalidationStack<SnippetState>,
  853    select_syntax_node_history: SelectSyntaxNodeHistory,
  854    ime_transaction: Option<TransactionId>,
  855    active_diagnostics: ActiveDiagnostic,
  856    show_inline_diagnostics: bool,
  857    inline_diagnostics_update: Task<()>,
  858    inline_diagnostics_enabled: bool,
  859    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  860    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  861    hard_wrap: Option<usize>,
  862
  863    // TODO: make this a access method
  864    pub project: Option<Entity<Project>>,
  865    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  866    completion_provider: Option<Box<dyn CompletionProvider>>,
  867    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  868    blink_manager: Entity<BlinkManager>,
  869    show_cursor_names: bool,
  870    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  871    pub show_local_selections: bool,
  872    mode: EditorMode,
  873    show_breadcrumbs: bool,
  874    show_gutter: bool,
  875    show_scrollbars: bool,
  876    disable_expand_excerpt_buttons: bool,
  877    show_line_numbers: Option<bool>,
  878    use_relative_line_numbers: Option<bool>,
  879    show_git_diff_gutter: Option<bool>,
  880    show_code_actions: Option<bool>,
  881    show_runnables: Option<bool>,
  882    show_breakpoints: Option<bool>,
  883    show_wrap_guides: Option<bool>,
  884    show_indent_guides: Option<bool>,
  885    placeholder_text: Option<Arc<str>>,
  886    highlight_order: usize,
  887    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  888    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  889    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  890    scrollbar_marker_state: ScrollbarMarkerState,
  891    active_indent_guides_state: ActiveIndentGuidesState,
  892    nav_history: Option<ItemNavHistory>,
  893    context_menu: RefCell<Option<CodeContextMenu>>,
  894    context_menu_options: Option<ContextMenuOptions>,
  895    mouse_context_menu: Option<MouseContextMenu>,
  896    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  897    inline_blame_popover: Option<InlineBlamePopover>,
  898    signature_help_state: SignatureHelpState,
  899    auto_signature_help: Option<bool>,
  900    find_all_references_task_sources: Vec<Anchor>,
  901    next_completion_id: CompletionId,
  902    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  903    code_actions_task: Option<Task<Result<()>>>,
  904    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  905    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  906    document_highlights_task: Option<Task<()>>,
  907    linked_editing_range_task: Option<Task<Option<()>>>,
  908    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  909    pending_rename: Option<RenameState>,
  910    searchable: bool,
  911    cursor_shape: CursorShape,
  912    current_line_highlight: Option<CurrentLineHighlight>,
  913    collapse_matches: bool,
  914    autoindent_mode: Option<AutoindentMode>,
  915    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  916    input_enabled: bool,
  917    use_modal_editing: bool,
  918    read_only: bool,
  919    leader_id: Option<CollaboratorId>,
  920    remote_id: Option<ViewId>,
  921    pub hover_state: HoverState,
  922    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  923    gutter_hovered: bool,
  924    hovered_link_state: Option<HoveredLinkState>,
  925    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  926    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  927    active_inline_completion: Option<InlineCompletionState>,
  928    /// Used to prevent flickering as the user types while the menu is open
  929    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  930    edit_prediction_settings: EditPredictionSettings,
  931    inline_completions_hidden_for_vim_mode: bool,
  932    show_inline_completions_override: Option<bool>,
  933    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  934    edit_prediction_preview: EditPredictionPreview,
  935    edit_prediction_indent_conflict: bool,
  936    edit_prediction_requires_modifier_in_indent_conflict: bool,
  937    inlay_hint_cache: InlayHintCache,
  938    next_inlay_id: usize,
  939    _subscriptions: Vec<Subscription>,
  940    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  941    gutter_dimensions: GutterDimensions,
  942    style: Option<EditorStyle>,
  943    text_style_refinement: Option<TextStyleRefinement>,
  944    next_editor_action_id: EditorActionId,
  945    editor_actions:
  946        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  947    use_autoclose: bool,
  948    use_auto_surround: bool,
  949    auto_replace_emoji_shortcode: bool,
  950    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  951    show_git_blame_gutter: bool,
  952    show_git_blame_inline: bool,
  953    show_git_blame_inline_delay_task: Option<Task<()>>,
  954    git_blame_inline_enabled: bool,
  955    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  956    serialize_dirty_buffers: bool,
  957    show_selection_menu: Option<bool>,
  958    blame: Option<Entity<GitBlame>>,
  959    blame_subscription: Option<Subscription>,
  960    custom_context_menu: Option<
  961        Box<
  962            dyn 'static
  963                + Fn(
  964                    &mut Self,
  965                    DisplayPoint,
  966                    &mut Window,
  967                    &mut Context<Self>,
  968                ) -> Option<Entity<ui::ContextMenu>>,
  969        >,
  970    >,
  971    last_bounds: Option<Bounds<Pixels>>,
  972    last_position_map: Option<Rc<PositionMap>>,
  973    expect_bounds_change: Option<Bounds<Pixels>>,
  974    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  975    tasks_update_task: Option<Task<()>>,
  976    breakpoint_store: Option<Entity<BreakpointStore>>,
  977    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
  978    in_project_search: bool,
  979    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  980    breadcrumb_header: Option<String>,
  981    focused_block: Option<FocusedBlock>,
  982    next_scroll_position: NextScrollCursorCenterTopBottom,
  983    addons: HashMap<TypeId, Box<dyn Addon>>,
  984    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  985    load_diff_task: Option<Shared<Task<()>>>,
  986    /// Whether we are temporarily displaying a diff other than git's
  987    temporary_diff_override: bool,
  988    selection_mark_mode: bool,
  989    toggle_fold_multiple_buffers: Task<()>,
  990    _scroll_cursor_center_top_bottom_task: Task<()>,
  991    serialize_selections: Task<()>,
  992    serialize_folds: Task<()>,
  993    mouse_cursor_hidden: bool,
  994    hide_mouse_mode: HideMouseMode,
  995    pub change_list: ChangeList,
  996    inline_value_cache: InlineValueCache,
  997}
  998
  999#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
 1000enum NextScrollCursorCenterTopBottom {
 1001    #[default]
 1002    Center,
 1003    Top,
 1004    Bottom,
 1005}
 1006
 1007impl NextScrollCursorCenterTopBottom {
 1008    fn next(&self) -> Self {
 1009        match self {
 1010            Self::Center => Self::Top,
 1011            Self::Top => Self::Bottom,
 1012            Self::Bottom => Self::Center,
 1013        }
 1014    }
 1015}
 1016
 1017#[derive(Clone)]
 1018pub struct EditorSnapshot {
 1019    pub mode: EditorMode,
 1020    show_gutter: bool,
 1021    show_line_numbers: Option<bool>,
 1022    show_git_diff_gutter: Option<bool>,
 1023    show_code_actions: Option<bool>,
 1024    show_runnables: Option<bool>,
 1025    show_breakpoints: Option<bool>,
 1026    git_blame_gutter_max_author_length: Option<usize>,
 1027    pub display_snapshot: DisplaySnapshot,
 1028    pub placeholder_text: Option<Arc<str>>,
 1029    is_focused: bool,
 1030    scroll_anchor: ScrollAnchor,
 1031    ongoing_scroll: OngoingScroll,
 1032    current_line_highlight: CurrentLineHighlight,
 1033    gutter_hovered: bool,
 1034}
 1035
 1036#[derive(Default, Debug, Clone, Copy)]
 1037pub struct GutterDimensions {
 1038    pub left_padding: Pixels,
 1039    pub right_padding: Pixels,
 1040    pub width: Pixels,
 1041    pub margin: Pixels,
 1042    pub git_blame_entries_width: Option<Pixels>,
 1043}
 1044
 1045impl GutterDimensions {
 1046    /// The full width of the space taken up by the gutter.
 1047    pub fn full_width(&self) -> Pixels {
 1048        self.margin + self.width
 1049    }
 1050
 1051    /// The width of the space reserved for the fold indicators,
 1052    /// use alongside 'justify_end' and `gutter_width` to
 1053    /// right align content with the line numbers
 1054    pub fn fold_area_width(&self) -> Pixels {
 1055        self.margin + self.right_padding
 1056    }
 1057}
 1058
 1059#[derive(Debug)]
 1060pub struct RemoteSelection {
 1061    pub replica_id: ReplicaId,
 1062    pub selection: Selection<Anchor>,
 1063    pub cursor_shape: CursorShape,
 1064    pub collaborator_id: CollaboratorId,
 1065    pub line_mode: bool,
 1066    pub user_name: Option<SharedString>,
 1067    pub color: PlayerColor,
 1068}
 1069
 1070#[derive(Clone, Debug)]
 1071struct SelectionHistoryEntry {
 1072    selections: Arc<[Selection<Anchor>]>,
 1073    select_next_state: Option<SelectNextState>,
 1074    select_prev_state: Option<SelectNextState>,
 1075    add_selections_state: Option<AddSelectionsState>,
 1076}
 1077
 1078enum SelectionHistoryMode {
 1079    Normal,
 1080    Undoing,
 1081    Redoing,
 1082}
 1083
 1084#[derive(Clone, PartialEq, Eq, Hash)]
 1085struct HoveredCursor {
 1086    replica_id: u16,
 1087    selection_id: usize,
 1088}
 1089
 1090impl Default for SelectionHistoryMode {
 1091    fn default() -> Self {
 1092        Self::Normal
 1093    }
 1094}
 1095
 1096#[derive(Default)]
 1097struct SelectionHistory {
 1098    #[allow(clippy::type_complexity)]
 1099    selections_by_transaction:
 1100        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1101    mode: SelectionHistoryMode,
 1102    undo_stack: VecDeque<SelectionHistoryEntry>,
 1103    redo_stack: VecDeque<SelectionHistoryEntry>,
 1104}
 1105
 1106impl SelectionHistory {
 1107    fn insert_transaction(
 1108        &mut self,
 1109        transaction_id: TransactionId,
 1110        selections: Arc<[Selection<Anchor>]>,
 1111    ) {
 1112        self.selections_by_transaction
 1113            .insert(transaction_id, (selections, None));
 1114    }
 1115
 1116    #[allow(clippy::type_complexity)]
 1117    fn transaction(
 1118        &self,
 1119        transaction_id: TransactionId,
 1120    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1121        self.selections_by_transaction.get(&transaction_id)
 1122    }
 1123
 1124    #[allow(clippy::type_complexity)]
 1125    fn transaction_mut(
 1126        &mut self,
 1127        transaction_id: TransactionId,
 1128    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1129        self.selections_by_transaction.get_mut(&transaction_id)
 1130    }
 1131
 1132    fn push(&mut self, entry: SelectionHistoryEntry) {
 1133        if !entry.selections.is_empty() {
 1134            match self.mode {
 1135                SelectionHistoryMode::Normal => {
 1136                    self.push_undo(entry);
 1137                    self.redo_stack.clear();
 1138                }
 1139                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1140                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1141            }
 1142        }
 1143    }
 1144
 1145    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1146        if self
 1147            .undo_stack
 1148            .back()
 1149            .map_or(true, |e| e.selections != entry.selections)
 1150        {
 1151            self.undo_stack.push_back(entry);
 1152            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1153                self.undo_stack.pop_front();
 1154            }
 1155        }
 1156    }
 1157
 1158    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1159        if self
 1160            .redo_stack
 1161            .back()
 1162            .map_or(true, |e| e.selections != entry.selections)
 1163        {
 1164            self.redo_stack.push_back(entry);
 1165            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1166                self.redo_stack.pop_front();
 1167            }
 1168        }
 1169    }
 1170}
 1171
 1172#[derive(Clone, Copy)]
 1173pub struct RowHighlightOptions {
 1174    pub autoscroll: bool,
 1175    pub include_gutter: bool,
 1176}
 1177
 1178impl Default for RowHighlightOptions {
 1179    fn default() -> Self {
 1180        Self {
 1181            autoscroll: Default::default(),
 1182            include_gutter: true,
 1183        }
 1184    }
 1185}
 1186
 1187struct RowHighlight {
 1188    index: usize,
 1189    range: Range<Anchor>,
 1190    color: Hsla,
 1191    options: RowHighlightOptions,
 1192    type_id: TypeId,
 1193}
 1194
 1195#[derive(Clone, Debug)]
 1196struct AddSelectionsState {
 1197    above: bool,
 1198    stack: Vec<usize>,
 1199}
 1200
 1201#[derive(Clone)]
 1202struct SelectNextState {
 1203    query: AhoCorasick,
 1204    wordwise: bool,
 1205    done: bool,
 1206}
 1207
 1208impl std::fmt::Debug for SelectNextState {
 1209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1210        f.debug_struct(std::any::type_name::<Self>())
 1211            .field("wordwise", &self.wordwise)
 1212            .field("done", &self.done)
 1213            .finish()
 1214    }
 1215}
 1216
 1217#[derive(Debug)]
 1218struct AutocloseRegion {
 1219    selection_id: usize,
 1220    range: Range<Anchor>,
 1221    pair: BracketPair,
 1222}
 1223
 1224#[derive(Debug)]
 1225struct SnippetState {
 1226    ranges: Vec<Vec<Range<Anchor>>>,
 1227    active_index: usize,
 1228    choices: Vec<Option<Vec<String>>>,
 1229}
 1230
 1231#[doc(hidden)]
 1232pub struct RenameState {
 1233    pub range: Range<Anchor>,
 1234    pub old_name: Arc<str>,
 1235    pub editor: Entity<Editor>,
 1236    block_id: CustomBlockId,
 1237}
 1238
 1239struct InvalidationStack<T>(Vec<T>);
 1240
 1241struct RegisteredInlineCompletionProvider {
 1242    provider: Arc<dyn InlineCompletionProviderHandle>,
 1243    _subscription: Subscription,
 1244}
 1245
 1246#[derive(Debug, PartialEq, Eq)]
 1247pub struct ActiveDiagnosticGroup {
 1248    pub active_range: Range<Anchor>,
 1249    pub active_message: String,
 1250    pub group_id: usize,
 1251    pub blocks: HashSet<CustomBlockId>,
 1252}
 1253
 1254#[derive(Debug, PartialEq, Eq)]
 1255#[allow(clippy::large_enum_variant)]
 1256pub(crate) enum ActiveDiagnostic {
 1257    None,
 1258    All,
 1259    Group(ActiveDiagnosticGroup),
 1260}
 1261
 1262#[derive(Serialize, Deserialize, Clone, Debug)]
 1263pub struct ClipboardSelection {
 1264    /// The number of bytes in this selection.
 1265    pub len: usize,
 1266    /// Whether this was a full-line selection.
 1267    pub is_entire_line: bool,
 1268    /// The indentation of the first line when this content was originally copied.
 1269    pub first_line_indent: u32,
 1270}
 1271
 1272// selections, scroll behavior, was newest selection reversed
 1273type SelectSyntaxNodeHistoryState = (
 1274    Box<[Selection<usize>]>,
 1275    SelectSyntaxNodeScrollBehavior,
 1276    bool,
 1277);
 1278
 1279#[derive(Default)]
 1280struct SelectSyntaxNodeHistory {
 1281    stack: Vec<SelectSyntaxNodeHistoryState>,
 1282    // disable temporarily to allow changing selections without losing the stack
 1283    pub disable_clearing: bool,
 1284}
 1285
 1286impl SelectSyntaxNodeHistory {
 1287    pub fn try_clear(&mut self) {
 1288        if !self.disable_clearing {
 1289            self.stack.clear();
 1290        }
 1291    }
 1292
 1293    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1294        self.stack.push(selection);
 1295    }
 1296
 1297    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1298        self.stack.pop()
 1299    }
 1300}
 1301
 1302enum SelectSyntaxNodeScrollBehavior {
 1303    CursorTop,
 1304    FitSelection,
 1305    CursorBottom,
 1306}
 1307
 1308#[derive(Debug)]
 1309pub(crate) struct NavigationData {
 1310    cursor_anchor: Anchor,
 1311    cursor_position: Point,
 1312    scroll_anchor: ScrollAnchor,
 1313    scroll_top_row: u32,
 1314}
 1315
 1316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1317pub enum GotoDefinitionKind {
 1318    Symbol,
 1319    Declaration,
 1320    Type,
 1321    Implementation,
 1322}
 1323
 1324#[derive(Debug, Clone)]
 1325enum InlayHintRefreshReason {
 1326    ModifiersChanged(bool),
 1327    Toggle(bool),
 1328    SettingsChange(InlayHintSettings),
 1329    NewLinesShown,
 1330    BufferEdited(HashSet<Arc<Language>>),
 1331    RefreshRequested,
 1332    ExcerptsRemoved(Vec<ExcerptId>),
 1333}
 1334
 1335impl InlayHintRefreshReason {
 1336    fn description(&self) -> &'static str {
 1337        match self {
 1338            Self::ModifiersChanged(_) => "modifiers changed",
 1339            Self::Toggle(_) => "toggle",
 1340            Self::SettingsChange(_) => "settings change",
 1341            Self::NewLinesShown => "new lines shown",
 1342            Self::BufferEdited(_) => "buffer edited",
 1343            Self::RefreshRequested => "refresh requested",
 1344            Self::ExcerptsRemoved(_) => "excerpts removed",
 1345        }
 1346    }
 1347}
 1348
 1349pub enum FormatTarget {
 1350    Buffers,
 1351    Ranges(Vec<Range<MultiBufferPoint>>),
 1352}
 1353
 1354pub(crate) struct FocusedBlock {
 1355    id: BlockId,
 1356    focus_handle: WeakFocusHandle,
 1357}
 1358
 1359#[derive(Clone)]
 1360enum JumpData {
 1361    MultiBufferRow {
 1362        row: MultiBufferRow,
 1363        line_offset_from_top: u32,
 1364    },
 1365    MultiBufferPoint {
 1366        excerpt_id: ExcerptId,
 1367        position: Point,
 1368        anchor: text::Anchor,
 1369        line_offset_from_top: u32,
 1370    },
 1371}
 1372
 1373pub enum MultibufferSelectionMode {
 1374    First,
 1375    All,
 1376}
 1377
 1378#[derive(Clone, Copy, Debug, Default)]
 1379pub struct RewrapOptions {
 1380    pub override_language_settings: bool,
 1381    pub preserve_existing_whitespace: bool,
 1382}
 1383
 1384impl Editor {
 1385    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1386        let buffer = cx.new(|cx| Buffer::local("", cx));
 1387        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1388        Self::new(
 1389            EditorMode::SingleLine { auto_width: false },
 1390            buffer,
 1391            None,
 1392            window,
 1393            cx,
 1394        )
 1395    }
 1396
 1397    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1398        let buffer = cx.new(|cx| Buffer::local("", cx));
 1399        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1400        Self::new(EditorMode::full(), buffer, None, window, cx)
 1401    }
 1402
 1403    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1404        let buffer = cx.new(|cx| Buffer::local("", cx));
 1405        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1406        Self::new(
 1407            EditorMode::SingleLine { auto_width: true },
 1408            buffer,
 1409            None,
 1410            window,
 1411            cx,
 1412        )
 1413    }
 1414
 1415    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1416        let buffer = cx.new(|cx| Buffer::local("", cx));
 1417        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1418        Self::new(
 1419            EditorMode::AutoHeight { max_lines },
 1420            buffer,
 1421            None,
 1422            window,
 1423            cx,
 1424        )
 1425    }
 1426
 1427    pub fn for_buffer(
 1428        buffer: Entity<Buffer>,
 1429        project: Option<Entity<Project>>,
 1430        window: &mut Window,
 1431        cx: &mut Context<Self>,
 1432    ) -> Self {
 1433        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1434        Self::new(EditorMode::full(), buffer, project, window, cx)
 1435    }
 1436
 1437    pub fn for_multibuffer(
 1438        buffer: Entity<MultiBuffer>,
 1439        project: Option<Entity<Project>>,
 1440        window: &mut Window,
 1441        cx: &mut Context<Self>,
 1442    ) -> Self {
 1443        Self::new(EditorMode::full(), buffer, project, window, cx)
 1444    }
 1445
 1446    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1447        let mut clone = Self::new(
 1448            self.mode,
 1449            self.buffer.clone(),
 1450            self.project.clone(),
 1451            window,
 1452            cx,
 1453        );
 1454        self.display_map.update(cx, |display_map, cx| {
 1455            let snapshot = display_map.snapshot(cx);
 1456            clone.display_map.update(cx, |display_map, cx| {
 1457                display_map.set_state(&snapshot, cx);
 1458            });
 1459        });
 1460        clone.folds_did_change(cx);
 1461        clone.selections.clone_state(&self.selections);
 1462        clone.scroll_manager.clone_state(&self.scroll_manager);
 1463        clone.searchable = self.searchable;
 1464        clone.read_only = self.read_only;
 1465        clone
 1466    }
 1467
 1468    pub fn new(
 1469        mode: EditorMode,
 1470        buffer: Entity<MultiBuffer>,
 1471        project: Option<Entity<Project>>,
 1472        window: &mut Window,
 1473        cx: &mut Context<Self>,
 1474    ) -> Self {
 1475        let style = window.text_style();
 1476        let font_size = style.font_size.to_pixels(window.rem_size());
 1477        let editor = cx.entity().downgrade();
 1478        let fold_placeholder = FoldPlaceholder {
 1479            constrain_width: true,
 1480            render: Arc::new(move |fold_id, fold_range, cx| {
 1481                let editor = editor.clone();
 1482                div()
 1483                    .id(fold_id)
 1484                    .bg(cx.theme().colors().ghost_element_background)
 1485                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1486                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1487                    .rounded_xs()
 1488                    .size_full()
 1489                    .cursor_pointer()
 1490                    .child("")
 1491                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1492                    .on_click(move |_, _window, cx| {
 1493                        editor
 1494                            .update(cx, |editor, cx| {
 1495                                editor.unfold_ranges(
 1496                                    &[fold_range.start..fold_range.end],
 1497                                    true,
 1498                                    false,
 1499                                    cx,
 1500                                );
 1501                                cx.stop_propagation();
 1502                            })
 1503                            .ok();
 1504                    })
 1505                    .into_any()
 1506            }),
 1507            merge_adjacent: true,
 1508            ..Default::default()
 1509        };
 1510        let display_map = cx.new(|cx| {
 1511            DisplayMap::new(
 1512                buffer.clone(),
 1513                style.font(),
 1514                font_size,
 1515                None,
 1516                FILE_HEADER_HEIGHT,
 1517                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1518                fold_placeholder,
 1519                cx,
 1520            )
 1521        });
 1522
 1523        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1524
 1525        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1526
 1527        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1528            .then(|| language_settings::SoftWrap::None);
 1529
 1530        let mut project_subscriptions = Vec::new();
 1531        if mode.is_full() {
 1532            if let Some(project) = project.as_ref() {
 1533                project_subscriptions.push(cx.subscribe_in(
 1534                    project,
 1535                    window,
 1536                    |editor, _, event, window, cx| match event {
 1537                        project::Event::RefreshCodeLens => {
 1538                            // we always query lens with actions, without storing them, always refreshing them
 1539                        }
 1540                        project::Event::RefreshInlayHints => {
 1541                            editor
 1542                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1543                        }
 1544                        project::Event::SnippetEdit(id, snippet_edits) => {
 1545                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1546                                let focus_handle = editor.focus_handle(cx);
 1547                                if focus_handle.is_focused(window) {
 1548                                    let snapshot = buffer.read(cx).snapshot();
 1549                                    for (range, snippet) in snippet_edits {
 1550                                        let editor_range =
 1551                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1552                                        editor
 1553                                            .insert_snippet(
 1554                                                &[editor_range],
 1555                                                snippet.clone(),
 1556                                                window,
 1557                                                cx,
 1558                                            )
 1559                                            .ok();
 1560                                    }
 1561                                }
 1562                            }
 1563                        }
 1564                        _ => {}
 1565                    },
 1566                ));
 1567                if let Some(task_inventory) = project
 1568                    .read(cx)
 1569                    .task_store()
 1570                    .read(cx)
 1571                    .task_inventory()
 1572                    .cloned()
 1573                {
 1574                    project_subscriptions.push(cx.observe_in(
 1575                        &task_inventory,
 1576                        window,
 1577                        |editor, _, window, cx| {
 1578                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1579                        },
 1580                    ));
 1581                };
 1582
 1583                project_subscriptions.push(cx.subscribe_in(
 1584                    &project.read(cx).breakpoint_store(),
 1585                    window,
 1586                    |editor, _, event, window, cx| match event {
 1587                        BreakpointStoreEvent::ClearDebugLines => {
 1588                            editor.clear_row_highlights::<ActiveDebugLine>();
 1589                            editor.refresh_inline_values(cx);
 1590                        }
 1591                        BreakpointStoreEvent::SetDebugLine => {
 1592                            if editor.go_to_active_debug_line(window, cx) {
 1593                                cx.stop_propagation();
 1594                            }
 1595
 1596                            editor.refresh_inline_values(cx);
 1597                        }
 1598                        _ => {}
 1599                    },
 1600                ));
 1601            }
 1602        }
 1603
 1604        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1605
 1606        let inlay_hint_settings =
 1607            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1608        let focus_handle = cx.focus_handle();
 1609        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1610            .detach();
 1611        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1612            .detach();
 1613        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1614            .detach();
 1615        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1616            .detach();
 1617
 1618        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1619            Some(false)
 1620        } else {
 1621            None
 1622        };
 1623
 1624        let breakpoint_store = match (mode, project.as_ref()) {
 1625            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1626            _ => None,
 1627        };
 1628
 1629        let mut code_action_providers = Vec::new();
 1630        let mut load_uncommitted_diff = None;
 1631        if let Some(project) = project.clone() {
 1632            load_uncommitted_diff = Some(
 1633                update_uncommitted_diff_for_buffer(
 1634                    cx.entity(),
 1635                    &project,
 1636                    buffer.read(cx).all_buffers(),
 1637                    buffer.clone(),
 1638                    cx,
 1639                )
 1640                .shared(),
 1641            );
 1642            code_action_providers.push(Rc::new(project) as Rc<_>);
 1643        }
 1644
 1645        let mut this = Self {
 1646            focus_handle,
 1647            show_cursor_when_unfocused: false,
 1648            last_focused_descendant: None,
 1649            buffer: buffer.clone(),
 1650            display_map: display_map.clone(),
 1651            selections,
 1652            scroll_manager: ScrollManager::new(cx),
 1653            columnar_selection_tail: None,
 1654            add_selections_state: None,
 1655            select_next_state: None,
 1656            select_prev_state: None,
 1657            selection_history: Default::default(),
 1658            autoclose_regions: Default::default(),
 1659            snippet_stack: Default::default(),
 1660            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1661            ime_transaction: Default::default(),
 1662            active_diagnostics: ActiveDiagnostic::None,
 1663            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1664            inline_diagnostics_update: Task::ready(()),
 1665            inline_diagnostics: Vec::new(),
 1666            soft_wrap_mode_override,
 1667            hard_wrap: None,
 1668            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1669            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1670            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1671            project,
 1672            blink_manager: blink_manager.clone(),
 1673            show_local_selections: true,
 1674            show_scrollbars: true,
 1675            mode,
 1676            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1677            show_gutter: mode.is_full(),
 1678            show_line_numbers: None,
 1679            use_relative_line_numbers: None,
 1680            disable_expand_excerpt_buttons: false,
 1681            show_git_diff_gutter: None,
 1682            show_code_actions: None,
 1683            show_runnables: None,
 1684            show_breakpoints: None,
 1685            show_wrap_guides: None,
 1686            show_indent_guides,
 1687            placeholder_text: None,
 1688            highlight_order: 0,
 1689            highlighted_rows: HashMap::default(),
 1690            background_highlights: Default::default(),
 1691            gutter_highlights: TreeMap::default(),
 1692            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1693            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1694            nav_history: None,
 1695            context_menu: RefCell::new(None),
 1696            context_menu_options: None,
 1697            mouse_context_menu: None,
 1698            completion_tasks: Default::default(),
 1699            inline_blame_popover: Default::default(),
 1700            signature_help_state: SignatureHelpState::default(),
 1701            auto_signature_help: None,
 1702            find_all_references_task_sources: Vec::new(),
 1703            next_completion_id: 0,
 1704            next_inlay_id: 0,
 1705            code_action_providers,
 1706            available_code_actions: Default::default(),
 1707            code_actions_task: Default::default(),
 1708            quick_selection_highlight_task: Default::default(),
 1709            debounced_selection_highlight_task: Default::default(),
 1710            document_highlights_task: Default::default(),
 1711            linked_editing_range_task: Default::default(),
 1712            pending_rename: Default::default(),
 1713            searchable: true,
 1714            cursor_shape: EditorSettings::get_global(cx)
 1715                .cursor_shape
 1716                .unwrap_or_default(),
 1717            current_line_highlight: None,
 1718            autoindent_mode: Some(AutoindentMode::EachLine),
 1719            collapse_matches: false,
 1720            workspace: None,
 1721            input_enabled: true,
 1722            use_modal_editing: mode.is_full(),
 1723            read_only: false,
 1724            use_autoclose: true,
 1725            use_auto_surround: true,
 1726            auto_replace_emoji_shortcode: false,
 1727            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1728            leader_id: None,
 1729            remote_id: None,
 1730            hover_state: Default::default(),
 1731            pending_mouse_down: None,
 1732            hovered_link_state: Default::default(),
 1733            edit_prediction_provider: None,
 1734            active_inline_completion: None,
 1735            stale_inline_completion_in_menu: None,
 1736            edit_prediction_preview: EditPredictionPreview::Inactive {
 1737                released_too_fast: false,
 1738            },
 1739            inline_diagnostics_enabled: mode.is_full(),
 1740            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1741            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1742
 1743            gutter_hovered: false,
 1744            pixel_position_of_newest_cursor: None,
 1745            last_bounds: None,
 1746            last_position_map: None,
 1747            expect_bounds_change: None,
 1748            gutter_dimensions: GutterDimensions::default(),
 1749            style: None,
 1750            show_cursor_names: false,
 1751            hovered_cursors: Default::default(),
 1752            next_editor_action_id: EditorActionId::default(),
 1753            editor_actions: Rc::default(),
 1754            inline_completions_hidden_for_vim_mode: false,
 1755            show_inline_completions_override: None,
 1756            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1757            edit_prediction_settings: EditPredictionSettings::Disabled,
 1758            edit_prediction_indent_conflict: false,
 1759            edit_prediction_requires_modifier_in_indent_conflict: true,
 1760            custom_context_menu: None,
 1761            show_git_blame_gutter: false,
 1762            show_git_blame_inline: false,
 1763            show_selection_menu: None,
 1764            show_git_blame_inline_delay_task: None,
 1765            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1766            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1767            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1768                .session
 1769                .restore_unsaved_buffers,
 1770            blame: None,
 1771            blame_subscription: None,
 1772            tasks: Default::default(),
 1773
 1774            breakpoint_store,
 1775            gutter_breakpoint_indicator: (None, None),
 1776            _subscriptions: vec![
 1777                cx.observe(&buffer, Self::on_buffer_changed),
 1778                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1779                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1780                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1781                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1782                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1783                cx.observe_window_activation(window, |editor, window, cx| {
 1784                    let active = window.is_window_active();
 1785                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1786                        if active {
 1787                            blink_manager.enable(cx);
 1788                        } else {
 1789                            blink_manager.disable(cx);
 1790                        }
 1791                    });
 1792                }),
 1793            ],
 1794            tasks_update_task: None,
 1795            linked_edit_ranges: Default::default(),
 1796            in_project_search: false,
 1797            previous_search_ranges: None,
 1798            breadcrumb_header: None,
 1799            focused_block: None,
 1800            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1801            addons: HashMap::default(),
 1802            registered_buffers: HashMap::default(),
 1803            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1804            selection_mark_mode: false,
 1805            toggle_fold_multiple_buffers: Task::ready(()),
 1806            serialize_selections: Task::ready(()),
 1807            serialize_folds: Task::ready(()),
 1808            text_style_refinement: None,
 1809            load_diff_task: load_uncommitted_diff,
 1810            temporary_diff_override: false,
 1811            mouse_cursor_hidden: false,
 1812            hide_mouse_mode: EditorSettings::get_global(cx)
 1813                .hide_mouse
 1814                .unwrap_or_default(),
 1815            change_list: ChangeList::new(),
 1816        };
 1817        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1818            this._subscriptions
 1819                .push(cx.observe(breakpoints, |_, _, cx| {
 1820                    cx.notify();
 1821                }));
 1822        }
 1823        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1824        this._subscriptions.extend(project_subscriptions);
 1825
 1826        this._subscriptions.push(cx.subscribe_in(
 1827            &cx.entity(),
 1828            window,
 1829            |editor, _, e: &EditorEvent, window, cx| match e {
 1830                EditorEvent::ScrollPositionChanged { local, .. } => {
 1831                    if *local {
 1832                        let new_anchor = editor.scroll_manager.anchor();
 1833                        let snapshot = editor.snapshot(window, cx);
 1834                        editor.update_restoration_data(cx, move |data| {
 1835                            data.scroll_position = (
 1836                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1837                                new_anchor.offset,
 1838                            );
 1839                        });
 1840                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1841                        editor.inline_blame_popover.take();
 1842                    }
 1843                }
 1844                EditorEvent::Edited { .. } => {
 1845                    if !vim_enabled(cx) {
 1846                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1847                        let pop_state = editor
 1848                            .change_list
 1849                            .last()
 1850                            .map(|previous| {
 1851                                previous.len() == selections.len()
 1852                                    && previous.iter().enumerate().all(|(ix, p)| {
 1853                                        p.to_display_point(&map).row()
 1854                                            == selections[ix].head().row()
 1855                                    })
 1856                            })
 1857                            .unwrap_or(false);
 1858                        let new_positions = selections
 1859                            .into_iter()
 1860                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1861                            .collect();
 1862                        editor
 1863                            .change_list
 1864                            .push_to_change_list(pop_state, new_positions);
 1865                    }
 1866                }
 1867                _ => (),
 1868            },
 1869        ));
 1870
 1871        if let Some(dap_store) = this
 1872            .project
 1873            .as_ref()
 1874            .map(|project| project.read(cx).dap_store())
 1875        {
 1876            let weak_editor = cx.weak_entity();
 1877
 1878            this._subscriptions
 1879                .push(
 1880                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1881                        let session_entity = cx.entity();
 1882                        weak_editor
 1883                            .update(cx, |editor, cx| {
 1884                                editor._subscriptions.push(
 1885                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1886                                );
 1887                            })
 1888                            .ok();
 1889                    }),
 1890                );
 1891
 1892            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1893                this._subscriptions
 1894                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1895            }
 1896        }
 1897
 1898        this.end_selection(window, cx);
 1899        this.scroll_manager.show_scrollbars(window, cx);
 1900        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1901
 1902        if mode.is_full() {
 1903            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1904            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1905
 1906            if this.git_blame_inline_enabled {
 1907                this.git_blame_inline_enabled = true;
 1908                this.start_git_blame_inline(false, window, cx);
 1909            }
 1910
 1911            this.go_to_active_debug_line(window, cx);
 1912
 1913            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1914                if let Some(project) = this.project.as_ref() {
 1915                    let handle = project.update(cx, |project, cx| {
 1916                        project.register_buffer_with_language_servers(&buffer, cx)
 1917                    });
 1918                    this.registered_buffers
 1919                        .insert(buffer.read(cx).remote_id(), handle);
 1920                }
 1921            }
 1922        }
 1923
 1924        this.report_editor_event("Editor Opened", None, cx);
 1925        this
 1926    }
 1927
 1928    pub fn deploy_mouse_context_menu(
 1929        &mut self,
 1930        position: gpui::Point<Pixels>,
 1931        context_menu: Entity<ContextMenu>,
 1932        window: &mut Window,
 1933        cx: &mut Context<Self>,
 1934    ) {
 1935        self.mouse_context_menu = Some(MouseContextMenu::new(
 1936            self,
 1937            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1938            context_menu,
 1939            window,
 1940            cx,
 1941        ));
 1942    }
 1943
 1944    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1945        self.mouse_context_menu
 1946            .as_ref()
 1947            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1948    }
 1949
 1950    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1951        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1952    }
 1953
 1954    fn key_context_internal(
 1955        &self,
 1956        has_active_edit_prediction: bool,
 1957        window: &Window,
 1958        cx: &App,
 1959    ) -> KeyContext {
 1960        let mut key_context = KeyContext::new_with_defaults();
 1961        key_context.add("Editor");
 1962        let mode = match self.mode {
 1963            EditorMode::SingleLine { .. } => "single_line",
 1964            EditorMode::AutoHeight { .. } => "auto_height",
 1965            EditorMode::Full { .. } => "full",
 1966        };
 1967
 1968        if EditorSettings::jupyter_enabled(cx) {
 1969            key_context.add("jupyter");
 1970        }
 1971
 1972        key_context.set("mode", mode);
 1973        if self.pending_rename.is_some() {
 1974            key_context.add("renaming");
 1975        }
 1976
 1977        match self.context_menu.borrow().as_ref() {
 1978            Some(CodeContextMenu::Completions(_)) => {
 1979                key_context.add("menu");
 1980                key_context.add("showing_completions");
 1981            }
 1982            Some(CodeContextMenu::CodeActions(_)) => {
 1983                key_context.add("menu");
 1984                key_context.add("showing_code_actions")
 1985            }
 1986            None => {}
 1987        }
 1988
 1989        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1990        if !self.focus_handle(cx).contains_focused(window, cx)
 1991            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1992        {
 1993            for addon in self.addons.values() {
 1994                addon.extend_key_context(&mut key_context, cx)
 1995            }
 1996        }
 1997
 1998        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1999            if let Some(extension) = singleton_buffer
 2000                .read(cx)
 2001                .file()
 2002                .and_then(|file| file.path().extension()?.to_str())
 2003            {
 2004                key_context.set("extension", extension.to_string());
 2005            }
 2006        } else {
 2007            key_context.add("multibuffer");
 2008        }
 2009
 2010        if has_active_edit_prediction {
 2011            if self.edit_prediction_in_conflict() {
 2012                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2013            } else {
 2014                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2015                key_context.add("copilot_suggestion");
 2016            }
 2017        }
 2018
 2019        if self.selection_mark_mode {
 2020            key_context.add("selection_mode");
 2021        }
 2022
 2023        key_context
 2024    }
 2025
 2026    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2027        self.mouse_cursor_hidden = match origin {
 2028            HideMouseCursorOrigin::TypingAction => {
 2029                matches!(
 2030                    self.hide_mouse_mode,
 2031                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2032                )
 2033            }
 2034            HideMouseCursorOrigin::MovementAction => {
 2035                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2036            }
 2037        };
 2038    }
 2039
 2040    pub fn edit_prediction_in_conflict(&self) -> bool {
 2041        if !self.show_edit_predictions_in_menu() {
 2042            return false;
 2043        }
 2044
 2045        let showing_completions = self
 2046            .context_menu
 2047            .borrow()
 2048            .as_ref()
 2049            .map_or(false, |context| {
 2050                matches!(context, CodeContextMenu::Completions(_))
 2051            });
 2052
 2053        showing_completions
 2054            || self.edit_prediction_requires_modifier()
 2055            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2056            // bindings to insert tab characters.
 2057            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2058    }
 2059
 2060    pub fn accept_edit_prediction_keybind(
 2061        &self,
 2062        window: &Window,
 2063        cx: &App,
 2064    ) -> AcceptEditPredictionBinding {
 2065        let key_context = self.key_context_internal(true, window, cx);
 2066        let in_conflict = self.edit_prediction_in_conflict();
 2067
 2068        AcceptEditPredictionBinding(
 2069            window
 2070                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2071                .into_iter()
 2072                .filter(|binding| {
 2073                    !in_conflict
 2074                        || binding
 2075                            .keystrokes()
 2076                            .first()
 2077                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2078                })
 2079                .rev()
 2080                .min_by_key(|binding| {
 2081                    binding
 2082                        .keystrokes()
 2083                        .first()
 2084                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2085                }),
 2086        )
 2087    }
 2088
 2089    pub fn new_file(
 2090        workspace: &mut Workspace,
 2091        _: &workspace::NewFile,
 2092        window: &mut Window,
 2093        cx: &mut Context<Workspace>,
 2094    ) {
 2095        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2096            "Failed to create buffer",
 2097            window,
 2098            cx,
 2099            |e, _, _| match e.error_code() {
 2100                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2101                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2102                e.error_tag("required").unwrap_or("the latest version")
 2103            )),
 2104                _ => None,
 2105            },
 2106        );
 2107    }
 2108
 2109    pub fn new_in_workspace(
 2110        workspace: &mut Workspace,
 2111        window: &mut Window,
 2112        cx: &mut Context<Workspace>,
 2113    ) -> Task<Result<Entity<Editor>>> {
 2114        let project = workspace.project().clone();
 2115        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2116
 2117        cx.spawn_in(window, async move |workspace, cx| {
 2118            let buffer = create.await?;
 2119            workspace.update_in(cx, |workspace, window, cx| {
 2120                let editor =
 2121                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2122                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2123                editor
 2124            })
 2125        })
 2126    }
 2127
 2128    fn new_file_vertical(
 2129        workspace: &mut Workspace,
 2130        _: &workspace::NewFileSplitVertical,
 2131        window: &mut Window,
 2132        cx: &mut Context<Workspace>,
 2133    ) {
 2134        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2135    }
 2136
 2137    fn new_file_horizontal(
 2138        workspace: &mut Workspace,
 2139        _: &workspace::NewFileSplitHorizontal,
 2140        window: &mut Window,
 2141        cx: &mut Context<Workspace>,
 2142    ) {
 2143        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2144    }
 2145
 2146    fn new_file_in_direction(
 2147        workspace: &mut Workspace,
 2148        direction: SplitDirection,
 2149        window: &mut Window,
 2150        cx: &mut Context<Workspace>,
 2151    ) {
 2152        let project = workspace.project().clone();
 2153        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2154
 2155        cx.spawn_in(window, async move |workspace, cx| {
 2156            let buffer = create.await?;
 2157            workspace.update_in(cx, move |workspace, window, cx| {
 2158                workspace.split_item(
 2159                    direction,
 2160                    Box::new(
 2161                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2162                    ),
 2163                    window,
 2164                    cx,
 2165                )
 2166            })?;
 2167            anyhow::Ok(())
 2168        })
 2169        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2170            match e.error_code() {
 2171                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2172                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2173                e.error_tag("required").unwrap_or("the latest version")
 2174            )),
 2175                _ => None,
 2176            }
 2177        });
 2178    }
 2179
 2180    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2181        self.leader_id
 2182    }
 2183
 2184    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2185        &self.buffer
 2186    }
 2187
 2188    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2189        self.workspace.as_ref()?.0.upgrade()
 2190    }
 2191
 2192    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2193        self.buffer().read(cx).title(cx)
 2194    }
 2195
 2196    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2197        let git_blame_gutter_max_author_length = self
 2198            .render_git_blame_gutter(cx)
 2199            .then(|| {
 2200                if let Some(blame) = self.blame.as_ref() {
 2201                    let max_author_length =
 2202                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2203                    Some(max_author_length)
 2204                } else {
 2205                    None
 2206                }
 2207            })
 2208            .flatten();
 2209
 2210        EditorSnapshot {
 2211            mode: self.mode,
 2212            show_gutter: self.show_gutter,
 2213            show_line_numbers: self.show_line_numbers,
 2214            show_git_diff_gutter: self.show_git_diff_gutter,
 2215            show_code_actions: self.show_code_actions,
 2216            show_runnables: self.show_runnables,
 2217            show_breakpoints: self.show_breakpoints,
 2218            git_blame_gutter_max_author_length,
 2219            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2220            scroll_anchor: self.scroll_manager.anchor(),
 2221            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2222            placeholder_text: self.placeholder_text.clone(),
 2223            is_focused: self.focus_handle.is_focused(window),
 2224            current_line_highlight: self
 2225                .current_line_highlight
 2226                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2227            gutter_hovered: self.gutter_hovered,
 2228        }
 2229    }
 2230
 2231    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2232        self.buffer.read(cx).language_at(point, cx)
 2233    }
 2234
 2235    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2236        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2237    }
 2238
 2239    pub fn active_excerpt(
 2240        &self,
 2241        cx: &App,
 2242    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2243        self.buffer
 2244            .read(cx)
 2245            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2246    }
 2247
 2248    pub fn mode(&self) -> EditorMode {
 2249        self.mode
 2250    }
 2251
 2252    pub fn set_mode(&mut self, mode: EditorMode) {
 2253        self.mode = mode;
 2254    }
 2255
 2256    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2257        self.collaboration_hub.as_deref()
 2258    }
 2259
 2260    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2261        self.collaboration_hub = Some(hub);
 2262    }
 2263
 2264    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2265        self.in_project_search = in_project_search;
 2266    }
 2267
 2268    pub fn set_custom_context_menu(
 2269        &mut self,
 2270        f: impl 'static
 2271        + Fn(
 2272            &mut Self,
 2273            DisplayPoint,
 2274            &mut Window,
 2275            &mut Context<Self>,
 2276        ) -> Option<Entity<ui::ContextMenu>>,
 2277    ) {
 2278        self.custom_context_menu = Some(Box::new(f))
 2279    }
 2280
 2281    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2282        self.completion_provider = provider;
 2283    }
 2284
 2285    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2286        self.semantics_provider.clone()
 2287    }
 2288
 2289    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2290        self.semantics_provider = provider;
 2291    }
 2292
 2293    pub fn set_edit_prediction_provider<T>(
 2294        &mut self,
 2295        provider: Option<Entity<T>>,
 2296        window: &mut Window,
 2297        cx: &mut Context<Self>,
 2298    ) where
 2299        T: EditPredictionProvider,
 2300    {
 2301        self.edit_prediction_provider =
 2302            provider.map(|provider| RegisteredInlineCompletionProvider {
 2303                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2304                    if this.focus_handle.is_focused(window) {
 2305                        this.update_visible_inline_completion(window, cx);
 2306                    }
 2307                }),
 2308                provider: Arc::new(provider),
 2309            });
 2310        self.update_edit_prediction_settings(cx);
 2311        self.refresh_inline_completion(false, false, window, cx);
 2312    }
 2313
 2314    pub fn placeholder_text(&self) -> Option<&str> {
 2315        self.placeholder_text.as_deref()
 2316    }
 2317
 2318    pub fn set_placeholder_text(
 2319        &mut self,
 2320        placeholder_text: impl Into<Arc<str>>,
 2321        cx: &mut Context<Self>,
 2322    ) {
 2323        let placeholder_text = Some(placeholder_text.into());
 2324        if self.placeholder_text != placeholder_text {
 2325            self.placeholder_text = placeholder_text;
 2326            cx.notify();
 2327        }
 2328    }
 2329
 2330    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2331        self.cursor_shape = cursor_shape;
 2332
 2333        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2334        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2335
 2336        cx.notify();
 2337    }
 2338
 2339    pub fn set_current_line_highlight(
 2340        &mut self,
 2341        current_line_highlight: Option<CurrentLineHighlight>,
 2342    ) {
 2343        self.current_line_highlight = current_line_highlight;
 2344    }
 2345
 2346    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2347        self.collapse_matches = collapse_matches;
 2348    }
 2349
 2350    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2351        let buffers = self.buffer.read(cx).all_buffers();
 2352        let Some(project) = self.project.as_ref() else {
 2353            return;
 2354        };
 2355        project.update(cx, |project, cx| {
 2356            for buffer in buffers {
 2357                self.registered_buffers
 2358                    .entry(buffer.read(cx).remote_id())
 2359                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2360            }
 2361        })
 2362    }
 2363
 2364    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2365        if self.collapse_matches {
 2366            return range.start..range.start;
 2367        }
 2368        range.clone()
 2369    }
 2370
 2371    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2372        if self.display_map.read(cx).clip_at_line_ends != clip {
 2373            self.display_map
 2374                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2375        }
 2376    }
 2377
 2378    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2379        self.input_enabled = input_enabled;
 2380    }
 2381
 2382    pub fn set_inline_completions_hidden_for_vim_mode(
 2383        &mut self,
 2384        hidden: bool,
 2385        window: &mut Window,
 2386        cx: &mut Context<Self>,
 2387    ) {
 2388        if hidden != self.inline_completions_hidden_for_vim_mode {
 2389            self.inline_completions_hidden_for_vim_mode = hidden;
 2390            if hidden {
 2391                self.update_visible_inline_completion(window, cx);
 2392            } else {
 2393                self.refresh_inline_completion(true, false, window, cx);
 2394            }
 2395        }
 2396    }
 2397
 2398    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2399        self.menu_inline_completions_policy = value;
 2400    }
 2401
 2402    pub fn set_autoindent(&mut self, autoindent: bool) {
 2403        if autoindent {
 2404            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2405        } else {
 2406            self.autoindent_mode = None;
 2407        }
 2408    }
 2409
 2410    pub fn read_only(&self, cx: &App) -> bool {
 2411        self.read_only || self.buffer.read(cx).read_only()
 2412    }
 2413
 2414    pub fn set_read_only(&mut self, read_only: bool) {
 2415        self.read_only = read_only;
 2416    }
 2417
 2418    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2419        self.use_autoclose = autoclose;
 2420    }
 2421
 2422    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2423        self.use_auto_surround = auto_surround;
 2424    }
 2425
 2426    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2427        self.auto_replace_emoji_shortcode = auto_replace;
 2428    }
 2429
 2430    pub fn toggle_edit_predictions(
 2431        &mut self,
 2432        _: &ToggleEditPrediction,
 2433        window: &mut Window,
 2434        cx: &mut Context<Self>,
 2435    ) {
 2436        if self.show_inline_completions_override.is_some() {
 2437            self.set_show_edit_predictions(None, window, cx);
 2438        } else {
 2439            let show_edit_predictions = !self.edit_predictions_enabled();
 2440            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2441        }
 2442    }
 2443
 2444    pub fn set_show_edit_predictions(
 2445        &mut self,
 2446        show_edit_predictions: Option<bool>,
 2447        window: &mut Window,
 2448        cx: &mut Context<Self>,
 2449    ) {
 2450        self.show_inline_completions_override = show_edit_predictions;
 2451        self.update_edit_prediction_settings(cx);
 2452
 2453        if let Some(false) = show_edit_predictions {
 2454            self.discard_inline_completion(false, cx);
 2455        } else {
 2456            self.refresh_inline_completion(false, true, window, cx);
 2457        }
 2458    }
 2459
 2460    fn inline_completions_disabled_in_scope(
 2461        &self,
 2462        buffer: &Entity<Buffer>,
 2463        buffer_position: language::Anchor,
 2464        cx: &App,
 2465    ) -> bool {
 2466        let snapshot = buffer.read(cx).snapshot();
 2467        let settings = snapshot.settings_at(buffer_position, cx);
 2468
 2469        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2470            return false;
 2471        };
 2472
 2473        scope.override_name().map_or(false, |scope_name| {
 2474            settings
 2475                .edit_predictions_disabled_in
 2476                .iter()
 2477                .any(|s| s == scope_name)
 2478        })
 2479    }
 2480
 2481    pub fn set_use_modal_editing(&mut self, to: bool) {
 2482        self.use_modal_editing = to;
 2483    }
 2484
 2485    pub fn use_modal_editing(&self) -> bool {
 2486        self.use_modal_editing
 2487    }
 2488
 2489    fn selections_did_change(
 2490        &mut self,
 2491        local: bool,
 2492        old_cursor_position: &Anchor,
 2493        show_completions: bool,
 2494        window: &mut Window,
 2495        cx: &mut Context<Self>,
 2496    ) {
 2497        window.invalidate_character_coordinates();
 2498
 2499        // Copy selections to primary selection buffer
 2500        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2501        if local {
 2502            let selections = self.selections.all::<usize>(cx);
 2503            let buffer_handle = self.buffer.read(cx).read(cx);
 2504
 2505            let mut text = String::new();
 2506            for (index, selection) in selections.iter().enumerate() {
 2507                let text_for_selection = buffer_handle
 2508                    .text_for_range(selection.start..selection.end)
 2509                    .collect::<String>();
 2510
 2511                text.push_str(&text_for_selection);
 2512                if index != selections.len() - 1 {
 2513                    text.push('\n');
 2514                }
 2515            }
 2516
 2517            if !text.is_empty() {
 2518                cx.write_to_primary(ClipboardItem::new_string(text));
 2519            }
 2520        }
 2521
 2522        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2523            self.buffer.update(cx, |buffer, cx| {
 2524                buffer.set_active_selections(
 2525                    &self.selections.disjoint_anchors(),
 2526                    self.selections.line_mode,
 2527                    self.cursor_shape,
 2528                    cx,
 2529                )
 2530            });
 2531        }
 2532        let display_map = self
 2533            .display_map
 2534            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2535        let buffer = &display_map.buffer_snapshot;
 2536        self.add_selections_state = None;
 2537        self.select_next_state = None;
 2538        self.select_prev_state = None;
 2539        self.select_syntax_node_history.try_clear();
 2540        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2541        self.snippet_stack
 2542            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2543        self.take_rename(false, window, cx);
 2544
 2545        let new_cursor_position = self.selections.newest_anchor().head();
 2546
 2547        self.push_to_nav_history(
 2548            *old_cursor_position,
 2549            Some(new_cursor_position.to_point(buffer)),
 2550            false,
 2551            cx,
 2552        );
 2553
 2554        if local {
 2555            let new_cursor_position = self.selections.newest_anchor().head();
 2556            let mut context_menu = self.context_menu.borrow_mut();
 2557            let completion_menu = match context_menu.as_ref() {
 2558                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2559                _ => {
 2560                    *context_menu = None;
 2561                    None
 2562                }
 2563            };
 2564            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2565                if !self.registered_buffers.contains_key(&buffer_id) {
 2566                    if let Some(project) = self.project.as_ref() {
 2567                        project.update(cx, |project, cx| {
 2568                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2569                                return;
 2570                            };
 2571                            self.registered_buffers.insert(
 2572                                buffer_id,
 2573                                project.register_buffer_with_language_servers(&buffer, cx),
 2574                            );
 2575                        })
 2576                    }
 2577                }
 2578            }
 2579
 2580            if let Some(completion_menu) = completion_menu {
 2581                let cursor_position = new_cursor_position.to_offset(buffer);
 2582                let (word_range, kind) =
 2583                    buffer.surrounding_word(completion_menu.initial_position, true);
 2584                if kind == Some(CharKind::Word)
 2585                    && word_range.to_inclusive().contains(&cursor_position)
 2586                {
 2587                    let mut completion_menu = completion_menu.clone();
 2588                    drop(context_menu);
 2589
 2590                    let query = Self::completion_query(buffer, cursor_position);
 2591                    cx.spawn(async move |this, cx| {
 2592                        completion_menu
 2593                            .filter(query.as_deref(), cx.background_executor().clone())
 2594                            .await;
 2595
 2596                        this.update(cx, |this, cx| {
 2597                            let mut context_menu = this.context_menu.borrow_mut();
 2598                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2599                            else {
 2600                                return;
 2601                            };
 2602
 2603                            if menu.id > completion_menu.id {
 2604                                return;
 2605                            }
 2606
 2607                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2608                            drop(context_menu);
 2609                            cx.notify();
 2610                        })
 2611                    })
 2612                    .detach();
 2613
 2614                    if show_completions {
 2615                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2616                    }
 2617                } else {
 2618                    drop(context_menu);
 2619                    self.hide_context_menu(window, cx);
 2620                }
 2621            } else {
 2622                drop(context_menu);
 2623            }
 2624
 2625            hide_hover(self, cx);
 2626
 2627            if old_cursor_position.to_display_point(&display_map).row()
 2628                != new_cursor_position.to_display_point(&display_map).row()
 2629            {
 2630                self.available_code_actions.take();
 2631            }
 2632            self.refresh_code_actions(window, cx);
 2633            self.refresh_document_highlights(cx);
 2634            self.refresh_selected_text_highlights(false, window, cx);
 2635            refresh_matching_bracket_highlights(self, window, cx);
 2636            self.update_visible_inline_completion(window, cx);
 2637            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2638            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2639            self.inline_blame_popover.take();
 2640            if self.git_blame_inline_enabled {
 2641                self.start_inline_blame_timer(window, cx);
 2642            }
 2643        }
 2644
 2645        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2646        cx.emit(EditorEvent::SelectionsChanged { local });
 2647
 2648        let selections = &self.selections.disjoint;
 2649        if selections.len() == 1 {
 2650            cx.emit(SearchEvent::ActiveMatchChanged)
 2651        }
 2652        if local {
 2653            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2654                let inmemory_selections = selections
 2655                    .iter()
 2656                    .map(|s| {
 2657                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2658                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2659                    })
 2660                    .collect();
 2661                self.update_restoration_data(cx, |data| {
 2662                    data.selections = inmemory_selections;
 2663                });
 2664
 2665                if WorkspaceSettings::get(None, cx).restore_on_startup
 2666                    != RestoreOnStartupBehavior::None
 2667                {
 2668                    if let Some(workspace_id) =
 2669                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2670                    {
 2671                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2672                        let selections = selections.clone();
 2673                        let background_executor = cx.background_executor().clone();
 2674                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2675                        self.serialize_selections = cx.background_spawn(async move {
 2676                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2677                    let db_selections = selections
 2678                        .iter()
 2679                        .map(|selection| {
 2680                            (
 2681                                selection.start.to_offset(&snapshot),
 2682                                selection.end.to_offset(&snapshot),
 2683                            )
 2684                        })
 2685                        .collect();
 2686
 2687                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2688                        .await
 2689                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2690                        .log_err();
 2691                });
 2692                    }
 2693                }
 2694            }
 2695        }
 2696
 2697        cx.notify();
 2698    }
 2699
 2700    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2701        use text::ToOffset as _;
 2702        use text::ToPoint as _;
 2703
 2704        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2705            return;
 2706        }
 2707
 2708        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2709            return;
 2710        };
 2711
 2712        let snapshot = singleton.read(cx).snapshot();
 2713        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2714            let display_snapshot = display_map.snapshot(cx);
 2715
 2716            display_snapshot
 2717                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2718                .map(|fold| {
 2719                    fold.range.start.text_anchor.to_point(&snapshot)
 2720                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2721                })
 2722                .collect()
 2723        });
 2724        self.update_restoration_data(cx, |data| {
 2725            data.folds = inmemory_folds;
 2726        });
 2727
 2728        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2729            return;
 2730        };
 2731        let background_executor = cx.background_executor().clone();
 2732        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2733        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2734            display_map
 2735                .snapshot(cx)
 2736                .folds_in_range(0..snapshot.len())
 2737                .map(|fold| {
 2738                    (
 2739                        fold.range.start.text_anchor.to_offset(&snapshot),
 2740                        fold.range.end.text_anchor.to_offset(&snapshot),
 2741                    )
 2742                })
 2743                .collect()
 2744        });
 2745        self.serialize_folds = cx.background_spawn(async move {
 2746            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2747            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2748                .await
 2749                .with_context(|| {
 2750                    format!(
 2751                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2752                    )
 2753                })
 2754                .log_err();
 2755        });
 2756    }
 2757
 2758    pub fn sync_selections(
 2759        &mut self,
 2760        other: Entity<Editor>,
 2761        cx: &mut Context<Self>,
 2762    ) -> gpui::Subscription {
 2763        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2764        self.selections.change_with(cx, |selections| {
 2765            selections.select_anchors(other_selections);
 2766        });
 2767
 2768        let other_subscription =
 2769            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2770                EditorEvent::SelectionsChanged { local: true } => {
 2771                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2772                    if other_selections.is_empty() {
 2773                        return;
 2774                    }
 2775                    this.selections.change_with(cx, |selections| {
 2776                        selections.select_anchors(other_selections);
 2777                    });
 2778                }
 2779                _ => {}
 2780            });
 2781
 2782        let this_subscription =
 2783            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2784                EditorEvent::SelectionsChanged { local: true } => {
 2785                    let these_selections = this.selections.disjoint.to_vec();
 2786                    if these_selections.is_empty() {
 2787                        return;
 2788                    }
 2789                    other.update(cx, |other_editor, cx| {
 2790                        other_editor.selections.change_with(cx, |selections| {
 2791                            selections.select_anchors(these_selections);
 2792                        })
 2793                    });
 2794                }
 2795                _ => {}
 2796            });
 2797
 2798        Subscription::join(other_subscription, this_subscription)
 2799    }
 2800
 2801    pub fn change_selections<R>(
 2802        &mut self,
 2803        autoscroll: Option<Autoscroll>,
 2804        window: &mut Window,
 2805        cx: &mut Context<Self>,
 2806        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2807    ) -> R {
 2808        self.change_selections_inner(autoscroll, true, window, cx, change)
 2809    }
 2810
 2811    fn change_selections_inner<R>(
 2812        &mut self,
 2813        autoscroll: Option<Autoscroll>,
 2814        request_completions: bool,
 2815        window: &mut Window,
 2816        cx: &mut Context<Self>,
 2817        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2818    ) -> R {
 2819        let old_cursor_position = self.selections.newest_anchor().head();
 2820        self.push_to_selection_history();
 2821
 2822        let (changed, result) = self.selections.change_with(cx, change);
 2823
 2824        if changed {
 2825            if let Some(autoscroll) = autoscroll {
 2826                self.request_autoscroll(autoscroll, cx);
 2827            }
 2828            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2829
 2830            if self.should_open_signature_help_automatically(
 2831                &old_cursor_position,
 2832                self.signature_help_state.backspace_pressed(),
 2833                cx,
 2834            ) {
 2835                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2836            }
 2837            self.signature_help_state.set_backspace_pressed(false);
 2838        }
 2839
 2840        result
 2841    }
 2842
 2843    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2844    where
 2845        I: IntoIterator<Item = (Range<S>, T)>,
 2846        S: ToOffset,
 2847        T: Into<Arc<str>>,
 2848    {
 2849        if self.read_only(cx) {
 2850            return;
 2851        }
 2852
 2853        self.buffer
 2854            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2855    }
 2856
 2857    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2858    where
 2859        I: IntoIterator<Item = (Range<S>, T)>,
 2860        S: ToOffset,
 2861        T: Into<Arc<str>>,
 2862    {
 2863        if self.read_only(cx) {
 2864            return;
 2865        }
 2866
 2867        self.buffer.update(cx, |buffer, cx| {
 2868            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2869        });
 2870    }
 2871
 2872    pub fn edit_with_block_indent<I, S, T>(
 2873        &mut self,
 2874        edits: I,
 2875        original_indent_columns: Vec<Option<u32>>,
 2876        cx: &mut Context<Self>,
 2877    ) where
 2878        I: IntoIterator<Item = (Range<S>, T)>,
 2879        S: ToOffset,
 2880        T: Into<Arc<str>>,
 2881    {
 2882        if self.read_only(cx) {
 2883            return;
 2884        }
 2885
 2886        self.buffer.update(cx, |buffer, cx| {
 2887            buffer.edit(
 2888                edits,
 2889                Some(AutoindentMode::Block {
 2890                    original_indent_columns,
 2891                }),
 2892                cx,
 2893            )
 2894        });
 2895    }
 2896
 2897    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2898        self.hide_context_menu(window, cx);
 2899
 2900        match phase {
 2901            SelectPhase::Begin {
 2902                position,
 2903                add,
 2904                click_count,
 2905            } => self.begin_selection(position, add, click_count, window, cx),
 2906            SelectPhase::BeginColumnar {
 2907                position,
 2908                goal_column,
 2909                reset,
 2910            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2911            SelectPhase::Extend {
 2912                position,
 2913                click_count,
 2914            } => self.extend_selection(position, click_count, window, cx),
 2915            SelectPhase::Update {
 2916                position,
 2917                goal_column,
 2918                scroll_delta,
 2919            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2920            SelectPhase::End => self.end_selection(window, cx),
 2921        }
 2922    }
 2923
 2924    fn extend_selection(
 2925        &mut self,
 2926        position: DisplayPoint,
 2927        click_count: usize,
 2928        window: &mut Window,
 2929        cx: &mut Context<Self>,
 2930    ) {
 2931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2932        let tail = self.selections.newest::<usize>(cx).tail();
 2933        self.begin_selection(position, false, click_count, window, cx);
 2934
 2935        let position = position.to_offset(&display_map, Bias::Left);
 2936        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2937
 2938        let mut pending_selection = self
 2939            .selections
 2940            .pending_anchor()
 2941            .expect("extend_selection not called with pending selection");
 2942        if position >= tail {
 2943            pending_selection.start = tail_anchor;
 2944        } else {
 2945            pending_selection.end = tail_anchor;
 2946            pending_selection.reversed = true;
 2947        }
 2948
 2949        let mut pending_mode = self.selections.pending_mode().unwrap();
 2950        match &mut pending_mode {
 2951            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2952            _ => {}
 2953        }
 2954
 2955        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 2956
 2957        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 2958            s.set_pending(pending_selection, pending_mode)
 2959        });
 2960    }
 2961
 2962    fn begin_selection(
 2963        &mut self,
 2964        position: DisplayPoint,
 2965        add: bool,
 2966        click_count: usize,
 2967        window: &mut Window,
 2968        cx: &mut Context<Self>,
 2969    ) {
 2970        if !self.focus_handle.is_focused(window) {
 2971            self.last_focused_descendant = None;
 2972            window.focus(&self.focus_handle);
 2973        }
 2974
 2975        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2976        let buffer = &display_map.buffer_snapshot;
 2977        let position = display_map.clip_point(position, Bias::Left);
 2978
 2979        let start;
 2980        let end;
 2981        let mode;
 2982        let mut auto_scroll;
 2983        match click_count {
 2984            1 => {
 2985                start = buffer.anchor_before(position.to_point(&display_map));
 2986                end = start;
 2987                mode = SelectMode::Character;
 2988                auto_scroll = true;
 2989            }
 2990            2 => {
 2991                let range = movement::surrounding_word(&display_map, position);
 2992                start = buffer.anchor_before(range.start.to_point(&display_map));
 2993                end = buffer.anchor_before(range.end.to_point(&display_map));
 2994                mode = SelectMode::Word(start..end);
 2995                auto_scroll = true;
 2996            }
 2997            3 => {
 2998                let position = display_map
 2999                    .clip_point(position, Bias::Left)
 3000                    .to_point(&display_map);
 3001                let line_start = display_map.prev_line_boundary(position).0;
 3002                let next_line_start = buffer.clip_point(
 3003                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3004                    Bias::Left,
 3005                );
 3006                start = buffer.anchor_before(line_start);
 3007                end = buffer.anchor_before(next_line_start);
 3008                mode = SelectMode::Line(start..end);
 3009                auto_scroll = true;
 3010            }
 3011            _ => {
 3012                start = buffer.anchor_before(0);
 3013                end = buffer.anchor_before(buffer.len());
 3014                mode = SelectMode::All;
 3015                auto_scroll = false;
 3016            }
 3017        }
 3018        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3019
 3020        let point_to_delete: Option<usize> = {
 3021            let selected_points: Vec<Selection<Point>> =
 3022                self.selections.disjoint_in_range(start..end, cx);
 3023
 3024            if !add || click_count > 1 {
 3025                None
 3026            } else if !selected_points.is_empty() {
 3027                Some(selected_points[0].id)
 3028            } else {
 3029                let clicked_point_already_selected =
 3030                    self.selections.disjoint.iter().find(|selection| {
 3031                        selection.start.to_point(buffer) == start.to_point(buffer)
 3032                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3033                    });
 3034
 3035                clicked_point_already_selected.map(|selection| selection.id)
 3036            }
 3037        };
 3038
 3039        let selections_count = self.selections.count();
 3040
 3041        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3042            if let Some(point_to_delete) = point_to_delete {
 3043                s.delete(point_to_delete);
 3044
 3045                if selections_count == 1 {
 3046                    s.set_pending_anchor_range(start..end, mode);
 3047                }
 3048            } else {
 3049                if !add {
 3050                    s.clear_disjoint();
 3051                }
 3052
 3053                s.set_pending_anchor_range(start..end, mode);
 3054            }
 3055        });
 3056    }
 3057
 3058    fn begin_columnar_selection(
 3059        &mut self,
 3060        position: DisplayPoint,
 3061        goal_column: u32,
 3062        reset: bool,
 3063        window: &mut Window,
 3064        cx: &mut Context<Self>,
 3065    ) {
 3066        if !self.focus_handle.is_focused(window) {
 3067            self.last_focused_descendant = None;
 3068            window.focus(&self.focus_handle);
 3069        }
 3070
 3071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3072
 3073        if reset {
 3074            let pointer_position = display_map
 3075                .buffer_snapshot
 3076                .anchor_before(position.to_point(&display_map));
 3077
 3078            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3079                s.clear_disjoint();
 3080                s.set_pending_anchor_range(
 3081                    pointer_position..pointer_position,
 3082                    SelectMode::Character,
 3083                );
 3084            });
 3085        }
 3086
 3087        let tail = self.selections.newest::<Point>(cx).tail();
 3088        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3089
 3090        if !reset {
 3091            self.select_columns(
 3092                tail.to_display_point(&display_map),
 3093                position,
 3094                goal_column,
 3095                &display_map,
 3096                window,
 3097                cx,
 3098            );
 3099        }
 3100    }
 3101
 3102    fn update_selection(
 3103        &mut self,
 3104        position: DisplayPoint,
 3105        goal_column: u32,
 3106        scroll_delta: gpui::Point<f32>,
 3107        window: &mut Window,
 3108        cx: &mut Context<Self>,
 3109    ) {
 3110        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3111
 3112        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3113            let tail = tail.to_display_point(&display_map);
 3114            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3115        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3116            let buffer = self.buffer.read(cx).snapshot(cx);
 3117            let head;
 3118            let tail;
 3119            let mode = self.selections.pending_mode().unwrap();
 3120            match &mode {
 3121                SelectMode::Character => {
 3122                    head = position.to_point(&display_map);
 3123                    tail = pending.tail().to_point(&buffer);
 3124                }
 3125                SelectMode::Word(original_range) => {
 3126                    let original_display_range = original_range.start.to_display_point(&display_map)
 3127                        ..original_range.end.to_display_point(&display_map);
 3128                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3129                        ..original_display_range.end.to_point(&display_map);
 3130                    if movement::is_inside_word(&display_map, position)
 3131                        || original_display_range.contains(&position)
 3132                    {
 3133                        let word_range = movement::surrounding_word(&display_map, position);
 3134                        if word_range.start < original_display_range.start {
 3135                            head = word_range.start.to_point(&display_map);
 3136                        } else {
 3137                            head = word_range.end.to_point(&display_map);
 3138                        }
 3139                    } else {
 3140                        head = position.to_point(&display_map);
 3141                    }
 3142
 3143                    if head <= original_buffer_range.start {
 3144                        tail = original_buffer_range.end;
 3145                    } else {
 3146                        tail = original_buffer_range.start;
 3147                    }
 3148                }
 3149                SelectMode::Line(original_range) => {
 3150                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3151
 3152                    let position = display_map
 3153                        .clip_point(position, Bias::Left)
 3154                        .to_point(&display_map);
 3155                    let line_start = display_map.prev_line_boundary(position).0;
 3156                    let next_line_start = buffer.clip_point(
 3157                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3158                        Bias::Left,
 3159                    );
 3160
 3161                    if line_start < original_range.start {
 3162                        head = line_start
 3163                    } else {
 3164                        head = next_line_start
 3165                    }
 3166
 3167                    if head <= original_range.start {
 3168                        tail = original_range.end;
 3169                    } else {
 3170                        tail = original_range.start;
 3171                    }
 3172                }
 3173                SelectMode::All => {
 3174                    return;
 3175                }
 3176            };
 3177
 3178            if head < tail {
 3179                pending.start = buffer.anchor_before(head);
 3180                pending.end = buffer.anchor_before(tail);
 3181                pending.reversed = true;
 3182            } else {
 3183                pending.start = buffer.anchor_before(tail);
 3184                pending.end = buffer.anchor_before(head);
 3185                pending.reversed = false;
 3186            }
 3187
 3188            self.change_selections(None, window, cx, |s| {
 3189                s.set_pending(pending, mode);
 3190            });
 3191        } else {
 3192            log::error!("update_selection dispatched with no pending selection");
 3193            return;
 3194        }
 3195
 3196        self.apply_scroll_delta(scroll_delta, window, cx);
 3197        cx.notify();
 3198    }
 3199
 3200    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3201        self.columnar_selection_tail.take();
 3202        if self.selections.pending_anchor().is_some() {
 3203            let selections = self.selections.all::<usize>(cx);
 3204            self.change_selections(None, window, cx, |s| {
 3205                s.select(selections);
 3206                s.clear_pending();
 3207            });
 3208        }
 3209    }
 3210
 3211    fn select_columns(
 3212        &mut self,
 3213        tail: DisplayPoint,
 3214        head: DisplayPoint,
 3215        goal_column: u32,
 3216        display_map: &DisplaySnapshot,
 3217        window: &mut Window,
 3218        cx: &mut Context<Self>,
 3219    ) {
 3220        let start_row = cmp::min(tail.row(), head.row());
 3221        let end_row = cmp::max(tail.row(), head.row());
 3222        let start_column = cmp::min(tail.column(), goal_column);
 3223        let end_column = cmp::max(tail.column(), goal_column);
 3224        let reversed = start_column < tail.column();
 3225
 3226        let selection_ranges = (start_row.0..=end_row.0)
 3227            .map(DisplayRow)
 3228            .filter_map(|row| {
 3229                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3230                    let start = display_map
 3231                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3232                        .to_point(display_map);
 3233                    let end = display_map
 3234                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3235                        .to_point(display_map);
 3236                    if reversed {
 3237                        Some(end..start)
 3238                    } else {
 3239                        Some(start..end)
 3240                    }
 3241                } else {
 3242                    None
 3243                }
 3244            })
 3245            .collect::<Vec<_>>();
 3246
 3247        self.change_selections(None, window, cx, |s| {
 3248            s.select_ranges(selection_ranges);
 3249        });
 3250        cx.notify();
 3251    }
 3252
 3253    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3254        self.selections
 3255            .all_adjusted(cx)
 3256            .iter()
 3257            .any(|selection| !selection.is_empty())
 3258    }
 3259
 3260    pub fn has_pending_nonempty_selection(&self) -> bool {
 3261        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3262            Some(Selection { start, end, .. }) => start != end,
 3263            None => false,
 3264        };
 3265
 3266        pending_nonempty_selection
 3267            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3268    }
 3269
 3270    pub fn has_pending_selection(&self) -> bool {
 3271        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3272    }
 3273
 3274    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3275        self.selection_mark_mode = false;
 3276
 3277        if self.clear_expanded_diff_hunks(cx) {
 3278            cx.notify();
 3279            return;
 3280        }
 3281        if self.dismiss_menus_and_popups(true, window, cx) {
 3282            return;
 3283        }
 3284
 3285        if self.mode.is_full()
 3286            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3287        {
 3288            return;
 3289        }
 3290
 3291        cx.propagate();
 3292    }
 3293
 3294    pub fn dismiss_menus_and_popups(
 3295        &mut self,
 3296        is_user_requested: bool,
 3297        window: &mut Window,
 3298        cx: &mut Context<Self>,
 3299    ) -> bool {
 3300        if self.take_rename(false, window, cx).is_some() {
 3301            return true;
 3302        }
 3303
 3304        if hide_hover(self, cx) {
 3305            return true;
 3306        }
 3307
 3308        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3309            return true;
 3310        }
 3311
 3312        if self.hide_context_menu(window, cx).is_some() {
 3313            return true;
 3314        }
 3315
 3316        if self.mouse_context_menu.take().is_some() {
 3317            return true;
 3318        }
 3319
 3320        if is_user_requested && self.discard_inline_completion(true, cx) {
 3321            return true;
 3322        }
 3323
 3324        if self.snippet_stack.pop().is_some() {
 3325            return true;
 3326        }
 3327
 3328        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3329            self.dismiss_diagnostics(cx);
 3330            return true;
 3331        }
 3332
 3333        false
 3334    }
 3335
 3336    fn linked_editing_ranges_for(
 3337        &self,
 3338        selection: Range<text::Anchor>,
 3339        cx: &App,
 3340    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3341        if self.linked_edit_ranges.is_empty() {
 3342            return None;
 3343        }
 3344        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3345            selection.end.buffer_id.and_then(|end_buffer_id| {
 3346                if selection.start.buffer_id != Some(end_buffer_id) {
 3347                    return None;
 3348                }
 3349                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3350                let snapshot = buffer.read(cx).snapshot();
 3351                self.linked_edit_ranges
 3352                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3353                    .map(|ranges| (ranges, snapshot, buffer))
 3354            })?;
 3355        use text::ToOffset as TO;
 3356        // find offset from the start of current range to current cursor position
 3357        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3358
 3359        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3360        let start_difference = start_offset - start_byte_offset;
 3361        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3362        let end_difference = end_offset - start_byte_offset;
 3363        // Current range has associated linked ranges.
 3364        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3365        for range in linked_ranges.iter() {
 3366            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3367            let end_offset = start_offset + end_difference;
 3368            let start_offset = start_offset + start_difference;
 3369            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3370                continue;
 3371            }
 3372            if self.selections.disjoint_anchor_ranges().any(|s| {
 3373                if s.start.buffer_id != selection.start.buffer_id
 3374                    || s.end.buffer_id != selection.end.buffer_id
 3375                {
 3376                    return false;
 3377                }
 3378                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3379                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3380            }) {
 3381                continue;
 3382            }
 3383            let start = buffer_snapshot.anchor_after(start_offset);
 3384            let end = buffer_snapshot.anchor_after(end_offset);
 3385            linked_edits
 3386                .entry(buffer.clone())
 3387                .or_default()
 3388                .push(start..end);
 3389        }
 3390        Some(linked_edits)
 3391    }
 3392
 3393    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3394        let text: Arc<str> = text.into();
 3395
 3396        if self.read_only(cx) {
 3397            return;
 3398        }
 3399
 3400        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3401
 3402        let selections = self.selections.all_adjusted(cx);
 3403        let mut bracket_inserted = false;
 3404        let mut edits = Vec::new();
 3405        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3406        let mut new_selections = Vec::with_capacity(selections.len());
 3407        let mut new_autoclose_regions = Vec::new();
 3408        let snapshot = self.buffer.read(cx).read(cx);
 3409        let mut clear_linked_edit_ranges = false;
 3410
 3411        for (selection, autoclose_region) in
 3412            self.selections_with_autoclose_regions(selections, &snapshot)
 3413        {
 3414            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3415                // Determine if the inserted text matches the opening or closing
 3416                // bracket of any of this language's bracket pairs.
 3417                let mut bracket_pair = None;
 3418                let mut is_bracket_pair_start = false;
 3419                let mut is_bracket_pair_end = false;
 3420                if !text.is_empty() {
 3421                    let mut bracket_pair_matching_end = None;
 3422                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3423                    //  and they are removing the character that triggered IME popup.
 3424                    for (pair, enabled) in scope.brackets() {
 3425                        if !pair.close && !pair.surround {
 3426                            continue;
 3427                        }
 3428
 3429                        if enabled && pair.start.ends_with(text.as_ref()) {
 3430                            let prefix_len = pair.start.len() - text.len();
 3431                            let preceding_text_matches_prefix = prefix_len == 0
 3432                                || (selection.start.column >= (prefix_len as u32)
 3433                                    && snapshot.contains_str_at(
 3434                                        Point::new(
 3435                                            selection.start.row,
 3436                                            selection.start.column - (prefix_len as u32),
 3437                                        ),
 3438                                        &pair.start[..prefix_len],
 3439                                    ));
 3440                            if preceding_text_matches_prefix {
 3441                                bracket_pair = Some(pair.clone());
 3442                                is_bracket_pair_start = true;
 3443                                break;
 3444                            }
 3445                        }
 3446                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3447                        {
 3448                            // take first bracket pair matching end, but don't break in case a later bracket
 3449                            // pair matches start
 3450                            bracket_pair_matching_end = Some(pair.clone());
 3451                        }
 3452                    }
 3453                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3454                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3455                        is_bracket_pair_end = true;
 3456                    }
 3457                }
 3458
 3459                if let Some(bracket_pair) = bracket_pair {
 3460                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3461                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3462                    let auto_surround =
 3463                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3464                    if selection.is_empty() {
 3465                        if is_bracket_pair_start {
 3466                            // If the inserted text is a suffix of an opening bracket and the
 3467                            // selection is preceded by the rest of the opening bracket, then
 3468                            // insert the closing bracket.
 3469                            let following_text_allows_autoclose = snapshot
 3470                                .chars_at(selection.start)
 3471                                .next()
 3472                                .map_or(true, |c| scope.should_autoclose_before(c));
 3473
 3474                            let preceding_text_allows_autoclose = selection.start.column == 0
 3475                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3476                                    true,
 3477                                    |c| {
 3478                                        bracket_pair.start != bracket_pair.end
 3479                                            || !snapshot
 3480                                                .char_classifier_at(selection.start)
 3481                                                .is_word(c)
 3482                                    },
 3483                                );
 3484
 3485                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3486                                && bracket_pair.start.len() == 1
 3487                            {
 3488                                let target = bracket_pair.start.chars().next().unwrap();
 3489                                let current_line_count = snapshot
 3490                                    .reversed_chars_at(selection.start)
 3491                                    .take_while(|&c| c != '\n')
 3492                                    .filter(|&c| c == target)
 3493                                    .count();
 3494                                current_line_count % 2 == 1
 3495                            } else {
 3496                                false
 3497                            };
 3498
 3499                            if autoclose
 3500                                && bracket_pair.close
 3501                                && following_text_allows_autoclose
 3502                                && preceding_text_allows_autoclose
 3503                                && !is_closing_quote
 3504                            {
 3505                                let anchor = snapshot.anchor_before(selection.end);
 3506                                new_selections.push((selection.map(|_| anchor), text.len()));
 3507                                new_autoclose_regions.push((
 3508                                    anchor,
 3509                                    text.len(),
 3510                                    selection.id,
 3511                                    bracket_pair.clone(),
 3512                                ));
 3513                                edits.push((
 3514                                    selection.range(),
 3515                                    format!("{}{}", text, bracket_pair.end).into(),
 3516                                ));
 3517                                bracket_inserted = true;
 3518                                continue;
 3519                            }
 3520                        }
 3521
 3522                        if let Some(region) = autoclose_region {
 3523                            // If the selection is followed by an auto-inserted closing bracket,
 3524                            // then don't insert that closing bracket again; just move the selection
 3525                            // past the closing bracket.
 3526                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3527                                && text.as_ref() == region.pair.end.as_str();
 3528                            if should_skip {
 3529                                let anchor = snapshot.anchor_after(selection.end);
 3530                                new_selections
 3531                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3532                                continue;
 3533                            }
 3534                        }
 3535
 3536                        let always_treat_brackets_as_autoclosed = snapshot
 3537                            .language_settings_at(selection.start, cx)
 3538                            .always_treat_brackets_as_autoclosed;
 3539                        if always_treat_brackets_as_autoclosed
 3540                            && is_bracket_pair_end
 3541                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3542                        {
 3543                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3544                            // and the inserted text is a closing bracket and the selection is followed
 3545                            // by the closing bracket then move the selection past the closing bracket.
 3546                            let anchor = snapshot.anchor_after(selection.end);
 3547                            new_selections.push((selection.map(|_| anchor), text.len()));
 3548                            continue;
 3549                        }
 3550                    }
 3551                    // If an opening bracket is 1 character long and is typed while
 3552                    // text is selected, then surround that text with the bracket pair.
 3553                    else if auto_surround
 3554                        && bracket_pair.surround
 3555                        && is_bracket_pair_start
 3556                        && bracket_pair.start.chars().count() == 1
 3557                    {
 3558                        edits.push((selection.start..selection.start, text.clone()));
 3559                        edits.push((
 3560                            selection.end..selection.end,
 3561                            bracket_pair.end.as_str().into(),
 3562                        ));
 3563                        bracket_inserted = true;
 3564                        new_selections.push((
 3565                            Selection {
 3566                                id: selection.id,
 3567                                start: snapshot.anchor_after(selection.start),
 3568                                end: snapshot.anchor_before(selection.end),
 3569                                reversed: selection.reversed,
 3570                                goal: selection.goal,
 3571                            },
 3572                            0,
 3573                        ));
 3574                        continue;
 3575                    }
 3576                }
 3577            }
 3578
 3579            if self.auto_replace_emoji_shortcode
 3580                && selection.is_empty()
 3581                && text.as_ref().ends_with(':')
 3582            {
 3583                if let Some(possible_emoji_short_code) =
 3584                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3585                {
 3586                    if !possible_emoji_short_code.is_empty() {
 3587                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3588                            let emoji_shortcode_start = Point::new(
 3589                                selection.start.row,
 3590                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3591                            );
 3592
 3593                            // Remove shortcode from buffer
 3594                            edits.push((
 3595                                emoji_shortcode_start..selection.start,
 3596                                "".to_string().into(),
 3597                            ));
 3598                            new_selections.push((
 3599                                Selection {
 3600                                    id: selection.id,
 3601                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3602                                    end: snapshot.anchor_before(selection.start),
 3603                                    reversed: selection.reversed,
 3604                                    goal: selection.goal,
 3605                                },
 3606                                0,
 3607                            ));
 3608
 3609                            // Insert emoji
 3610                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3611                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3612                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3613
 3614                            continue;
 3615                        }
 3616                    }
 3617                }
 3618            }
 3619
 3620            // If not handling any auto-close operation, then just replace the selected
 3621            // text with the given input and move the selection to the end of the
 3622            // newly inserted text.
 3623            let anchor = snapshot.anchor_after(selection.end);
 3624            if !self.linked_edit_ranges.is_empty() {
 3625                let start_anchor = snapshot.anchor_before(selection.start);
 3626
 3627                let is_word_char = text.chars().next().map_or(true, |char| {
 3628                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3629                    classifier.is_word(char)
 3630                });
 3631
 3632                if is_word_char {
 3633                    if let Some(ranges) = self
 3634                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3635                    {
 3636                        for (buffer, edits) in ranges {
 3637                            linked_edits
 3638                                .entry(buffer.clone())
 3639                                .or_default()
 3640                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3641                        }
 3642                    }
 3643                } else {
 3644                    clear_linked_edit_ranges = true;
 3645                }
 3646            }
 3647
 3648            new_selections.push((selection.map(|_| anchor), 0));
 3649            edits.push((selection.start..selection.end, text.clone()));
 3650        }
 3651
 3652        drop(snapshot);
 3653
 3654        self.transact(window, cx, |this, window, cx| {
 3655            if clear_linked_edit_ranges {
 3656                this.linked_edit_ranges.clear();
 3657            }
 3658            let initial_buffer_versions =
 3659                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3660
 3661            this.buffer.update(cx, |buffer, cx| {
 3662                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3663            });
 3664            for (buffer, edits) in linked_edits {
 3665                buffer.update(cx, |buffer, cx| {
 3666                    let snapshot = buffer.snapshot();
 3667                    let edits = edits
 3668                        .into_iter()
 3669                        .map(|(range, text)| {
 3670                            use text::ToPoint as TP;
 3671                            let end_point = TP::to_point(&range.end, &snapshot);
 3672                            let start_point = TP::to_point(&range.start, &snapshot);
 3673                            (start_point..end_point, text)
 3674                        })
 3675                        .sorted_by_key(|(range, _)| range.start);
 3676                    buffer.edit(edits, None, cx);
 3677                })
 3678            }
 3679            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3680            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3681            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3682            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3683                .zip(new_selection_deltas)
 3684                .map(|(selection, delta)| Selection {
 3685                    id: selection.id,
 3686                    start: selection.start + delta,
 3687                    end: selection.end + delta,
 3688                    reversed: selection.reversed,
 3689                    goal: SelectionGoal::None,
 3690                })
 3691                .collect::<Vec<_>>();
 3692
 3693            let mut i = 0;
 3694            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3695                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3696                let start = map.buffer_snapshot.anchor_before(position);
 3697                let end = map.buffer_snapshot.anchor_after(position);
 3698                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3699                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3700                        Ordering::Less => i += 1,
 3701                        Ordering::Greater => break,
 3702                        Ordering::Equal => {
 3703                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3704                                Ordering::Less => i += 1,
 3705                                Ordering::Equal => break,
 3706                                Ordering::Greater => break,
 3707                            }
 3708                        }
 3709                    }
 3710                }
 3711                this.autoclose_regions.insert(
 3712                    i,
 3713                    AutocloseRegion {
 3714                        selection_id,
 3715                        range: start..end,
 3716                        pair,
 3717                    },
 3718                );
 3719            }
 3720
 3721            let had_active_inline_completion = this.has_active_inline_completion();
 3722            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3723                s.select(new_selections)
 3724            });
 3725
 3726            if !bracket_inserted {
 3727                if let Some(on_type_format_task) =
 3728                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3729                {
 3730                    on_type_format_task.detach_and_log_err(cx);
 3731                }
 3732            }
 3733
 3734            let editor_settings = EditorSettings::get_global(cx);
 3735            if bracket_inserted
 3736                && (editor_settings.auto_signature_help
 3737                    || editor_settings.show_signature_help_after_edits)
 3738            {
 3739                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3740            }
 3741
 3742            let trigger_in_words =
 3743                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3744            if this.hard_wrap.is_some() {
 3745                let latest: Range<Point> = this.selections.newest(cx).range();
 3746                if latest.is_empty()
 3747                    && this
 3748                        .buffer()
 3749                        .read(cx)
 3750                        .snapshot(cx)
 3751                        .line_len(MultiBufferRow(latest.start.row))
 3752                        == latest.start.column
 3753                {
 3754                    this.rewrap_impl(
 3755                        RewrapOptions {
 3756                            override_language_settings: true,
 3757                            preserve_existing_whitespace: true,
 3758                        },
 3759                        cx,
 3760                    )
 3761                }
 3762            }
 3763            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3764            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3765            this.refresh_inline_completion(true, false, window, cx);
 3766            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3767        });
 3768    }
 3769
 3770    fn find_possible_emoji_shortcode_at_position(
 3771        snapshot: &MultiBufferSnapshot,
 3772        position: Point,
 3773    ) -> Option<String> {
 3774        let mut chars = Vec::new();
 3775        let mut found_colon = false;
 3776        for char in snapshot.reversed_chars_at(position).take(100) {
 3777            // Found a possible emoji shortcode in the middle of the buffer
 3778            if found_colon {
 3779                if char.is_whitespace() {
 3780                    chars.reverse();
 3781                    return Some(chars.iter().collect());
 3782                }
 3783                // If the previous character is not a whitespace, we are in the middle of a word
 3784                // and we only want to complete the shortcode if the word is made up of other emojis
 3785                let mut containing_word = String::new();
 3786                for ch in snapshot
 3787                    .reversed_chars_at(position)
 3788                    .skip(chars.len() + 1)
 3789                    .take(100)
 3790                {
 3791                    if ch.is_whitespace() {
 3792                        break;
 3793                    }
 3794                    containing_word.push(ch);
 3795                }
 3796                let containing_word = containing_word.chars().rev().collect::<String>();
 3797                if util::word_consists_of_emojis(containing_word.as_str()) {
 3798                    chars.reverse();
 3799                    return Some(chars.iter().collect());
 3800                }
 3801            }
 3802
 3803            if char.is_whitespace() || !char.is_ascii() {
 3804                return None;
 3805            }
 3806            if char == ':' {
 3807                found_colon = true;
 3808            } else {
 3809                chars.push(char);
 3810            }
 3811        }
 3812        // Found a possible emoji shortcode at the beginning of the buffer
 3813        chars.reverse();
 3814        Some(chars.iter().collect())
 3815    }
 3816
 3817    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3818        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3819        self.transact(window, cx, |this, window, cx| {
 3820            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3821                let selections = this.selections.all::<usize>(cx);
 3822                let multi_buffer = this.buffer.read(cx);
 3823                let buffer = multi_buffer.snapshot(cx);
 3824                selections
 3825                    .iter()
 3826                    .map(|selection| {
 3827                        let start_point = selection.start.to_point(&buffer);
 3828                        let mut indent =
 3829                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3830                        indent.len = cmp::min(indent.len, start_point.column);
 3831                        let start = selection.start;
 3832                        let end = selection.end;
 3833                        let selection_is_empty = start == end;
 3834                        let language_scope = buffer.language_scope_at(start);
 3835                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3836                            &language_scope
 3837                        {
 3838                            let insert_extra_newline =
 3839                                insert_extra_newline_brackets(&buffer, start..end, language)
 3840                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3841
 3842                            // Comment extension on newline is allowed only for cursor selections
 3843                            let comment_delimiter = maybe!({
 3844                                if !selection_is_empty {
 3845                                    return None;
 3846                                }
 3847
 3848                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3849                                    return None;
 3850                                }
 3851
 3852                                let delimiters = language.line_comment_prefixes();
 3853                                let max_len_of_delimiter =
 3854                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3855                                let (snapshot, range) =
 3856                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3857
 3858                                let mut index_of_first_non_whitespace = 0;
 3859                                let comment_candidate = snapshot
 3860                                    .chars_for_range(range)
 3861                                    .skip_while(|c| {
 3862                                        let should_skip = c.is_whitespace();
 3863                                        if should_skip {
 3864                                            index_of_first_non_whitespace += 1;
 3865                                        }
 3866                                        should_skip
 3867                                    })
 3868                                    .take(max_len_of_delimiter)
 3869                                    .collect::<String>();
 3870                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3871                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3872                                })?;
 3873                                let cursor_is_placed_after_comment_marker =
 3874                                    index_of_first_non_whitespace + comment_prefix.len()
 3875                                        <= start_point.column as usize;
 3876                                if cursor_is_placed_after_comment_marker {
 3877                                    Some(comment_prefix.clone())
 3878                                } else {
 3879                                    None
 3880                                }
 3881                            });
 3882                            (comment_delimiter, insert_extra_newline)
 3883                        } else {
 3884                            (None, false)
 3885                        };
 3886
 3887                        let capacity_for_delimiter = comment_delimiter
 3888                            .as_deref()
 3889                            .map(str::len)
 3890                            .unwrap_or_default();
 3891                        let mut new_text =
 3892                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3893                        new_text.push('\n');
 3894                        new_text.extend(indent.chars());
 3895                        if let Some(delimiter) = &comment_delimiter {
 3896                            new_text.push_str(delimiter);
 3897                        }
 3898                        if insert_extra_newline {
 3899                            new_text = new_text.repeat(2);
 3900                        }
 3901
 3902                        let anchor = buffer.anchor_after(end);
 3903                        let new_selection = selection.map(|_| anchor);
 3904                        (
 3905                            (start..end, new_text),
 3906                            (insert_extra_newline, new_selection),
 3907                        )
 3908                    })
 3909                    .unzip()
 3910            };
 3911
 3912            this.edit_with_autoindent(edits, cx);
 3913            let buffer = this.buffer.read(cx).snapshot(cx);
 3914            let new_selections = selection_fixup_info
 3915                .into_iter()
 3916                .map(|(extra_newline_inserted, new_selection)| {
 3917                    let mut cursor = new_selection.end.to_point(&buffer);
 3918                    if extra_newline_inserted {
 3919                        cursor.row -= 1;
 3920                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3921                    }
 3922                    new_selection.map(|_| cursor)
 3923                })
 3924                .collect();
 3925
 3926            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3927                s.select(new_selections)
 3928            });
 3929            this.refresh_inline_completion(true, false, window, cx);
 3930        });
 3931    }
 3932
 3933    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3934        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3935
 3936        let buffer = self.buffer.read(cx);
 3937        let snapshot = buffer.snapshot(cx);
 3938
 3939        let mut edits = Vec::new();
 3940        let mut rows = Vec::new();
 3941
 3942        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3943            let cursor = selection.head();
 3944            let row = cursor.row;
 3945
 3946            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3947
 3948            let newline = "\n".to_string();
 3949            edits.push((start_of_line..start_of_line, newline));
 3950
 3951            rows.push(row + rows_inserted as u32);
 3952        }
 3953
 3954        self.transact(window, cx, |editor, window, cx| {
 3955            editor.edit(edits, cx);
 3956
 3957            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3958                let mut index = 0;
 3959                s.move_cursors_with(|map, _, _| {
 3960                    let row = rows[index];
 3961                    index += 1;
 3962
 3963                    let point = Point::new(row, 0);
 3964                    let boundary = map.next_line_boundary(point).1;
 3965                    let clipped = map.clip_point(boundary, Bias::Left);
 3966
 3967                    (clipped, SelectionGoal::None)
 3968                });
 3969            });
 3970
 3971            let mut indent_edits = Vec::new();
 3972            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3973            for row in rows {
 3974                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3975                for (row, indent) in indents {
 3976                    if indent.len == 0 {
 3977                        continue;
 3978                    }
 3979
 3980                    let text = match indent.kind {
 3981                        IndentKind::Space => " ".repeat(indent.len as usize),
 3982                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3983                    };
 3984                    let point = Point::new(row.0, 0);
 3985                    indent_edits.push((point..point, text));
 3986                }
 3987            }
 3988            editor.edit(indent_edits, cx);
 3989        });
 3990    }
 3991
 3992    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3993        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3994
 3995        let buffer = self.buffer.read(cx);
 3996        let snapshot = buffer.snapshot(cx);
 3997
 3998        let mut edits = Vec::new();
 3999        let mut rows = Vec::new();
 4000        let mut rows_inserted = 0;
 4001
 4002        for selection in self.selections.all_adjusted(cx) {
 4003            let cursor = selection.head();
 4004            let row = cursor.row;
 4005
 4006            let point = Point::new(row + 1, 0);
 4007            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4008
 4009            let newline = "\n".to_string();
 4010            edits.push((start_of_line..start_of_line, newline));
 4011
 4012            rows_inserted += 1;
 4013            rows.push(row + rows_inserted);
 4014        }
 4015
 4016        self.transact(window, cx, |editor, window, cx| {
 4017            editor.edit(edits, cx);
 4018
 4019            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4020                let mut index = 0;
 4021                s.move_cursors_with(|map, _, _| {
 4022                    let row = rows[index];
 4023                    index += 1;
 4024
 4025                    let point = Point::new(row, 0);
 4026                    let boundary = map.next_line_boundary(point).1;
 4027                    let clipped = map.clip_point(boundary, Bias::Left);
 4028
 4029                    (clipped, SelectionGoal::None)
 4030                });
 4031            });
 4032
 4033            let mut indent_edits = Vec::new();
 4034            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4035            for row in rows {
 4036                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4037                for (row, indent) in indents {
 4038                    if indent.len == 0 {
 4039                        continue;
 4040                    }
 4041
 4042                    let text = match indent.kind {
 4043                        IndentKind::Space => " ".repeat(indent.len as usize),
 4044                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4045                    };
 4046                    let point = Point::new(row.0, 0);
 4047                    indent_edits.push((point..point, text));
 4048                }
 4049            }
 4050            editor.edit(indent_edits, cx);
 4051        });
 4052    }
 4053
 4054    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4055        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4056            original_indent_columns: Vec::new(),
 4057        });
 4058        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4059    }
 4060
 4061    fn insert_with_autoindent_mode(
 4062        &mut self,
 4063        text: &str,
 4064        autoindent_mode: Option<AutoindentMode>,
 4065        window: &mut Window,
 4066        cx: &mut Context<Self>,
 4067    ) {
 4068        if self.read_only(cx) {
 4069            return;
 4070        }
 4071
 4072        let text: Arc<str> = text.into();
 4073        self.transact(window, cx, |this, window, cx| {
 4074            let old_selections = this.selections.all_adjusted(cx);
 4075            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4076                let anchors = {
 4077                    let snapshot = buffer.read(cx);
 4078                    old_selections
 4079                        .iter()
 4080                        .map(|s| {
 4081                            let anchor = snapshot.anchor_after(s.head());
 4082                            s.map(|_| anchor)
 4083                        })
 4084                        .collect::<Vec<_>>()
 4085                };
 4086                buffer.edit(
 4087                    old_selections
 4088                        .iter()
 4089                        .map(|s| (s.start..s.end, text.clone())),
 4090                    autoindent_mode,
 4091                    cx,
 4092                );
 4093                anchors
 4094            });
 4095
 4096            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4097                s.select_anchors(selection_anchors);
 4098            });
 4099
 4100            cx.notify();
 4101        });
 4102    }
 4103
 4104    fn trigger_completion_on_input(
 4105        &mut self,
 4106        text: &str,
 4107        trigger_in_words: bool,
 4108        window: &mut Window,
 4109        cx: &mut Context<Self>,
 4110    ) {
 4111        let ignore_completion_provider = self
 4112            .context_menu
 4113            .borrow()
 4114            .as_ref()
 4115            .map(|menu| match menu {
 4116                CodeContextMenu::Completions(completions_menu) => {
 4117                    completions_menu.ignore_completion_provider
 4118                }
 4119                CodeContextMenu::CodeActions(_) => false,
 4120            })
 4121            .unwrap_or(false);
 4122
 4123        if ignore_completion_provider {
 4124            self.show_word_completions(&ShowWordCompletions, window, cx);
 4125        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4126            self.show_completions(
 4127                &ShowCompletions {
 4128                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4129                },
 4130                window,
 4131                cx,
 4132            );
 4133        } else {
 4134            self.hide_context_menu(window, cx);
 4135        }
 4136    }
 4137
 4138    fn is_completion_trigger(
 4139        &self,
 4140        text: &str,
 4141        trigger_in_words: bool,
 4142        cx: &mut Context<Self>,
 4143    ) -> bool {
 4144        let position = self.selections.newest_anchor().head();
 4145        let multibuffer = self.buffer.read(cx);
 4146        let Some(buffer) = position
 4147            .buffer_id
 4148            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4149        else {
 4150            return false;
 4151        };
 4152
 4153        if let Some(completion_provider) = &self.completion_provider {
 4154            completion_provider.is_completion_trigger(
 4155                &buffer,
 4156                position.text_anchor,
 4157                text,
 4158                trigger_in_words,
 4159                cx,
 4160            )
 4161        } else {
 4162            false
 4163        }
 4164    }
 4165
 4166    /// If any empty selections is touching the start of its innermost containing autoclose
 4167    /// region, expand it to select the brackets.
 4168    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4169        let selections = self.selections.all::<usize>(cx);
 4170        let buffer = self.buffer.read(cx).read(cx);
 4171        let new_selections = self
 4172            .selections_with_autoclose_regions(selections, &buffer)
 4173            .map(|(mut selection, region)| {
 4174                if !selection.is_empty() {
 4175                    return selection;
 4176                }
 4177
 4178                if let Some(region) = region {
 4179                    let mut range = region.range.to_offset(&buffer);
 4180                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4181                        range.start -= region.pair.start.len();
 4182                        if buffer.contains_str_at(range.start, &region.pair.start)
 4183                            && buffer.contains_str_at(range.end, &region.pair.end)
 4184                        {
 4185                            range.end += region.pair.end.len();
 4186                            selection.start = range.start;
 4187                            selection.end = range.end;
 4188
 4189                            return selection;
 4190                        }
 4191                    }
 4192                }
 4193
 4194                let always_treat_brackets_as_autoclosed = buffer
 4195                    .language_settings_at(selection.start, cx)
 4196                    .always_treat_brackets_as_autoclosed;
 4197
 4198                if !always_treat_brackets_as_autoclosed {
 4199                    return selection;
 4200                }
 4201
 4202                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4203                    for (pair, enabled) in scope.brackets() {
 4204                        if !enabled || !pair.close {
 4205                            continue;
 4206                        }
 4207
 4208                        if buffer.contains_str_at(selection.start, &pair.end) {
 4209                            let pair_start_len = pair.start.len();
 4210                            if buffer.contains_str_at(
 4211                                selection.start.saturating_sub(pair_start_len),
 4212                                &pair.start,
 4213                            ) {
 4214                                selection.start -= pair_start_len;
 4215                                selection.end += pair.end.len();
 4216
 4217                                return selection;
 4218                            }
 4219                        }
 4220                    }
 4221                }
 4222
 4223                selection
 4224            })
 4225            .collect();
 4226
 4227        drop(buffer);
 4228        self.change_selections(None, window, cx, |selections| {
 4229            selections.select(new_selections)
 4230        });
 4231    }
 4232
 4233    /// Iterate the given selections, and for each one, find the smallest surrounding
 4234    /// autoclose region. This uses the ordering of the selections and the autoclose
 4235    /// regions to avoid repeated comparisons.
 4236    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4237        &'a self,
 4238        selections: impl IntoIterator<Item = Selection<D>>,
 4239        buffer: &'a MultiBufferSnapshot,
 4240    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4241        let mut i = 0;
 4242        let mut regions = self.autoclose_regions.as_slice();
 4243        selections.into_iter().map(move |selection| {
 4244            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4245
 4246            let mut enclosing = None;
 4247            while let Some(pair_state) = regions.get(i) {
 4248                if pair_state.range.end.to_offset(buffer) < range.start {
 4249                    regions = &regions[i + 1..];
 4250                    i = 0;
 4251                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4252                    break;
 4253                } else {
 4254                    if pair_state.selection_id == selection.id {
 4255                        enclosing = Some(pair_state);
 4256                    }
 4257                    i += 1;
 4258                }
 4259            }
 4260
 4261            (selection, enclosing)
 4262        })
 4263    }
 4264
 4265    /// Remove any autoclose regions that no longer contain their selection.
 4266    fn invalidate_autoclose_regions(
 4267        &mut self,
 4268        mut selections: &[Selection<Anchor>],
 4269        buffer: &MultiBufferSnapshot,
 4270    ) {
 4271        self.autoclose_regions.retain(|state| {
 4272            let mut i = 0;
 4273            while let Some(selection) = selections.get(i) {
 4274                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4275                    selections = &selections[1..];
 4276                    continue;
 4277                }
 4278                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4279                    break;
 4280                }
 4281                if selection.id == state.selection_id {
 4282                    return true;
 4283                } else {
 4284                    i += 1;
 4285                }
 4286            }
 4287            false
 4288        });
 4289    }
 4290
 4291    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4292        let offset = position.to_offset(buffer);
 4293        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4294        if offset > word_range.start && kind == Some(CharKind::Word) {
 4295            Some(
 4296                buffer
 4297                    .text_for_range(word_range.start..offset)
 4298                    .collect::<String>(),
 4299            )
 4300        } else {
 4301            None
 4302        }
 4303    }
 4304
 4305    pub fn toggle_inline_values(
 4306        &mut self,
 4307        _: &ToggleInlineValues,
 4308        _: &mut Window,
 4309        cx: &mut Context<Self>,
 4310    ) {
 4311        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4312
 4313        self.refresh_inline_values(cx);
 4314    }
 4315
 4316    pub fn toggle_inlay_hints(
 4317        &mut self,
 4318        _: &ToggleInlayHints,
 4319        _: &mut Window,
 4320        cx: &mut Context<Self>,
 4321    ) {
 4322        self.refresh_inlay_hints(
 4323            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4324            cx,
 4325        );
 4326    }
 4327
 4328    pub fn inlay_hints_enabled(&self) -> bool {
 4329        self.inlay_hint_cache.enabled
 4330    }
 4331
 4332    pub fn inline_values_enabled(&self) -> bool {
 4333        self.inline_value_cache.enabled
 4334    }
 4335
 4336    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4337        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4338            return;
 4339        }
 4340
 4341        let reason_description = reason.description();
 4342        let ignore_debounce = matches!(
 4343            reason,
 4344            InlayHintRefreshReason::SettingsChange(_)
 4345                | InlayHintRefreshReason::Toggle(_)
 4346                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4347                | InlayHintRefreshReason::ModifiersChanged(_)
 4348        );
 4349        let (invalidate_cache, required_languages) = match reason {
 4350            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4351                match self.inlay_hint_cache.modifiers_override(enabled) {
 4352                    Some(enabled) => {
 4353                        if enabled {
 4354                            (InvalidationStrategy::RefreshRequested, None)
 4355                        } else {
 4356                            self.splice_inlays(
 4357                                &self
 4358                                    .visible_inlay_hints(cx)
 4359                                    .iter()
 4360                                    .map(|inlay| inlay.id)
 4361                                    .collect::<Vec<InlayId>>(),
 4362                                Vec::new(),
 4363                                cx,
 4364                            );
 4365                            return;
 4366                        }
 4367                    }
 4368                    None => return,
 4369                }
 4370            }
 4371            InlayHintRefreshReason::Toggle(enabled) => {
 4372                if self.inlay_hint_cache.toggle(enabled) {
 4373                    if enabled {
 4374                        (InvalidationStrategy::RefreshRequested, None)
 4375                    } else {
 4376                        self.splice_inlays(
 4377                            &self
 4378                                .visible_inlay_hints(cx)
 4379                                .iter()
 4380                                .map(|inlay| inlay.id)
 4381                                .collect::<Vec<InlayId>>(),
 4382                            Vec::new(),
 4383                            cx,
 4384                        );
 4385                        return;
 4386                    }
 4387                } else {
 4388                    return;
 4389                }
 4390            }
 4391            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4392                match self.inlay_hint_cache.update_settings(
 4393                    &self.buffer,
 4394                    new_settings,
 4395                    self.visible_inlay_hints(cx),
 4396                    cx,
 4397                ) {
 4398                    ControlFlow::Break(Some(InlaySplice {
 4399                        to_remove,
 4400                        to_insert,
 4401                    })) => {
 4402                        self.splice_inlays(&to_remove, to_insert, cx);
 4403                        return;
 4404                    }
 4405                    ControlFlow::Break(None) => return,
 4406                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4407                }
 4408            }
 4409            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4410                if let Some(InlaySplice {
 4411                    to_remove,
 4412                    to_insert,
 4413                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4414                {
 4415                    self.splice_inlays(&to_remove, to_insert, cx);
 4416                }
 4417                self.display_map.update(cx, |display_map, _| {
 4418                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4419                });
 4420                return;
 4421            }
 4422            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4423            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4424                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4425            }
 4426            InlayHintRefreshReason::RefreshRequested => {
 4427                (InvalidationStrategy::RefreshRequested, None)
 4428            }
 4429        };
 4430
 4431        if let Some(InlaySplice {
 4432            to_remove,
 4433            to_insert,
 4434        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4435            reason_description,
 4436            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4437            invalidate_cache,
 4438            ignore_debounce,
 4439            cx,
 4440        ) {
 4441            self.splice_inlays(&to_remove, to_insert, cx);
 4442        }
 4443    }
 4444
 4445    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4446        self.display_map
 4447            .read(cx)
 4448            .current_inlays()
 4449            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4450            .cloned()
 4451            .collect()
 4452    }
 4453
 4454    pub fn excerpts_for_inlay_hints_query(
 4455        &self,
 4456        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4457        cx: &mut Context<Editor>,
 4458    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4459        let Some(project) = self.project.as_ref() else {
 4460            return HashMap::default();
 4461        };
 4462        let project = project.read(cx);
 4463        let multi_buffer = self.buffer().read(cx);
 4464        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4465        let multi_buffer_visible_start = self
 4466            .scroll_manager
 4467            .anchor()
 4468            .anchor
 4469            .to_point(&multi_buffer_snapshot);
 4470        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4471            multi_buffer_visible_start
 4472                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4473            Bias::Left,
 4474        );
 4475        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4476        multi_buffer_snapshot
 4477            .range_to_buffer_ranges(multi_buffer_visible_range)
 4478            .into_iter()
 4479            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4480            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4481                let buffer_file = project::File::from_dyn(buffer.file())?;
 4482                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4483                let worktree_entry = buffer_worktree
 4484                    .read(cx)
 4485                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4486                if worktree_entry.is_ignored {
 4487                    return None;
 4488                }
 4489
 4490                let language = buffer.language()?;
 4491                if let Some(restrict_to_languages) = restrict_to_languages {
 4492                    if !restrict_to_languages.contains(language) {
 4493                        return None;
 4494                    }
 4495                }
 4496                Some((
 4497                    excerpt_id,
 4498                    (
 4499                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4500                        buffer.version().clone(),
 4501                        excerpt_visible_range,
 4502                    ),
 4503                ))
 4504            })
 4505            .collect()
 4506    }
 4507
 4508    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4509        TextLayoutDetails {
 4510            text_system: window.text_system().clone(),
 4511            editor_style: self.style.clone().unwrap(),
 4512            rem_size: window.rem_size(),
 4513            scroll_anchor: self.scroll_manager.anchor(),
 4514            visible_rows: self.visible_line_count(),
 4515            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4516        }
 4517    }
 4518
 4519    pub fn splice_inlays(
 4520        &self,
 4521        to_remove: &[InlayId],
 4522        to_insert: Vec<Inlay>,
 4523        cx: &mut Context<Self>,
 4524    ) {
 4525        self.display_map.update(cx, |display_map, cx| {
 4526            display_map.splice_inlays(to_remove, to_insert, cx)
 4527        });
 4528        cx.notify();
 4529    }
 4530
 4531    fn trigger_on_type_formatting(
 4532        &self,
 4533        input: String,
 4534        window: &mut Window,
 4535        cx: &mut Context<Self>,
 4536    ) -> Option<Task<Result<()>>> {
 4537        if input.len() != 1 {
 4538            return None;
 4539        }
 4540
 4541        let project = self.project.as_ref()?;
 4542        let position = self.selections.newest_anchor().head();
 4543        let (buffer, buffer_position) = self
 4544            .buffer
 4545            .read(cx)
 4546            .text_anchor_for_position(position, cx)?;
 4547
 4548        let settings = language_settings::language_settings(
 4549            buffer
 4550                .read(cx)
 4551                .language_at(buffer_position)
 4552                .map(|l| l.name()),
 4553            buffer.read(cx).file(),
 4554            cx,
 4555        );
 4556        if !settings.use_on_type_format {
 4557            return None;
 4558        }
 4559
 4560        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4561        // hence we do LSP request & edit on host side only — add formats to host's history.
 4562        let push_to_lsp_host_history = true;
 4563        // If this is not the host, append its history with new edits.
 4564        let push_to_client_history = project.read(cx).is_via_collab();
 4565
 4566        let on_type_formatting = project.update(cx, |project, cx| {
 4567            project.on_type_format(
 4568                buffer.clone(),
 4569                buffer_position,
 4570                input,
 4571                push_to_lsp_host_history,
 4572                cx,
 4573            )
 4574        });
 4575        Some(cx.spawn_in(window, async move |editor, cx| {
 4576            if let Some(transaction) = on_type_formatting.await? {
 4577                if push_to_client_history {
 4578                    buffer
 4579                        .update(cx, |buffer, _| {
 4580                            buffer.push_transaction(transaction, Instant::now());
 4581                            buffer.finalize_last_transaction();
 4582                        })
 4583                        .ok();
 4584                }
 4585                editor.update(cx, |editor, cx| {
 4586                    editor.refresh_document_highlights(cx);
 4587                })?;
 4588            }
 4589            Ok(())
 4590        }))
 4591    }
 4592
 4593    pub fn show_word_completions(
 4594        &mut self,
 4595        _: &ShowWordCompletions,
 4596        window: &mut Window,
 4597        cx: &mut Context<Self>,
 4598    ) {
 4599        self.open_completions_menu(true, None, window, cx);
 4600    }
 4601
 4602    pub fn show_completions(
 4603        &mut self,
 4604        options: &ShowCompletions,
 4605        window: &mut Window,
 4606        cx: &mut Context<Self>,
 4607    ) {
 4608        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4609    }
 4610
 4611    fn open_completions_menu(
 4612        &mut self,
 4613        ignore_completion_provider: bool,
 4614        trigger: Option<&str>,
 4615        window: &mut Window,
 4616        cx: &mut Context<Self>,
 4617    ) {
 4618        if self.pending_rename.is_some() {
 4619            return;
 4620        }
 4621        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4622            return;
 4623        }
 4624
 4625        let position = self.selections.newest_anchor().head();
 4626        if position.diff_base_anchor.is_some() {
 4627            return;
 4628        }
 4629        let (buffer, buffer_position) =
 4630            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4631                output
 4632            } else {
 4633                return;
 4634            };
 4635        let buffer_snapshot = buffer.read(cx).snapshot();
 4636        let show_completion_documentation = buffer_snapshot
 4637            .settings_at(buffer_position, cx)
 4638            .show_completion_documentation;
 4639
 4640        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4641
 4642        let trigger_kind = match trigger {
 4643            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4644                CompletionTriggerKind::TRIGGER_CHARACTER
 4645            }
 4646            _ => CompletionTriggerKind::INVOKED,
 4647        };
 4648        let completion_context = CompletionContext {
 4649            trigger_character: trigger.and_then(|trigger| {
 4650                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4651                    Some(String::from(trigger))
 4652                } else {
 4653                    None
 4654                }
 4655            }),
 4656            trigger_kind,
 4657        };
 4658
 4659        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4660        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4661            let word_to_exclude = buffer_snapshot
 4662                .text_for_range(old_range.clone())
 4663                .collect::<String>();
 4664            (
 4665                buffer_snapshot.anchor_before(old_range.start)
 4666                    ..buffer_snapshot.anchor_after(old_range.end),
 4667                Some(word_to_exclude),
 4668            )
 4669        } else {
 4670            (buffer_position..buffer_position, None)
 4671        };
 4672
 4673        let completion_settings = language_settings(
 4674            buffer_snapshot
 4675                .language_at(buffer_position)
 4676                .map(|language| language.name()),
 4677            buffer_snapshot.file(),
 4678            cx,
 4679        )
 4680        .completions;
 4681
 4682        // The document can be large, so stay in reasonable bounds when searching for words,
 4683        // otherwise completion pop-up might be slow to appear.
 4684        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4685        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4686        let min_word_search = buffer_snapshot.clip_point(
 4687            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4688            Bias::Left,
 4689        );
 4690        let max_word_search = buffer_snapshot.clip_point(
 4691            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4692            Bias::Right,
 4693        );
 4694        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4695            ..buffer_snapshot.point_to_offset(max_word_search);
 4696
 4697        let provider = self
 4698            .completion_provider
 4699            .as_ref()
 4700            .filter(|_| !ignore_completion_provider);
 4701        let skip_digits = query
 4702            .as_ref()
 4703            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4704
 4705        let (mut words, provided_completions) = match provider {
 4706            Some(provider) => {
 4707                let completions = provider.completions(
 4708                    position.excerpt_id,
 4709                    &buffer,
 4710                    buffer_position,
 4711                    completion_context,
 4712                    window,
 4713                    cx,
 4714                );
 4715
 4716                let words = match completion_settings.words {
 4717                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4718                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4719                        .background_spawn(async move {
 4720                            buffer_snapshot.words_in_range(WordsQuery {
 4721                                fuzzy_contents: None,
 4722                                range: word_search_range,
 4723                                skip_digits,
 4724                            })
 4725                        }),
 4726                };
 4727
 4728                (words, completions)
 4729            }
 4730            None => (
 4731                cx.background_spawn(async move {
 4732                    buffer_snapshot.words_in_range(WordsQuery {
 4733                        fuzzy_contents: None,
 4734                        range: word_search_range,
 4735                        skip_digits,
 4736                    })
 4737                }),
 4738                Task::ready(Ok(None)),
 4739            ),
 4740        };
 4741
 4742        let sort_completions = provider
 4743            .as_ref()
 4744            .map_or(false, |provider| provider.sort_completions());
 4745
 4746        let filter_completions = provider
 4747            .as_ref()
 4748            .map_or(true, |provider| provider.filter_completions());
 4749
 4750        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4751
 4752        let id = post_inc(&mut self.next_completion_id);
 4753        let task = cx.spawn_in(window, async move |editor, cx| {
 4754            async move {
 4755                editor.update(cx, |this, _| {
 4756                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4757                })?;
 4758
 4759                let mut completions = Vec::new();
 4760                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4761                    completions.extend(provided_completions);
 4762                    if completion_settings.words == WordsCompletionMode::Fallback {
 4763                        words = Task::ready(BTreeMap::default());
 4764                    }
 4765                }
 4766
 4767                let mut words = words.await;
 4768                if let Some(word_to_exclude) = &word_to_exclude {
 4769                    words.remove(word_to_exclude);
 4770                }
 4771                for lsp_completion in &completions {
 4772                    words.remove(&lsp_completion.new_text);
 4773                }
 4774                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4775                    replace_range: old_range.clone(),
 4776                    new_text: word.clone(),
 4777                    label: CodeLabel::plain(word, None),
 4778                    icon_path: None,
 4779                    documentation: None,
 4780                    source: CompletionSource::BufferWord {
 4781                        word_range,
 4782                        resolved: false,
 4783                    },
 4784                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4785                    confirm: None,
 4786                }));
 4787
 4788                let menu = if completions.is_empty() {
 4789                    None
 4790                } else {
 4791                    let mut menu = CompletionsMenu::new(
 4792                        id,
 4793                        sort_completions,
 4794                        show_completion_documentation,
 4795                        ignore_completion_provider,
 4796                        position,
 4797                        buffer.clone(),
 4798                        completions.into(),
 4799                        snippet_sort_order,
 4800                    );
 4801
 4802                    menu.filter(
 4803                        if filter_completions {
 4804                            query.as_deref()
 4805                        } else {
 4806                            None
 4807                        },
 4808                        cx.background_executor().clone(),
 4809                    )
 4810                    .await;
 4811
 4812                    menu.visible().then_some(menu)
 4813                };
 4814
 4815                editor.update_in(cx, |editor, window, cx| {
 4816                    match editor.context_menu.borrow().as_ref() {
 4817                        None => {}
 4818                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4819                            if prev_menu.id > id {
 4820                                return;
 4821                            }
 4822                        }
 4823                        _ => return,
 4824                    }
 4825
 4826                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4827                        let mut menu = menu.unwrap();
 4828                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4829
 4830                        *editor.context_menu.borrow_mut() =
 4831                            Some(CodeContextMenu::Completions(menu));
 4832
 4833                        if editor.show_edit_predictions_in_menu() {
 4834                            editor.update_visible_inline_completion(window, cx);
 4835                        } else {
 4836                            editor.discard_inline_completion(false, cx);
 4837                        }
 4838
 4839                        cx.notify();
 4840                    } else if editor.completion_tasks.len() <= 1 {
 4841                        // If there are no more completion tasks and the last menu was
 4842                        // empty, we should hide it.
 4843                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4844                        // If it was already hidden and we don't show inline
 4845                        // completions in the menu, we should also show the
 4846                        // inline-completion when available.
 4847                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4848                            editor.update_visible_inline_completion(window, cx);
 4849                        }
 4850                    }
 4851                })?;
 4852
 4853                anyhow::Ok(())
 4854            }
 4855            .log_err()
 4856            .await
 4857        });
 4858
 4859        self.completion_tasks.push((id, task));
 4860    }
 4861
 4862    #[cfg(feature = "test-support")]
 4863    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4864        let menu = self.context_menu.borrow();
 4865        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4866            let completions = menu.completions.borrow();
 4867            Some(completions.to_vec())
 4868        } else {
 4869            None
 4870        }
 4871    }
 4872
 4873    pub fn confirm_completion(
 4874        &mut self,
 4875        action: &ConfirmCompletion,
 4876        window: &mut Window,
 4877        cx: &mut Context<Self>,
 4878    ) -> Option<Task<Result<()>>> {
 4879        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4880        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4881    }
 4882
 4883    pub fn confirm_completion_insert(
 4884        &mut self,
 4885        _: &ConfirmCompletionInsert,
 4886        window: &mut Window,
 4887        cx: &mut Context<Self>,
 4888    ) -> Option<Task<Result<()>>> {
 4889        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4890        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4891    }
 4892
 4893    pub fn confirm_completion_replace(
 4894        &mut self,
 4895        _: &ConfirmCompletionReplace,
 4896        window: &mut Window,
 4897        cx: &mut Context<Self>,
 4898    ) -> Option<Task<Result<()>>> {
 4899        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4900        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4901    }
 4902
 4903    pub fn compose_completion(
 4904        &mut self,
 4905        action: &ComposeCompletion,
 4906        window: &mut Window,
 4907        cx: &mut Context<Self>,
 4908    ) -> Option<Task<Result<()>>> {
 4909        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4910        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4911    }
 4912
 4913    fn do_completion(
 4914        &mut self,
 4915        item_ix: Option<usize>,
 4916        intent: CompletionIntent,
 4917        window: &mut Window,
 4918        cx: &mut Context<Editor>,
 4919    ) -> Option<Task<Result<()>>> {
 4920        use language::ToOffset as _;
 4921
 4922        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4923        else {
 4924            return None;
 4925        };
 4926
 4927        let candidate_id = {
 4928            let entries = completions_menu.entries.borrow();
 4929            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4930            if self.show_edit_predictions_in_menu() {
 4931                self.discard_inline_completion(true, cx);
 4932            }
 4933            mat.candidate_id
 4934        };
 4935
 4936        let buffer_handle = completions_menu.buffer;
 4937        let completion = completions_menu
 4938            .completions
 4939            .borrow()
 4940            .get(candidate_id)?
 4941            .clone();
 4942        cx.stop_propagation();
 4943
 4944        let snippet;
 4945        let new_text;
 4946        if completion.is_snippet() {
 4947            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4948            new_text = snippet.as_ref().unwrap().text.clone();
 4949        } else {
 4950            snippet = None;
 4951            new_text = completion.new_text.clone();
 4952        };
 4953
 4954        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4955        let buffer = buffer_handle.read(cx);
 4956        let snapshot = self.buffer.read(cx).snapshot(cx);
 4957        let replace_range_multibuffer = {
 4958            let excerpt = snapshot
 4959                .excerpt_containing(self.selections.newest_anchor().range())
 4960                .unwrap();
 4961            let multibuffer_anchor = snapshot
 4962                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4963                .unwrap()
 4964                ..snapshot
 4965                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4966                    .unwrap();
 4967            multibuffer_anchor.start.to_offset(&snapshot)
 4968                ..multibuffer_anchor.end.to_offset(&snapshot)
 4969        };
 4970        let newest_anchor = self.selections.newest_anchor();
 4971        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4972            return None;
 4973        }
 4974
 4975        let old_text = buffer
 4976            .text_for_range(replace_range.clone())
 4977            .collect::<String>();
 4978        let lookbehind = newest_anchor
 4979            .start
 4980            .text_anchor
 4981            .to_offset(buffer)
 4982            .saturating_sub(replace_range.start);
 4983        let lookahead = replace_range
 4984            .end
 4985            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4986        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4987        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4988
 4989        let selections = self.selections.all::<usize>(cx);
 4990        let mut ranges = Vec::new();
 4991        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4992
 4993        for selection in &selections {
 4994            let range = if selection.id == newest_anchor.id {
 4995                replace_range_multibuffer.clone()
 4996            } else {
 4997                let mut range = selection.range();
 4998
 4999                // if prefix is present, don't duplicate it
 5000                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5001                    range.start = range.start.saturating_sub(lookbehind);
 5002
 5003                    // if suffix is also present, mimic the newest cursor and replace it
 5004                    if selection.id != newest_anchor.id
 5005                        && snapshot.contains_str_at(range.end, suffix)
 5006                    {
 5007                        range.end += lookahead;
 5008                    }
 5009                }
 5010                range
 5011            };
 5012
 5013            ranges.push(range.clone());
 5014
 5015            if !self.linked_edit_ranges.is_empty() {
 5016                let start_anchor = snapshot.anchor_before(range.start);
 5017                let end_anchor = snapshot.anchor_after(range.end);
 5018                if let Some(ranges) = self
 5019                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5020                {
 5021                    for (buffer, edits) in ranges {
 5022                        linked_edits
 5023                            .entry(buffer.clone())
 5024                            .or_default()
 5025                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5026                    }
 5027                }
 5028            }
 5029        }
 5030
 5031        cx.emit(EditorEvent::InputHandled {
 5032            utf16_range_to_replace: None,
 5033            text: new_text.clone().into(),
 5034        });
 5035
 5036        self.transact(window, cx, |this, window, cx| {
 5037            if let Some(mut snippet) = snippet {
 5038                snippet.text = new_text.to_string();
 5039                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5040            } else {
 5041                this.buffer.update(cx, |buffer, cx| {
 5042                    let auto_indent = match completion.insert_text_mode {
 5043                        Some(InsertTextMode::AS_IS) => None,
 5044                        _ => this.autoindent_mode.clone(),
 5045                    };
 5046                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5047                    buffer.edit(edits, auto_indent, cx);
 5048                });
 5049            }
 5050            for (buffer, edits) in linked_edits {
 5051                buffer.update(cx, |buffer, cx| {
 5052                    let snapshot = buffer.snapshot();
 5053                    let edits = edits
 5054                        .into_iter()
 5055                        .map(|(range, text)| {
 5056                            use text::ToPoint as TP;
 5057                            let end_point = TP::to_point(&range.end, &snapshot);
 5058                            let start_point = TP::to_point(&range.start, &snapshot);
 5059                            (start_point..end_point, text)
 5060                        })
 5061                        .sorted_by_key(|(range, _)| range.start);
 5062                    buffer.edit(edits, None, cx);
 5063                })
 5064            }
 5065
 5066            this.refresh_inline_completion(true, false, window, cx);
 5067        });
 5068
 5069        let show_new_completions_on_confirm = completion
 5070            .confirm
 5071            .as_ref()
 5072            .map_or(false, |confirm| confirm(intent, window, cx));
 5073        if show_new_completions_on_confirm {
 5074            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5075        }
 5076
 5077        let provider = self.completion_provider.as_ref()?;
 5078        drop(completion);
 5079        let apply_edits = provider.apply_additional_edits_for_completion(
 5080            buffer_handle,
 5081            completions_menu.completions.clone(),
 5082            candidate_id,
 5083            true,
 5084            cx,
 5085        );
 5086
 5087        let editor_settings = EditorSettings::get_global(cx);
 5088        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5089            // After the code completion is finished, users often want to know what signatures are needed.
 5090            // so we should automatically call signature_help
 5091            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5092        }
 5093
 5094        Some(cx.foreground_executor().spawn(async move {
 5095            apply_edits.await?;
 5096            Ok(())
 5097        }))
 5098    }
 5099
 5100    pub fn toggle_code_actions(
 5101        &mut self,
 5102        action: &ToggleCodeActions,
 5103        window: &mut Window,
 5104        cx: &mut Context<Self>,
 5105    ) {
 5106        let quick_launch = action.quick_launch;
 5107        let mut context_menu = self.context_menu.borrow_mut();
 5108        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5109            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5110                // Toggle if we're selecting the same one
 5111                *context_menu = None;
 5112                cx.notify();
 5113                return;
 5114            } else {
 5115                // Otherwise, clear it and start a new one
 5116                *context_menu = None;
 5117                cx.notify();
 5118            }
 5119        }
 5120        drop(context_menu);
 5121        let snapshot = self.snapshot(window, cx);
 5122        let deployed_from_indicator = action.deployed_from_indicator;
 5123        let mut task = self.code_actions_task.take();
 5124        let action = action.clone();
 5125        cx.spawn_in(window, async move |editor, cx| {
 5126            while let Some(prev_task) = task {
 5127                prev_task.await.log_err();
 5128                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5129            }
 5130
 5131            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5132                if editor.focus_handle.is_focused(window) {
 5133                    let multibuffer_point = action
 5134                        .deployed_from_indicator
 5135                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5136                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5137                    let (buffer, buffer_row) = snapshot
 5138                        .buffer_snapshot
 5139                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5140                        .and_then(|(buffer_snapshot, range)| {
 5141                            editor
 5142                                .buffer
 5143                                .read(cx)
 5144                                .buffer(buffer_snapshot.remote_id())
 5145                                .map(|buffer| (buffer, range.start.row))
 5146                        })?;
 5147                    let (_, code_actions) = editor
 5148                        .available_code_actions
 5149                        .clone()
 5150                        .and_then(|(location, code_actions)| {
 5151                            let snapshot = location.buffer.read(cx).snapshot();
 5152                            let point_range = location.range.to_point(&snapshot);
 5153                            let point_range = point_range.start.row..=point_range.end.row;
 5154                            if point_range.contains(&buffer_row) {
 5155                                Some((location, code_actions))
 5156                            } else {
 5157                                None
 5158                            }
 5159                        })
 5160                        .unzip();
 5161                    let buffer_id = buffer.read(cx).remote_id();
 5162                    let tasks = editor
 5163                        .tasks
 5164                        .get(&(buffer_id, buffer_row))
 5165                        .map(|t| Arc::new(t.to_owned()));
 5166                    if tasks.is_none() && code_actions.is_none() {
 5167                        return None;
 5168                    }
 5169
 5170                    editor.completion_tasks.clear();
 5171                    editor.discard_inline_completion(false, cx);
 5172                    let task_context =
 5173                        tasks
 5174                            .as_ref()
 5175                            .zip(editor.project.clone())
 5176                            .map(|(tasks, project)| {
 5177                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5178                            });
 5179
 5180                    Some(cx.spawn_in(window, async move |editor, cx| {
 5181                        let task_context = match task_context {
 5182                            Some(task_context) => task_context.await,
 5183                            None => None,
 5184                        };
 5185                        let resolved_tasks =
 5186                            tasks
 5187                                .zip(task_context.clone())
 5188                                .map(|(tasks, task_context)| ResolvedTasks {
 5189                                    templates: tasks.resolve(&task_context).collect(),
 5190                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5191                                        multibuffer_point.row,
 5192                                        tasks.column,
 5193                                    )),
 5194                                });
 5195                        let spawn_straight_away = quick_launch
 5196                            && resolved_tasks
 5197                                .as_ref()
 5198                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5199                            && code_actions
 5200                                .as_ref()
 5201                                .map_or(true, |actions| actions.is_empty());
 5202                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5203                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5204                                maybe!({
 5205                                    let project = editor.project.as_ref()?;
 5206                                    let dap_store = project.read(cx).dap_store();
 5207                                    let mut scenarios = vec![];
 5208                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5209                                    let debug_adapter: SharedString = buffer
 5210                                        .read(cx)
 5211                                        .language()?
 5212                                        .context_provider()?
 5213                                        .debug_adapter()?
 5214                                        .into();
 5215                                    dap_store.update(cx, |this, cx| {
 5216                                        for (_, task) in &resolved_tasks.templates {
 5217                                            if let Some(scenario) = this
 5218                                                .debug_scenario_for_build_task(
 5219                                                    task.original_task().clone(),
 5220                                                    debug_adapter.clone(),
 5221                                                    cx,
 5222                                                )
 5223                                            {
 5224                                                scenarios.push(scenario);
 5225                                            }
 5226                                        }
 5227                                    });
 5228                                    Some(scenarios)
 5229                                })
 5230                                .unwrap_or_default()
 5231                            } else {
 5232                                vec![]
 5233                            }
 5234                        })?;
 5235                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5236                            *editor.context_menu.borrow_mut() =
 5237                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5238                                    buffer,
 5239                                    actions: CodeActionContents::new(
 5240                                        resolved_tasks,
 5241                                        code_actions,
 5242                                        debug_scenarios,
 5243                                        task_context.unwrap_or_default(),
 5244                                    ),
 5245                                    selected_item: Default::default(),
 5246                                    scroll_handle: UniformListScrollHandle::default(),
 5247                                    deployed_from_indicator,
 5248                                }));
 5249                            if spawn_straight_away {
 5250                                if let Some(task) = editor.confirm_code_action(
 5251                                    &ConfirmCodeAction { item_ix: Some(0) },
 5252                                    window,
 5253                                    cx,
 5254                                ) {
 5255                                    cx.notify();
 5256                                    return task;
 5257                                }
 5258                            }
 5259                            cx.notify();
 5260                            Task::ready(Ok(()))
 5261                        }) {
 5262                            task.await
 5263                        } else {
 5264                            Ok(())
 5265                        }
 5266                    }))
 5267                } else {
 5268                    Some(Task::ready(Ok(())))
 5269                }
 5270            })?;
 5271            if let Some(task) = spawned_test_task {
 5272                task.await?;
 5273            }
 5274
 5275            Ok::<_, anyhow::Error>(())
 5276        })
 5277        .detach_and_log_err(cx);
 5278    }
 5279
 5280    pub fn confirm_code_action(
 5281        &mut self,
 5282        action: &ConfirmCodeAction,
 5283        window: &mut Window,
 5284        cx: &mut Context<Self>,
 5285    ) -> Option<Task<Result<()>>> {
 5286        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5287
 5288        let actions_menu =
 5289            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5290                menu
 5291            } else {
 5292                return None;
 5293            };
 5294
 5295        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5296        let action = actions_menu.actions.get(action_ix)?;
 5297        let title = action.label();
 5298        let buffer = actions_menu.buffer;
 5299        let workspace = self.workspace()?;
 5300
 5301        match action {
 5302            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5303                workspace.update(cx, |workspace, cx| {
 5304                    workspace.schedule_resolved_task(
 5305                        task_source_kind,
 5306                        resolved_task,
 5307                        false,
 5308                        window,
 5309                        cx,
 5310                    );
 5311
 5312                    Some(Task::ready(Ok(())))
 5313                })
 5314            }
 5315            CodeActionsItem::CodeAction {
 5316                excerpt_id,
 5317                action,
 5318                provider,
 5319            } => {
 5320                let apply_code_action =
 5321                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5322                let workspace = workspace.downgrade();
 5323                Some(cx.spawn_in(window, async move |editor, cx| {
 5324                    let project_transaction = apply_code_action.await?;
 5325                    Self::open_project_transaction(
 5326                        &editor,
 5327                        workspace,
 5328                        project_transaction,
 5329                        title,
 5330                        cx,
 5331                    )
 5332                    .await
 5333                }))
 5334            }
 5335            CodeActionsItem::DebugScenario(scenario) => {
 5336                let context = actions_menu.actions.context.clone();
 5337
 5338                workspace.update(cx, |workspace, cx| {
 5339                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5340                });
 5341                Some(Task::ready(Ok(())))
 5342            }
 5343        }
 5344    }
 5345
 5346    pub async fn open_project_transaction(
 5347        this: &WeakEntity<Editor>,
 5348        workspace: WeakEntity<Workspace>,
 5349        transaction: ProjectTransaction,
 5350        title: String,
 5351        cx: &mut AsyncWindowContext,
 5352    ) -> Result<()> {
 5353        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5354        cx.update(|_, cx| {
 5355            entries.sort_unstable_by_key(|(buffer, _)| {
 5356                buffer.read(cx).file().map(|f| f.path().clone())
 5357            });
 5358        })?;
 5359
 5360        // If the project transaction's edits are all contained within this editor, then
 5361        // avoid opening a new editor to display them.
 5362
 5363        if let Some((buffer, transaction)) = entries.first() {
 5364            if entries.len() == 1 {
 5365                let excerpt = this.update(cx, |editor, cx| {
 5366                    editor
 5367                        .buffer()
 5368                        .read(cx)
 5369                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5370                })?;
 5371                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5372                    if excerpted_buffer == *buffer {
 5373                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5374                            let excerpt_range = excerpt_range.to_offset(buffer);
 5375                            buffer
 5376                                .edited_ranges_for_transaction::<usize>(transaction)
 5377                                .all(|range| {
 5378                                    excerpt_range.start <= range.start
 5379                                        && excerpt_range.end >= range.end
 5380                                })
 5381                        })?;
 5382
 5383                        if all_edits_within_excerpt {
 5384                            return Ok(());
 5385                        }
 5386                    }
 5387                }
 5388            }
 5389        } else {
 5390            return Ok(());
 5391        }
 5392
 5393        let mut ranges_to_highlight = Vec::new();
 5394        let excerpt_buffer = cx.new(|cx| {
 5395            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5396            for (buffer_handle, transaction) in &entries {
 5397                let edited_ranges = buffer_handle
 5398                    .read(cx)
 5399                    .edited_ranges_for_transaction::<Point>(transaction)
 5400                    .collect::<Vec<_>>();
 5401                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5402                    PathKey::for_buffer(buffer_handle, cx),
 5403                    buffer_handle.clone(),
 5404                    edited_ranges,
 5405                    DEFAULT_MULTIBUFFER_CONTEXT,
 5406                    cx,
 5407                );
 5408
 5409                ranges_to_highlight.extend(ranges);
 5410            }
 5411            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5412            multibuffer
 5413        })?;
 5414
 5415        workspace.update_in(cx, |workspace, window, cx| {
 5416            let project = workspace.project().clone();
 5417            let editor =
 5418                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5419            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5420            editor.update(cx, |editor, cx| {
 5421                editor.highlight_background::<Self>(
 5422                    &ranges_to_highlight,
 5423                    |theme| theme.editor_highlighted_line_background,
 5424                    cx,
 5425                );
 5426            });
 5427        })?;
 5428
 5429        Ok(())
 5430    }
 5431
 5432    pub fn clear_code_action_providers(&mut self) {
 5433        self.code_action_providers.clear();
 5434        self.available_code_actions.take();
 5435    }
 5436
 5437    pub fn add_code_action_provider(
 5438        &mut self,
 5439        provider: Rc<dyn CodeActionProvider>,
 5440        window: &mut Window,
 5441        cx: &mut Context<Self>,
 5442    ) {
 5443        if self
 5444            .code_action_providers
 5445            .iter()
 5446            .any(|existing_provider| existing_provider.id() == provider.id())
 5447        {
 5448            return;
 5449        }
 5450
 5451        self.code_action_providers.push(provider);
 5452        self.refresh_code_actions(window, cx);
 5453    }
 5454
 5455    pub fn remove_code_action_provider(
 5456        &mut self,
 5457        id: Arc<str>,
 5458        window: &mut Window,
 5459        cx: &mut Context<Self>,
 5460    ) {
 5461        self.code_action_providers
 5462            .retain(|provider| provider.id() != id);
 5463        self.refresh_code_actions(window, cx);
 5464    }
 5465
 5466    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5467        let newest_selection = self.selections.newest_anchor().clone();
 5468        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5469        let buffer = self.buffer.read(cx);
 5470        if newest_selection.head().diff_base_anchor.is_some() {
 5471            return None;
 5472        }
 5473        let (start_buffer, start) =
 5474            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5475        let (end_buffer, end) =
 5476            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5477        if start_buffer != end_buffer {
 5478            return None;
 5479        }
 5480
 5481        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5482            cx.background_executor()
 5483                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5484                .await;
 5485
 5486            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5487                let providers = this.code_action_providers.clone();
 5488                let tasks = this
 5489                    .code_action_providers
 5490                    .iter()
 5491                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5492                    .collect::<Vec<_>>();
 5493                (providers, tasks)
 5494            })?;
 5495
 5496            let mut actions = Vec::new();
 5497            for (provider, provider_actions) in
 5498                providers.into_iter().zip(future::join_all(tasks).await)
 5499            {
 5500                if let Some(provider_actions) = provider_actions.log_err() {
 5501                    actions.extend(provider_actions.into_iter().map(|action| {
 5502                        AvailableCodeAction {
 5503                            excerpt_id: newest_selection.start.excerpt_id,
 5504                            action,
 5505                            provider: provider.clone(),
 5506                        }
 5507                    }));
 5508                }
 5509            }
 5510
 5511            this.update(cx, |this, cx| {
 5512                this.available_code_actions = if actions.is_empty() {
 5513                    None
 5514                } else {
 5515                    Some((
 5516                        Location {
 5517                            buffer: start_buffer,
 5518                            range: start..end,
 5519                        },
 5520                        actions.into(),
 5521                    ))
 5522                };
 5523                cx.notify();
 5524            })
 5525        }));
 5526        None
 5527    }
 5528
 5529    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5530        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5531            self.show_git_blame_inline = false;
 5532
 5533            self.show_git_blame_inline_delay_task =
 5534                Some(cx.spawn_in(window, async move |this, cx| {
 5535                    cx.background_executor().timer(delay).await;
 5536
 5537                    this.update(cx, |this, cx| {
 5538                        this.show_git_blame_inline = true;
 5539                        cx.notify();
 5540                    })
 5541                    .log_err();
 5542                }));
 5543        }
 5544    }
 5545
 5546    fn show_blame_popover(
 5547        &mut self,
 5548        blame_entry: &BlameEntry,
 5549        position: gpui::Point<Pixels>,
 5550        cx: &mut Context<Self>,
 5551    ) {
 5552        if let Some(state) = &mut self.inline_blame_popover {
 5553            state.hide_task.take();
 5554            cx.notify();
 5555        } else {
 5556            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5557            let show_task = cx.spawn(async move |editor, cx| {
 5558                cx.background_executor()
 5559                    .timer(std::time::Duration::from_millis(delay))
 5560                    .await;
 5561                editor
 5562                    .update(cx, |editor, cx| {
 5563                        if let Some(state) = &mut editor.inline_blame_popover {
 5564                            state.show_task = None;
 5565                            cx.notify();
 5566                        }
 5567                    })
 5568                    .ok();
 5569            });
 5570            let Some(blame) = self.blame.as_ref() else {
 5571                return;
 5572            };
 5573            let blame = blame.read(cx);
 5574            let details = blame.details_for_entry(&blame_entry);
 5575            let markdown = cx.new(|cx| {
 5576                Markdown::new(
 5577                    details
 5578                        .as_ref()
 5579                        .map(|message| message.message.clone())
 5580                        .unwrap_or_default(),
 5581                    None,
 5582                    None,
 5583                    cx,
 5584                )
 5585            });
 5586            self.inline_blame_popover = Some(InlineBlamePopover {
 5587                position,
 5588                show_task: Some(show_task),
 5589                hide_task: None,
 5590                popover_bounds: None,
 5591                popover_state: InlineBlamePopoverState {
 5592                    scroll_handle: ScrollHandle::new(),
 5593                    commit_message: details,
 5594                    markdown,
 5595                },
 5596            });
 5597        }
 5598    }
 5599
 5600    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5601        if let Some(state) = &mut self.inline_blame_popover {
 5602            if state.show_task.is_some() {
 5603                self.inline_blame_popover.take();
 5604                cx.notify();
 5605            } else {
 5606                let hide_task = cx.spawn(async move |editor, cx| {
 5607                    cx.background_executor()
 5608                        .timer(std::time::Duration::from_millis(100))
 5609                        .await;
 5610                    editor
 5611                        .update(cx, |editor, cx| {
 5612                            editor.inline_blame_popover.take();
 5613                            cx.notify();
 5614                        })
 5615                        .ok();
 5616                });
 5617                state.hide_task = Some(hide_task);
 5618            }
 5619        }
 5620    }
 5621
 5622    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5623        if self.pending_rename.is_some() {
 5624            return None;
 5625        }
 5626
 5627        let provider = self.semantics_provider.clone()?;
 5628        let buffer = self.buffer.read(cx);
 5629        let newest_selection = self.selections.newest_anchor().clone();
 5630        let cursor_position = newest_selection.head();
 5631        let (cursor_buffer, cursor_buffer_position) =
 5632            buffer.text_anchor_for_position(cursor_position, cx)?;
 5633        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5634        if cursor_buffer != tail_buffer {
 5635            return None;
 5636        }
 5637        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5638        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5639            cx.background_executor()
 5640                .timer(Duration::from_millis(debounce))
 5641                .await;
 5642
 5643            let highlights = if let Some(highlights) = cx
 5644                .update(|cx| {
 5645                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5646                })
 5647                .ok()
 5648                .flatten()
 5649            {
 5650                highlights.await.log_err()
 5651            } else {
 5652                None
 5653            };
 5654
 5655            if let Some(highlights) = highlights {
 5656                this.update(cx, |this, cx| {
 5657                    if this.pending_rename.is_some() {
 5658                        return;
 5659                    }
 5660
 5661                    let buffer_id = cursor_position.buffer_id;
 5662                    let buffer = this.buffer.read(cx);
 5663                    if !buffer
 5664                        .text_anchor_for_position(cursor_position, cx)
 5665                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5666                    {
 5667                        return;
 5668                    }
 5669
 5670                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5671                    let mut write_ranges = Vec::new();
 5672                    let mut read_ranges = Vec::new();
 5673                    for highlight in highlights {
 5674                        for (excerpt_id, excerpt_range) in
 5675                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5676                        {
 5677                            let start = highlight
 5678                                .range
 5679                                .start
 5680                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5681                            let end = highlight
 5682                                .range
 5683                                .end
 5684                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5685                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5686                                continue;
 5687                            }
 5688
 5689                            let range = Anchor {
 5690                                buffer_id,
 5691                                excerpt_id,
 5692                                text_anchor: start,
 5693                                diff_base_anchor: None,
 5694                            }..Anchor {
 5695                                buffer_id,
 5696                                excerpt_id,
 5697                                text_anchor: end,
 5698                                diff_base_anchor: None,
 5699                            };
 5700                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5701                                write_ranges.push(range);
 5702                            } else {
 5703                                read_ranges.push(range);
 5704                            }
 5705                        }
 5706                    }
 5707
 5708                    this.highlight_background::<DocumentHighlightRead>(
 5709                        &read_ranges,
 5710                        |theme| theme.editor_document_highlight_read_background,
 5711                        cx,
 5712                    );
 5713                    this.highlight_background::<DocumentHighlightWrite>(
 5714                        &write_ranges,
 5715                        |theme| theme.editor_document_highlight_write_background,
 5716                        cx,
 5717                    );
 5718                    cx.notify();
 5719                })
 5720                .log_err();
 5721            }
 5722        }));
 5723        None
 5724    }
 5725
 5726    fn prepare_highlight_query_from_selection(
 5727        &mut self,
 5728        cx: &mut Context<Editor>,
 5729    ) -> Option<(String, Range<Anchor>)> {
 5730        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5731            return None;
 5732        }
 5733        if !EditorSettings::get_global(cx).selection_highlight {
 5734            return None;
 5735        }
 5736        if self.selections.count() != 1 || self.selections.line_mode {
 5737            return None;
 5738        }
 5739        let selection = self.selections.newest::<Point>(cx);
 5740        if selection.is_empty() || selection.start.row != selection.end.row {
 5741            return None;
 5742        }
 5743        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5744        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5745        let query = multi_buffer_snapshot
 5746            .text_for_range(selection_anchor_range.clone())
 5747            .collect::<String>();
 5748        if query.trim().is_empty() {
 5749            return None;
 5750        }
 5751        Some((query, selection_anchor_range))
 5752    }
 5753
 5754    fn update_selection_occurrence_highlights(
 5755        &mut self,
 5756        query_text: String,
 5757        query_range: Range<Anchor>,
 5758        multi_buffer_range_to_query: Range<Point>,
 5759        use_debounce: bool,
 5760        window: &mut Window,
 5761        cx: &mut Context<Editor>,
 5762    ) -> Task<()> {
 5763        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5764        cx.spawn_in(window, async move |editor, cx| {
 5765            if use_debounce {
 5766                cx.background_executor()
 5767                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5768                    .await;
 5769            }
 5770            let match_task = cx.background_spawn(async move {
 5771                let buffer_ranges = multi_buffer_snapshot
 5772                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5773                    .into_iter()
 5774                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5775                let mut match_ranges = Vec::new();
 5776                let Ok(regex) = project::search::SearchQuery::text(
 5777                    query_text.clone(),
 5778                    false,
 5779                    false,
 5780                    false,
 5781                    Default::default(),
 5782                    Default::default(),
 5783                    false,
 5784                    None,
 5785                ) else {
 5786                    return Vec::default();
 5787                };
 5788                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5789                    match_ranges.extend(
 5790                        regex
 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 = buffer_snapshot
 5798                                    .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    fn select_match_ranges(
12131        &mut self,
12132        range: Range<usize>,
12133        reversed: bool,
12134        replace_newest: bool,
12135        auto_scroll: Option<Autoscroll>,
12136        window: &mut Window,
12137        cx: &mut Context<Editor>,
12138    ) {
12139        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12140        self.change_selections(auto_scroll, window, cx, |s| {
12141            if replace_newest {
12142                s.delete(s.newest_anchor().id);
12143            }
12144            if reversed {
12145                s.insert_range(range.end..range.start);
12146            } else {
12147                s.insert_range(range);
12148            }
12149        });
12150    }
12151
12152    pub fn select_next_match_internal(
12153        &mut self,
12154        display_map: &DisplaySnapshot,
12155        replace_newest: bool,
12156        autoscroll: Option<Autoscroll>,
12157        window: &mut Window,
12158        cx: &mut Context<Self>,
12159    ) -> Result<()> {
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                    self.select_match_ranges(
12205                        next_selected_range,
12206                        last_selection.reversed,
12207                        replace_newest,
12208                        autoscroll,
12209                        window,
12210                        cx,
12211                    );
12212                } else {
12213                    select_next_state.done = true;
12214                }
12215            }
12216
12217            self.select_next_state = Some(select_next_state);
12218        } else {
12219            let mut only_carets = true;
12220            let mut same_text_selected = true;
12221            let mut selected_text = None;
12222
12223            let mut selections_iter = selections.iter().peekable();
12224            while let Some(selection) = selections_iter.next() {
12225                if selection.start != selection.end {
12226                    only_carets = false;
12227                }
12228
12229                if same_text_selected {
12230                    if selected_text.is_none() {
12231                        selected_text =
12232                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12233                    }
12234
12235                    if let Some(next_selection) = selections_iter.peek() {
12236                        if next_selection.range().len() == selection.range().len() {
12237                            let next_selected_text = buffer
12238                                .text_for_range(next_selection.range())
12239                                .collect::<String>();
12240                            if Some(next_selected_text) != selected_text {
12241                                same_text_selected = false;
12242                                selected_text = None;
12243                            }
12244                        } else {
12245                            same_text_selected = false;
12246                            selected_text = None;
12247                        }
12248                    }
12249                }
12250            }
12251
12252            if only_carets {
12253                for selection in &mut selections {
12254                    let word_range = movement::surrounding_word(
12255                        display_map,
12256                        selection.start.to_display_point(display_map),
12257                    );
12258                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12259                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12260                    selection.goal = SelectionGoal::None;
12261                    selection.reversed = false;
12262                    self.select_match_ranges(
12263                        selection.start..selection.end,
12264                        selection.reversed,
12265                        replace_newest,
12266                        autoscroll,
12267                        window,
12268                        cx,
12269                    );
12270                }
12271
12272                if selections.len() == 1 {
12273                    let selection = selections
12274                        .last()
12275                        .expect("ensured that there's only one selection");
12276                    let query = buffer
12277                        .text_for_range(selection.start..selection.end)
12278                        .collect::<String>();
12279                    let is_empty = query.is_empty();
12280                    let select_state = SelectNextState {
12281                        query: AhoCorasick::new(&[query])?,
12282                        wordwise: true,
12283                        done: is_empty,
12284                    };
12285                    self.select_next_state = Some(select_state);
12286                } else {
12287                    self.select_next_state = None;
12288                }
12289            } else if let Some(selected_text) = selected_text {
12290                self.select_next_state = Some(SelectNextState {
12291                    query: AhoCorasick::new(&[selected_text])?,
12292                    wordwise: false,
12293                    done: false,
12294                });
12295                self.select_next_match_internal(
12296                    display_map,
12297                    replace_newest,
12298                    autoscroll,
12299                    window,
12300                    cx,
12301                )?;
12302            }
12303        }
12304        Ok(())
12305    }
12306
12307    pub fn select_all_matches(
12308        &mut self,
12309        _action: &SelectAllMatches,
12310        window: &mut Window,
12311        cx: &mut Context<Self>,
12312    ) -> Result<()> {
12313        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12314
12315        self.push_to_selection_history();
12316        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12317
12318        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12319        let Some(select_next_state) = self.select_next_state.as_mut() else {
12320            return Ok(());
12321        };
12322        if select_next_state.done {
12323            return Ok(());
12324        }
12325
12326        let mut new_selections = Vec::new();
12327
12328        let reversed = self.selections.oldest::<usize>(cx).reversed;
12329        let buffer = &display_map.buffer_snapshot;
12330        let query_matches = select_next_state
12331            .query
12332            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12333
12334        for query_match in query_matches.into_iter() {
12335            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12336            let offset_range = if reversed {
12337                query_match.end()..query_match.start()
12338            } else {
12339                query_match.start()..query_match.end()
12340            };
12341            let display_range = offset_range.start.to_display_point(&display_map)
12342                ..offset_range.end.to_display_point(&display_map);
12343
12344            if !select_next_state.wordwise
12345                || (!movement::is_inside_word(&display_map, display_range.start)
12346                    && !movement::is_inside_word(&display_map, display_range.end))
12347            {
12348                new_selections.push(offset_range.start..offset_range.end);
12349            }
12350        }
12351
12352        select_next_state.done = true;
12353        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12354        self.change_selections(None, window, cx, |selections| {
12355            selections.select_ranges(new_selections)
12356        });
12357
12358        Ok(())
12359    }
12360
12361    pub fn select_next(
12362        &mut self,
12363        action: &SelectNext,
12364        window: &mut Window,
12365        cx: &mut Context<Self>,
12366    ) -> Result<()> {
12367        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12368        self.push_to_selection_history();
12369        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12370        self.select_next_match_internal(
12371            &display_map,
12372            action.replace_newest,
12373            Some(Autoscroll::newest()),
12374            window,
12375            cx,
12376        )?;
12377        Ok(())
12378    }
12379
12380    pub fn select_previous(
12381        &mut self,
12382        action: &SelectPrevious,
12383        window: &mut Window,
12384        cx: &mut Context<Self>,
12385    ) -> Result<()> {
12386        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12387        self.push_to_selection_history();
12388        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12389        let buffer = &display_map.buffer_snapshot;
12390        let mut selections = self.selections.all::<usize>(cx);
12391        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12392            let query = &select_prev_state.query;
12393            if !select_prev_state.done {
12394                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12395                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12396                let mut next_selected_range = None;
12397                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12398                let bytes_before_last_selection =
12399                    buffer.reversed_bytes_in_range(0..last_selection.start);
12400                let bytes_after_first_selection =
12401                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12402                let query_matches = query
12403                    .stream_find_iter(bytes_before_last_selection)
12404                    .map(|result| (last_selection.start, result))
12405                    .chain(
12406                        query
12407                            .stream_find_iter(bytes_after_first_selection)
12408                            .map(|result| (buffer.len(), result)),
12409                    );
12410                for (end_offset, query_match) in query_matches {
12411                    let query_match = query_match.unwrap(); // can only fail due to I/O
12412                    let offset_range =
12413                        end_offset - query_match.end()..end_offset - query_match.start();
12414                    let display_range = offset_range.start.to_display_point(&display_map)
12415                        ..offset_range.end.to_display_point(&display_map);
12416
12417                    if !select_prev_state.wordwise
12418                        || (!movement::is_inside_word(&display_map, display_range.start)
12419                            && !movement::is_inside_word(&display_map, display_range.end))
12420                    {
12421                        next_selected_range = Some(offset_range);
12422                        break;
12423                    }
12424                }
12425
12426                if let Some(next_selected_range) = next_selected_range {
12427                    self.select_match_ranges(
12428                        next_selected_range,
12429                        last_selection.reversed,
12430                        action.replace_newest,
12431                        Some(Autoscroll::newest()),
12432                        window,
12433                        cx,
12434                    );
12435                } else {
12436                    select_prev_state.done = true;
12437                }
12438            }
12439
12440            self.select_prev_state = Some(select_prev_state);
12441        } else {
12442            let mut only_carets = true;
12443            let mut same_text_selected = true;
12444            let mut selected_text = None;
12445
12446            let mut selections_iter = selections.iter().peekable();
12447            while let Some(selection) = selections_iter.next() {
12448                if selection.start != selection.end {
12449                    only_carets = false;
12450                }
12451
12452                if same_text_selected {
12453                    if selected_text.is_none() {
12454                        selected_text =
12455                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12456                    }
12457
12458                    if let Some(next_selection) = selections_iter.peek() {
12459                        if next_selection.range().len() == selection.range().len() {
12460                            let next_selected_text = buffer
12461                                .text_for_range(next_selection.range())
12462                                .collect::<String>();
12463                            if Some(next_selected_text) != selected_text {
12464                                same_text_selected = false;
12465                                selected_text = None;
12466                            }
12467                        } else {
12468                            same_text_selected = false;
12469                            selected_text = None;
12470                        }
12471                    }
12472                }
12473            }
12474
12475            if only_carets {
12476                for selection in &mut selections {
12477                    let word_range = movement::surrounding_word(
12478                        &display_map,
12479                        selection.start.to_display_point(&display_map),
12480                    );
12481                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12482                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12483                    selection.goal = SelectionGoal::None;
12484                    selection.reversed = false;
12485                    self.select_match_ranges(
12486                        selection.start..selection.end,
12487                        selection.reversed,
12488                        action.replace_newest,
12489                        Some(Autoscroll::newest()),
12490                        window,
12491                        cx,
12492                    );
12493                }
12494                if selections.len() == 1 {
12495                    let selection = selections
12496                        .last()
12497                        .expect("ensured that there's only one selection");
12498                    let query = buffer
12499                        .text_for_range(selection.start..selection.end)
12500                        .collect::<String>();
12501                    let is_empty = query.is_empty();
12502                    let select_state = SelectNextState {
12503                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12504                        wordwise: true,
12505                        done: is_empty,
12506                    };
12507                    self.select_prev_state = Some(select_state);
12508                } else {
12509                    self.select_prev_state = None;
12510                }
12511            } else if let Some(selected_text) = selected_text {
12512                self.select_prev_state = Some(SelectNextState {
12513                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12514                    wordwise: false,
12515                    done: false,
12516                });
12517                self.select_previous(action, window, cx)?;
12518            }
12519        }
12520        Ok(())
12521    }
12522
12523    pub fn find_next_match(
12524        &mut self,
12525        _: &FindNextMatch,
12526        window: &mut Window,
12527        cx: &mut Context<Self>,
12528    ) -> Result<()> {
12529        let selections = self.selections.disjoint_anchors();
12530        match selections.first() {
12531            Some(first) if selections.len() >= 2 => {
12532                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12533                    s.select_ranges([first.range()]);
12534                });
12535            }
12536            _ => self.select_next(
12537                &SelectNext {
12538                    replace_newest: true,
12539                },
12540                window,
12541                cx,
12542            )?,
12543        }
12544        Ok(())
12545    }
12546
12547    pub fn find_previous_match(
12548        &mut self,
12549        _: &FindPreviousMatch,
12550        window: &mut Window,
12551        cx: &mut Context<Self>,
12552    ) -> Result<()> {
12553        let selections = self.selections.disjoint_anchors();
12554        match selections.last() {
12555            Some(last) if selections.len() >= 2 => {
12556                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12557                    s.select_ranges([last.range()]);
12558                });
12559            }
12560            _ => self.select_previous(
12561                &SelectPrevious {
12562                    replace_newest: true,
12563                },
12564                window,
12565                cx,
12566            )?,
12567        }
12568        Ok(())
12569    }
12570
12571    pub fn toggle_comments(
12572        &mut self,
12573        action: &ToggleComments,
12574        window: &mut Window,
12575        cx: &mut Context<Self>,
12576    ) {
12577        if self.read_only(cx) {
12578            return;
12579        }
12580        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12581        let text_layout_details = &self.text_layout_details(window);
12582        self.transact(window, cx, |this, window, cx| {
12583            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12584            let mut edits = Vec::new();
12585            let mut selection_edit_ranges = Vec::new();
12586            let mut last_toggled_row = None;
12587            let snapshot = this.buffer.read(cx).read(cx);
12588            let empty_str: Arc<str> = Arc::default();
12589            let mut suffixes_inserted = Vec::new();
12590            let ignore_indent = action.ignore_indent;
12591
12592            fn comment_prefix_range(
12593                snapshot: &MultiBufferSnapshot,
12594                row: MultiBufferRow,
12595                comment_prefix: &str,
12596                comment_prefix_whitespace: &str,
12597                ignore_indent: bool,
12598            ) -> Range<Point> {
12599                let indent_size = if ignore_indent {
12600                    0
12601                } else {
12602                    snapshot.indent_size_for_line(row).len
12603                };
12604
12605                let start = Point::new(row.0, indent_size);
12606
12607                let mut line_bytes = snapshot
12608                    .bytes_in_range(start..snapshot.max_point())
12609                    .flatten()
12610                    .copied();
12611
12612                // If this line currently begins with the line comment prefix, then record
12613                // the range containing the prefix.
12614                if line_bytes
12615                    .by_ref()
12616                    .take(comment_prefix.len())
12617                    .eq(comment_prefix.bytes())
12618                {
12619                    // Include any whitespace that matches the comment prefix.
12620                    let matching_whitespace_len = line_bytes
12621                        .zip(comment_prefix_whitespace.bytes())
12622                        .take_while(|(a, b)| a == b)
12623                        .count() as u32;
12624                    let end = Point::new(
12625                        start.row,
12626                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12627                    );
12628                    start..end
12629                } else {
12630                    start..start
12631                }
12632            }
12633
12634            fn comment_suffix_range(
12635                snapshot: &MultiBufferSnapshot,
12636                row: MultiBufferRow,
12637                comment_suffix: &str,
12638                comment_suffix_has_leading_space: bool,
12639            ) -> Range<Point> {
12640                let end = Point::new(row.0, snapshot.line_len(row));
12641                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12642
12643                let mut line_end_bytes = snapshot
12644                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12645                    .flatten()
12646                    .copied();
12647
12648                let leading_space_len = if suffix_start_column > 0
12649                    && line_end_bytes.next() == Some(b' ')
12650                    && comment_suffix_has_leading_space
12651                {
12652                    1
12653                } else {
12654                    0
12655                };
12656
12657                // If this line currently begins with the line comment prefix, then record
12658                // the range containing the prefix.
12659                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12660                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12661                    start..end
12662                } else {
12663                    end..end
12664                }
12665            }
12666
12667            // TODO: Handle selections that cross excerpts
12668            for selection in &mut selections {
12669                let start_column = snapshot
12670                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12671                    .len;
12672                let language = if let Some(language) =
12673                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12674                {
12675                    language
12676                } else {
12677                    continue;
12678                };
12679
12680                selection_edit_ranges.clear();
12681
12682                // If multiple selections contain a given row, avoid processing that
12683                // row more than once.
12684                let mut start_row = MultiBufferRow(selection.start.row);
12685                if last_toggled_row == Some(start_row) {
12686                    start_row = start_row.next_row();
12687                }
12688                let end_row =
12689                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12690                        MultiBufferRow(selection.end.row - 1)
12691                    } else {
12692                        MultiBufferRow(selection.end.row)
12693                    };
12694                last_toggled_row = Some(end_row);
12695
12696                if start_row > end_row {
12697                    continue;
12698                }
12699
12700                // If the language has line comments, toggle those.
12701                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12702
12703                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12704                if ignore_indent {
12705                    full_comment_prefixes = full_comment_prefixes
12706                        .into_iter()
12707                        .map(|s| Arc::from(s.trim_end()))
12708                        .collect();
12709                }
12710
12711                if !full_comment_prefixes.is_empty() {
12712                    let first_prefix = full_comment_prefixes
12713                        .first()
12714                        .expect("prefixes is non-empty");
12715                    let prefix_trimmed_lengths = full_comment_prefixes
12716                        .iter()
12717                        .map(|p| p.trim_end_matches(' ').len())
12718                        .collect::<SmallVec<[usize; 4]>>();
12719
12720                    let mut all_selection_lines_are_comments = true;
12721
12722                    for row in start_row.0..=end_row.0 {
12723                        let row = MultiBufferRow(row);
12724                        if start_row < end_row && snapshot.is_line_blank(row) {
12725                            continue;
12726                        }
12727
12728                        let prefix_range = full_comment_prefixes
12729                            .iter()
12730                            .zip(prefix_trimmed_lengths.iter().copied())
12731                            .map(|(prefix, trimmed_prefix_len)| {
12732                                comment_prefix_range(
12733                                    snapshot.deref(),
12734                                    row,
12735                                    &prefix[..trimmed_prefix_len],
12736                                    &prefix[trimmed_prefix_len..],
12737                                    ignore_indent,
12738                                )
12739                            })
12740                            .max_by_key(|range| range.end.column - range.start.column)
12741                            .expect("prefixes is non-empty");
12742
12743                        if prefix_range.is_empty() {
12744                            all_selection_lines_are_comments = false;
12745                        }
12746
12747                        selection_edit_ranges.push(prefix_range);
12748                    }
12749
12750                    if all_selection_lines_are_comments {
12751                        edits.extend(
12752                            selection_edit_ranges
12753                                .iter()
12754                                .cloned()
12755                                .map(|range| (range, empty_str.clone())),
12756                        );
12757                    } else {
12758                        let min_column = selection_edit_ranges
12759                            .iter()
12760                            .map(|range| range.start.column)
12761                            .min()
12762                            .unwrap_or(0);
12763                        edits.extend(selection_edit_ranges.iter().map(|range| {
12764                            let position = Point::new(range.start.row, min_column);
12765                            (position..position, first_prefix.clone())
12766                        }));
12767                    }
12768                } else if let Some((full_comment_prefix, comment_suffix)) =
12769                    language.block_comment_delimiters()
12770                {
12771                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12772                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12773                    let prefix_range = comment_prefix_range(
12774                        snapshot.deref(),
12775                        start_row,
12776                        comment_prefix,
12777                        comment_prefix_whitespace,
12778                        ignore_indent,
12779                    );
12780                    let suffix_range = comment_suffix_range(
12781                        snapshot.deref(),
12782                        end_row,
12783                        comment_suffix.trim_start_matches(' '),
12784                        comment_suffix.starts_with(' '),
12785                    );
12786
12787                    if prefix_range.is_empty() || suffix_range.is_empty() {
12788                        edits.push((
12789                            prefix_range.start..prefix_range.start,
12790                            full_comment_prefix.clone(),
12791                        ));
12792                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12793                        suffixes_inserted.push((end_row, comment_suffix.len()));
12794                    } else {
12795                        edits.push((prefix_range, empty_str.clone()));
12796                        edits.push((suffix_range, empty_str.clone()));
12797                    }
12798                } else {
12799                    continue;
12800                }
12801            }
12802
12803            drop(snapshot);
12804            this.buffer.update(cx, |buffer, cx| {
12805                buffer.edit(edits, None, cx);
12806            });
12807
12808            // Adjust selections so that they end before any comment suffixes that
12809            // were inserted.
12810            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12811            let mut selections = this.selections.all::<Point>(cx);
12812            let snapshot = this.buffer.read(cx).read(cx);
12813            for selection in &mut selections {
12814                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12815                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12816                        Ordering::Less => {
12817                            suffixes_inserted.next();
12818                            continue;
12819                        }
12820                        Ordering::Greater => break,
12821                        Ordering::Equal => {
12822                            if selection.end.column == snapshot.line_len(row) {
12823                                if selection.is_empty() {
12824                                    selection.start.column -= suffix_len as u32;
12825                                }
12826                                selection.end.column -= suffix_len as u32;
12827                            }
12828                            break;
12829                        }
12830                    }
12831                }
12832            }
12833
12834            drop(snapshot);
12835            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12836                s.select(selections)
12837            });
12838
12839            let selections = this.selections.all::<Point>(cx);
12840            let selections_on_single_row = selections.windows(2).all(|selections| {
12841                selections[0].start.row == selections[1].start.row
12842                    && selections[0].end.row == selections[1].end.row
12843                    && selections[0].start.row == selections[0].end.row
12844            });
12845            let selections_selecting = selections
12846                .iter()
12847                .any(|selection| selection.start != selection.end);
12848            let advance_downwards = action.advance_downwards
12849                && selections_on_single_row
12850                && !selections_selecting
12851                && !matches!(this.mode, EditorMode::SingleLine { .. });
12852
12853            if advance_downwards {
12854                let snapshot = this.buffer.read(cx).snapshot(cx);
12855
12856                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12857                    s.move_cursors_with(|display_snapshot, display_point, _| {
12858                        let mut point = display_point.to_point(display_snapshot);
12859                        point.row += 1;
12860                        point = snapshot.clip_point(point, Bias::Left);
12861                        let display_point = point.to_display_point(display_snapshot);
12862                        let goal = SelectionGoal::HorizontalPosition(
12863                            display_snapshot
12864                                .x_for_display_point(display_point, text_layout_details)
12865                                .into(),
12866                        );
12867                        (display_point, goal)
12868                    })
12869                });
12870            }
12871        });
12872    }
12873
12874    pub fn select_enclosing_symbol(
12875        &mut self,
12876        _: &SelectEnclosingSymbol,
12877        window: &mut Window,
12878        cx: &mut Context<Self>,
12879    ) {
12880        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12881
12882        let buffer = self.buffer.read(cx).snapshot(cx);
12883        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12884
12885        fn update_selection(
12886            selection: &Selection<usize>,
12887            buffer_snap: &MultiBufferSnapshot,
12888        ) -> Option<Selection<usize>> {
12889            let cursor = selection.head();
12890            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12891            for symbol in symbols.iter().rev() {
12892                let start = symbol.range.start.to_offset(buffer_snap);
12893                let end = symbol.range.end.to_offset(buffer_snap);
12894                let new_range = start..end;
12895                if start < selection.start || end > selection.end {
12896                    return Some(Selection {
12897                        id: selection.id,
12898                        start: new_range.start,
12899                        end: new_range.end,
12900                        goal: SelectionGoal::None,
12901                        reversed: selection.reversed,
12902                    });
12903                }
12904            }
12905            None
12906        }
12907
12908        let mut selected_larger_symbol = false;
12909        let new_selections = old_selections
12910            .iter()
12911            .map(|selection| match update_selection(selection, &buffer) {
12912                Some(new_selection) => {
12913                    if new_selection.range() != selection.range() {
12914                        selected_larger_symbol = true;
12915                    }
12916                    new_selection
12917                }
12918                None => selection.clone(),
12919            })
12920            .collect::<Vec<_>>();
12921
12922        if selected_larger_symbol {
12923            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12924                s.select(new_selections);
12925            });
12926        }
12927    }
12928
12929    pub fn select_larger_syntax_node(
12930        &mut self,
12931        _: &SelectLargerSyntaxNode,
12932        window: &mut Window,
12933        cx: &mut Context<Self>,
12934    ) {
12935        let Some(visible_row_count) = self.visible_row_count() else {
12936            return;
12937        };
12938        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12939        if old_selections.is_empty() {
12940            return;
12941        }
12942
12943        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12944
12945        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12946        let buffer = self.buffer.read(cx).snapshot(cx);
12947
12948        let mut selected_larger_node = false;
12949        let mut new_selections = old_selections
12950            .iter()
12951            .map(|selection| {
12952                let old_range = selection.start..selection.end;
12953
12954                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12955                    // manually select word at selection
12956                    if ["string_content", "inline"].contains(&node.kind()) {
12957                        let word_range = {
12958                            let display_point = buffer
12959                                .offset_to_point(old_range.start)
12960                                .to_display_point(&display_map);
12961                            let Range { start, end } =
12962                                movement::surrounding_word(&display_map, display_point);
12963                            start.to_point(&display_map).to_offset(&buffer)
12964                                ..end.to_point(&display_map).to_offset(&buffer)
12965                        };
12966                        // ignore if word is already selected
12967                        if !word_range.is_empty() && old_range != word_range {
12968                            let last_word_range = {
12969                                let display_point = buffer
12970                                    .offset_to_point(old_range.end)
12971                                    .to_display_point(&display_map);
12972                                let Range { start, end } =
12973                                    movement::surrounding_word(&display_map, display_point);
12974                                start.to_point(&display_map).to_offset(&buffer)
12975                                    ..end.to_point(&display_map).to_offset(&buffer)
12976                            };
12977                            // only select word if start and end point belongs to same word
12978                            if word_range == last_word_range {
12979                                selected_larger_node = true;
12980                                return Selection {
12981                                    id: selection.id,
12982                                    start: word_range.start,
12983                                    end: word_range.end,
12984                                    goal: SelectionGoal::None,
12985                                    reversed: selection.reversed,
12986                                };
12987                            }
12988                        }
12989                    }
12990                }
12991
12992                let mut new_range = old_range.clone();
12993                while let Some((_node, containing_range)) =
12994                    buffer.syntax_ancestor(new_range.clone())
12995                {
12996                    new_range = match containing_range {
12997                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12998                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12999                    };
13000                    if !display_map.intersects_fold(new_range.start)
13001                        && !display_map.intersects_fold(new_range.end)
13002                    {
13003                        break;
13004                    }
13005                }
13006
13007                selected_larger_node |= new_range != old_range;
13008                Selection {
13009                    id: selection.id,
13010                    start: new_range.start,
13011                    end: new_range.end,
13012                    goal: SelectionGoal::None,
13013                    reversed: selection.reversed,
13014                }
13015            })
13016            .collect::<Vec<_>>();
13017
13018        if !selected_larger_node {
13019            return; // don't put this call in the history
13020        }
13021
13022        // scroll based on transformation done to the last selection created by the user
13023        let (last_old, last_new) = old_selections
13024            .last()
13025            .zip(new_selections.last().cloned())
13026            .expect("old_selections isn't empty");
13027
13028        // revert selection
13029        let is_selection_reversed = {
13030            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13031            new_selections.last_mut().expect("checked above").reversed =
13032                should_newest_selection_be_reversed;
13033            should_newest_selection_be_reversed
13034        };
13035
13036        if selected_larger_node {
13037            self.select_syntax_node_history.disable_clearing = true;
13038            self.change_selections(None, window, cx, |s| {
13039                s.select(new_selections.clone());
13040            });
13041            self.select_syntax_node_history.disable_clearing = false;
13042        }
13043
13044        let start_row = last_new.start.to_display_point(&display_map).row().0;
13045        let end_row = last_new.end.to_display_point(&display_map).row().0;
13046        let selection_height = end_row - start_row + 1;
13047        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13048
13049        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13050        let scroll_behavior = if fits_on_the_screen {
13051            self.request_autoscroll(Autoscroll::fit(), cx);
13052            SelectSyntaxNodeScrollBehavior::FitSelection
13053        } else if is_selection_reversed {
13054            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13055            SelectSyntaxNodeScrollBehavior::CursorTop
13056        } else {
13057            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13058            SelectSyntaxNodeScrollBehavior::CursorBottom
13059        };
13060
13061        self.select_syntax_node_history.push((
13062            old_selections,
13063            scroll_behavior,
13064            is_selection_reversed,
13065        ));
13066    }
13067
13068    pub fn select_smaller_syntax_node(
13069        &mut self,
13070        _: &SelectSmallerSyntaxNode,
13071        window: &mut Window,
13072        cx: &mut Context<Self>,
13073    ) {
13074        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13075
13076        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13077            self.select_syntax_node_history.pop()
13078        {
13079            if let Some(selection) = selections.last_mut() {
13080                selection.reversed = is_selection_reversed;
13081            }
13082
13083            self.select_syntax_node_history.disable_clearing = true;
13084            self.change_selections(None, window, cx, |s| {
13085                s.select(selections.to_vec());
13086            });
13087            self.select_syntax_node_history.disable_clearing = false;
13088
13089            match scroll_behavior {
13090                SelectSyntaxNodeScrollBehavior::CursorTop => {
13091                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13092                }
13093                SelectSyntaxNodeScrollBehavior::FitSelection => {
13094                    self.request_autoscroll(Autoscroll::fit(), cx);
13095                }
13096                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13097                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13098                }
13099            }
13100        }
13101    }
13102
13103    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13104        if !EditorSettings::get_global(cx).gutter.runnables {
13105            self.clear_tasks();
13106            return Task::ready(());
13107        }
13108        let project = self.project.as_ref().map(Entity::downgrade);
13109        let task_sources = self.lsp_task_sources(cx);
13110        cx.spawn_in(window, async move |editor, cx| {
13111            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13112            let Some(project) = project.and_then(|p| p.upgrade()) else {
13113                return;
13114            };
13115            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13116                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13117            }) else {
13118                return;
13119            };
13120
13121            let hide_runnables = project
13122                .update(cx, |project, cx| {
13123                    // Do not display any test indicators in non-dev server remote projects.
13124                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13125                })
13126                .unwrap_or(true);
13127            if hide_runnables {
13128                return;
13129            }
13130            let new_rows =
13131                cx.background_spawn({
13132                    let snapshot = display_snapshot.clone();
13133                    async move {
13134                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13135                    }
13136                })
13137                    .await;
13138            let Ok(lsp_tasks) =
13139                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13140            else {
13141                return;
13142            };
13143            let lsp_tasks = lsp_tasks.await;
13144
13145            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13146                lsp_tasks
13147                    .into_iter()
13148                    .flat_map(|(kind, tasks)| {
13149                        tasks.into_iter().filter_map(move |(location, task)| {
13150                            Some((kind.clone(), location?, task))
13151                        })
13152                    })
13153                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13154                        let buffer = location.target.buffer;
13155                        let buffer_snapshot = buffer.read(cx).snapshot();
13156                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13157                            |(excerpt_id, snapshot, _)| {
13158                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13159                                    display_snapshot
13160                                        .buffer_snapshot
13161                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13162                                } else {
13163                                    None
13164                                }
13165                            },
13166                        );
13167                        if let Some(offset) = offset {
13168                            let task_buffer_range =
13169                                location.target.range.to_point(&buffer_snapshot);
13170                            let context_buffer_range =
13171                                task_buffer_range.to_offset(&buffer_snapshot);
13172                            let context_range = BufferOffset(context_buffer_range.start)
13173                                ..BufferOffset(context_buffer_range.end);
13174
13175                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13176                                .or_insert_with(|| RunnableTasks {
13177                                    templates: Vec::new(),
13178                                    offset,
13179                                    column: task_buffer_range.start.column,
13180                                    extra_variables: HashMap::default(),
13181                                    context_range,
13182                                })
13183                                .templates
13184                                .push((kind, task.original_task().clone()));
13185                        }
13186
13187                        acc
13188                    })
13189            }) else {
13190                return;
13191            };
13192
13193            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13194            editor
13195                .update(cx, |editor, _| {
13196                    editor.clear_tasks();
13197                    for (key, mut value) in rows {
13198                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13199                            value.templates.extend(lsp_tasks.templates);
13200                        }
13201
13202                        editor.insert_tasks(key, value);
13203                    }
13204                    for (key, value) in lsp_tasks_by_rows {
13205                        editor.insert_tasks(key, value);
13206                    }
13207                })
13208                .ok();
13209        })
13210    }
13211    fn fetch_runnable_ranges(
13212        snapshot: &DisplaySnapshot,
13213        range: Range<Anchor>,
13214    ) -> Vec<language::RunnableRange> {
13215        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13216    }
13217
13218    fn runnable_rows(
13219        project: Entity<Project>,
13220        snapshot: DisplaySnapshot,
13221        runnable_ranges: Vec<RunnableRange>,
13222        mut cx: AsyncWindowContext,
13223    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13224        runnable_ranges
13225            .into_iter()
13226            .filter_map(|mut runnable| {
13227                let tasks = cx
13228                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13229                    .ok()?;
13230                if tasks.is_empty() {
13231                    return None;
13232                }
13233
13234                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13235
13236                let row = snapshot
13237                    .buffer_snapshot
13238                    .buffer_line_for_row(MultiBufferRow(point.row))?
13239                    .1
13240                    .start
13241                    .row;
13242
13243                let context_range =
13244                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13245                Some((
13246                    (runnable.buffer_id, row),
13247                    RunnableTasks {
13248                        templates: tasks,
13249                        offset: snapshot
13250                            .buffer_snapshot
13251                            .anchor_before(runnable.run_range.start),
13252                        context_range,
13253                        column: point.column,
13254                        extra_variables: runnable.extra_captures,
13255                    },
13256                ))
13257            })
13258            .collect()
13259    }
13260
13261    fn templates_with_tags(
13262        project: &Entity<Project>,
13263        runnable: &mut Runnable,
13264        cx: &mut App,
13265    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13266        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13267            let (worktree_id, file) = project
13268                .buffer_for_id(runnable.buffer, cx)
13269                .and_then(|buffer| buffer.read(cx).file())
13270                .map(|file| (file.worktree_id(cx), file.clone()))
13271                .unzip();
13272
13273            (
13274                project.task_store().read(cx).task_inventory().cloned(),
13275                worktree_id,
13276                file,
13277            )
13278        });
13279
13280        let mut templates_with_tags = mem::take(&mut runnable.tags)
13281            .into_iter()
13282            .flat_map(|RunnableTag(tag)| {
13283                inventory
13284                    .as_ref()
13285                    .into_iter()
13286                    .flat_map(|inventory| {
13287                        inventory.read(cx).list_tasks(
13288                            file.clone(),
13289                            Some(runnable.language.clone()),
13290                            worktree_id,
13291                            cx,
13292                        )
13293                    })
13294                    .filter(move |(_, template)| {
13295                        template.tags.iter().any(|source_tag| source_tag == &tag)
13296                    })
13297            })
13298            .sorted_by_key(|(kind, _)| kind.to_owned())
13299            .collect::<Vec<_>>();
13300        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13301            // Strongest source wins; if we have worktree tag binding, prefer that to
13302            // global and language bindings;
13303            // if we have a global binding, prefer that to language binding.
13304            let first_mismatch = templates_with_tags
13305                .iter()
13306                .position(|(tag_source, _)| tag_source != leading_tag_source);
13307            if let Some(index) = first_mismatch {
13308                templates_with_tags.truncate(index);
13309            }
13310        }
13311
13312        templates_with_tags
13313    }
13314
13315    pub fn move_to_enclosing_bracket(
13316        &mut self,
13317        _: &MoveToEnclosingBracket,
13318        window: &mut Window,
13319        cx: &mut Context<Self>,
13320    ) {
13321        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13323            s.move_offsets_with(|snapshot, selection| {
13324                let Some(enclosing_bracket_ranges) =
13325                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13326                else {
13327                    return;
13328                };
13329
13330                let mut best_length = usize::MAX;
13331                let mut best_inside = false;
13332                let mut best_in_bracket_range = false;
13333                let mut best_destination = None;
13334                for (open, close) in enclosing_bracket_ranges {
13335                    let close = close.to_inclusive();
13336                    let length = close.end() - open.start;
13337                    let inside = selection.start >= open.end && selection.end <= *close.start();
13338                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13339                        || close.contains(&selection.head());
13340
13341                    // If best is next to a bracket and current isn't, skip
13342                    if !in_bracket_range && best_in_bracket_range {
13343                        continue;
13344                    }
13345
13346                    // Prefer smaller lengths unless best is inside and current isn't
13347                    if length > best_length && (best_inside || !inside) {
13348                        continue;
13349                    }
13350
13351                    best_length = length;
13352                    best_inside = inside;
13353                    best_in_bracket_range = in_bracket_range;
13354                    best_destination = Some(
13355                        if close.contains(&selection.start) && close.contains(&selection.end) {
13356                            if inside { open.end } else { open.start }
13357                        } else if inside {
13358                            *close.start()
13359                        } else {
13360                            *close.end()
13361                        },
13362                    );
13363                }
13364
13365                if let Some(destination) = best_destination {
13366                    selection.collapse_to(destination, SelectionGoal::None);
13367                }
13368            })
13369        });
13370    }
13371
13372    pub fn undo_selection(
13373        &mut self,
13374        _: &UndoSelection,
13375        window: &mut Window,
13376        cx: &mut Context<Self>,
13377    ) {
13378        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13379        self.end_selection(window, cx);
13380        self.selection_history.mode = SelectionHistoryMode::Undoing;
13381        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13382            self.change_selections(None, window, cx, |s| {
13383                s.select_anchors(entry.selections.to_vec())
13384            });
13385            self.select_next_state = entry.select_next_state;
13386            self.select_prev_state = entry.select_prev_state;
13387            self.add_selections_state = entry.add_selections_state;
13388            self.request_autoscroll(Autoscroll::newest(), cx);
13389        }
13390        self.selection_history.mode = SelectionHistoryMode::Normal;
13391    }
13392
13393    pub fn redo_selection(
13394        &mut self,
13395        _: &RedoSelection,
13396        window: &mut Window,
13397        cx: &mut Context<Self>,
13398    ) {
13399        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13400        self.end_selection(window, cx);
13401        self.selection_history.mode = SelectionHistoryMode::Redoing;
13402        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13403            self.change_selections(None, window, cx, |s| {
13404                s.select_anchors(entry.selections.to_vec())
13405            });
13406            self.select_next_state = entry.select_next_state;
13407            self.select_prev_state = entry.select_prev_state;
13408            self.add_selections_state = entry.add_selections_state;
13409            self.request_autoscroll(Autoscroll::newest(), cx);
13410        }
13411        self.selection_history.mode = SelectionHistoryMode::Normal;
13412    }
13413
13414    pub fn expand_excerpts(
13415        &mut self,
13416        action: &ExpandExcerpts,
13417        _: &mut Window,
13418        cx: &mut Context<Self>,
13419    ) {
13420        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13421    }
13422
13423    pub fn expand_excerpts_down(
13424        &mut self,
13425        action: &ExpandExcerptsDown,
13426        _: &mut Window,
13427        cx: &mut Context<Self>,
13428    ) {
13429        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13430    }
13431
13432    pub fn expand_excerpts_up(
13433        &mut self,
13434        action: &ExpandExcerptsUp,
13435        _: &mut Window,
13436        cx: &mut Context<Self>,
13437    ) {
13438        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13439    }
13440
13441    pub fn expand_excerpts_for_direction(
13442        &mut self,
13443        lines: u32,
13444        direction: ExpandExcerptDirection,
13445
13446        cx: &mut Context<Self>,
13447    ) {
13448        let selections = self.selections.disjoint_anchors();
13449
13450        let lines = if lines == 0 {
13451            EditorSettings::get_global(cx).expand_excerpt_lines
13452        } else {
13453            lines
13454        };
13455
13456        self.buffer.update(cx, |buffer, cx| {
13457            let snapshot = buffer.snapshot(cx);
13458            let mut excerpt_ids = selections
13459                .iter()
13460                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13461                .collect::<Vec<_>>();
13462            excerpt_ids.sort();
13463            excerpt_ids.dedup();
13464            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13465        })
13466    }
13467
13468    pub fn expand_excerpt(
13469        &mut self,
13470        excerpt: ExcerptId,
13471        direction: ExpandExcerptDirection,
13472        window: &mut Window,
13473        cx: &mut Context<Self>,
13474    ) {
13475        let current_scroll_position = self.scroll_position(cx);
13476        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13477        let mut should_scroll_up = false;
13478
13479        if direction == ExpandExcerptDirection::Down {
13480            let multi_buffer = self.buffer.read(cx);
13481            let snapshot = multi_buffer.snapshot(cx);
13482            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13483                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13484                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13485                        let buffer_snapshot = buffer.read(cx).snapshot();
13486                        let excerpt_end_row =
13487                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13488                        let last_row = buffer_snapshot.max_point().row;
13489                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13490                        should_scroll_up = lines_below >= lines_to_expand;
13491                    }
13492                }
13493            }
13494        }
13495
13496        self.buffer.update(cx, |buffer, cx| {
13497            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13498        });
13499
13500        if should_scroll_up {
13501            let new_scroll_position =
13502                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13503            self.set_scroll_position(new_scroll_position, window, cx);
13504        }
13505    }
13506
13507    pub fn go_to_singleton_buffer_point(
13508        &mut self,
13509        point: Point,
13510        window: &mut Window,
13511        cx: &mut Context<Self>,
13512    ) {
13513        self.go_to_singleton_buffer_range(point..point, window, cx);
13514    }
13515
13516    pub fn go_to_singleton_buffer_range(
13517        &mut self,
13518        range: Range<Point>,
13519        window: &mut Window,
13520        cx: &mut Context<Self>,
13521    ) {
13522        let multibuffer = self.buffer().read(cx);
13523        let Some(buffer) = multibuffer.as_singleton() else {
13524            return;
13525        };
13526        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13527            return;
13528        };
13529        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13530            return;
13531        };
13532        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13533            s.select_anchor_ranges([start..end])
13534        });
13535    }
13536
13537    pub fn go_to_diagnostic(
13538        &mut self,
13539        _: &GoToDiagnostic,
13540        window: &mut Window,
13541        cx: &mut Context<Self>,
13542    ) {
13543        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13544        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13545    }
13546
13547    pub fn go_to_prev_diagnostic(
13548        &mut self,
13549        _: &GoToPreviousDiagnostic,
13550        window: &mut Window,
13551        cx: &mut Context<Self>,
13552    ) {
13553        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13554        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13555    }
13556
13557    pub fn go_to_diagnostic_impl(
13558        &mut self,
13559        direction: Direction,
13560        window: &mut Window,
13561        cx: &mut Context<Self>,
13562    ) {
13563        let buffer = self.buffer.read(cx).snapshot(cx);
13564        let selection = self.selections.newest::<usize>(cx);
13565
13566        let mut active_group_id = None;
13567        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13568            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13569                active_group_id = Some(active_group.group_id);
13570            }
13571        }
13572
13573        fn filtered(
13574            snapshot: EditorSnapshot,
13575            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13576        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13577            diagnostics
13578                .filter(|entry| entry.range.start != entry.range.end)
13579                .filter(|entry| !entry.diagnostic.is_unnecessary)
13580                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13581        }
13582
13583        let snapshot = self.snapshot(window, cx);
13584        let before = filtered(
13585            snapshot.clone(),
13586            buffer
13587                .diagnostics_in_range(0..selection.start)
13588                .filter(|entry| entry.range.start <= selection.start),
13589        );
13590        let after = filtered(
13591            snapshot,
13592            buffer
13593                .diagnostics_in_range(selection.start..buffer.len())
13594                .filter(|entry| entry.range.start >= selection.start),
13595        );
13596
13597        let mut found: Option<DiagnosticEntry<usize>> = None;
13598        if direction == Direction::Prev {
13599            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13600            {
13601                for diagnostic in prev_diagnostics.into_iter().rev() {
13602                    if diagnostic.range.start != selection.start
13603                        || active_group_id
13604                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13605                    {
13606                        found = Some(diagnostic);
13607                        break 'outer;
13608                    }
13609                }
13610            }
13611        } else {
13612            for diagnostic in after.chain(before) {
13613                if diagnostic.range.start != selection.start
13614                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13615                {
13616                    found = Some(diagnostic);
13617                    break;
13618                }
13619            }
13620        }
13621        let Some(next_diagnostic) = found else {
13622            return;
13623        };
13624
13625        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13626            return;
13627        };
13628        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13629            s.select_ranges(vec![
13630                next_diagnostic.range.start..next_diagnostic.range.start,
13631            ])
13632        });
13633        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13634        self.refresh_inline_completion(false, true, window, cx);
13635    }
13636
13637    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13638        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13639        let snapshot = self.snapshot(window, cx);
13640        let selection = self.selections.newest::<Point>(cx);
13641        self.go_to_hunk_before_or_after_position(
13642            &snapshot,
13643            selection.head(),
13644            Direction::Next,
13645            window,
13646            cx,
13647        );
13648    }
13649
13650    pub fn go_to_hunk_before_or_after_position(
13651        &mut self,
13652        snapshot: &EditorSnapshot,
13653        position: Point,
13654        direction: Direction,
13655        window: &mut Window,
13656        cx: &mut Context<Editor>,
13657    ) {
13658        let row = if direction == Direction::Next {
13659            self.hunk_after_position(snapshot, position)
13660                .map(|hunk| hunk.row_range.start)
13661        } else {
13662            self.hunk_before_position(snapshot, position)
13663        };
13664
13665        if let Some(row) = row {
13666            let destination = Point::new(row.0, 0);
13667            let autoscroll = Autoscroll::center();
13668
13669            self.unfold_ranges(&[destination..destination], false, false, cx);
13670            self.change_selections(Some(autoscroll), window, cx, |s| {
13671                s.select_ranges([destination..destination]);
13672            });
13673        }
13674    }
13675
13676    fn hunk_after_position(
13677        &mut self,
13678        snapshot: &EditorSnapshot,
13679        position: Point,
13680    ) -> Option<MultiBufferDiffHunk> {
13681        snapshot
13682            .buffer_snapshot
13683            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13684            .find(|hunk| hunk.row_range.start.0 > position.row)
13685            .or_else(|| {
13686                snapshot
13687                    .buffer_snapshot
13688                    .diff_hunks_in_range(Point::zero()..position)
13689                    .find(|hunk| hunk.row_range.end.0 < position.row)
13690            })
13691    }
13692
13693    fn go_to_prev_hunk(
13694        &mut self,
13695        _: &GoToPreviousHunk,
13696        window: &mut Window,
13697        cx: &mut Context<Self>,
13698    ) {
13699        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13700        let snapshot = self.snapshot(window, cx);
13701        let selection = self.selections.newest::<Point>(cx);
13702        self.go_to_hunk_before_or_after_position(
13703            &snapshot,
13704            selection.head(),
13705            Direction::Prev,
13706            window,
13707            cx,
13708        );
13709    }
13710
13711    fn hunk_before_position(
13712        &mut self,
13713        snapshot: &EditorSnapshot,
13714        position: Point,
13715    ) -> Option<MultiBufferRow> {
13716        snapshot
13717            .buffer_snapshot
13718            .diff_hunk_before(position)
13719            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13720    }
13721
13722    fn go_to_next_change(
13723        &mut self,
13724        _: &GoToNextChange,
13725        window: &mut Window,
13726        cx: &mut Context<Self>,
13727    ) {
13728        if let Some(selections) = self
13729            .change_list
13730            .next_change(1, Direction::Next)
13731            .map(|s| s.to_vec())
13732        {
13733            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13734                let map = s.display_map();
13735                s.select_display_ranges(selections.iter().map(|a| {
13736                    let point = a.to_display_point(&map);
13737                    point..point
13738                }))
13739            })
13740        }
13741    }
13742
13743    fn go_to_previous_change(
13744        &mut self,
13745        _: &GoToPreviousChange,
13746        window: &mut Window,
13747        cx: &mut Context<Self>,
13748    ) {
13749        if let Some(selections) = self
13750            .change_list
13751            .next_change(1, Direction::Prev)
13752            .map(|s| s.to_vec())
13753        {
13754            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13755                let map = s.display_map();
13756                s.select_display_ranges(selections.iter().map(|a| {
13757                    let point = a.to_display_point(&map);
13758                    point..point
13759                }))
13760            })
13761        }
13762    }
13763
13764    fn go_to_line<T: 'static>(
13765        &mut self,
13766        position: Anchor,
13767        highlight_color: Option<Hsla>,
13768        window: &mut Window,
13769        cx: &mut Context<Self>,
13770    ) {
13771        let snapshot = self.snapshot(window, cx).display_snapshot;
13772        let position = position.to_point(&snapshot.buffer_snapshot);
13773        let start = snapshot
13774            .buffer_snapshot
13775            .clip_point(Point::new(position.row, 0), Bias::Left);
13776        let end = start + Point::new(1, 0);
13777        let start = snapshot.buffer_snapshot.anchor_before(start);
13778        let end = snapshot.buffer_snapshot.anchor_before(end);
13779
13780        self.highlight_rows::<T>(
13781            start..end,
13782            highlight_color
13783                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13784            Default::default(),
13785            cx,
13786        );
13787        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13788    }
13789
13790    pub fn go_to_definition(
13791        &mut self,
13792        _: &GoToDefinition,
13793        window: &mut Window,
13794        cx: &mut Context<Self>,
13795    ) -> Task<Result<Navigated>> {
13796        let definition =
13797            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13798        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13799        cx.spawn_in(window, async move |editor, cx| {
13800            if definition.await? == Navigated::Yes {
13801                return Ok(Navigated::Yes);
13802            }
13803            match fallback_strategy {
13804                GoToDefinitionFallback::None => Ok(Navigated::No),
13805                GoToDefinitionFallback::FindAllReferences => {
13806                    match editor.update_in(cx, |editor, window, cx| {
13807                        editor.find_all_references(&FindAllReferences, window, cx)
13808                    })? {
13809                        Some(references) => references.await,
13810                        None => Ok(Navigated::No),
13811                    }
13812                }
13813            }
13814        })
13815    }
13816
13817    pub fn go_to_declaration(
13818        &mut self,
13819        _: &GoToDeclaration,
13820        window: &mut Window,
13821        cx: &mut Context<Self>,
13822    ) -> Task<Result<Navigated>> {
13823        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13824    }
13825
13826    pub fn go_to_declaration_split(
13827        &mut self,
13828        _: &GoToDeclaration,
13829        window: &mut Window,
13830        cx: &mut Context<Self>,
13831    ) -> Task<Result<Navigated>> {
13832        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13833    }
13834
13835    pub fn go_to_implementation(
13836        &mut self,
13837        _: &GoToImplementation,
13838        window: &mut Window,
13839        cx: &mut Context<Self>,
13840    ) -> Task<Result<Navigated>> {
13841        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13842    }
13843
13844    pub fn go_to_implementation_split(
13845        &mut self,
13846        _: &GoToImplementationSplit,
13847        window: &mut Window,
13848        cx: &mut Context<Self>,
13849    ) -> Task<Result<Navigated>> {
13850        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13851    }
13852
13853    pub fn go_to_type_definition(
13854        &mut self,
13855        _: &GoToTypeDefinition,
13856        window: &mut Window,
13857        cx: &mut Context<Self>,
13858    ) -> Task<Result<Navigated>> {
13859        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13860    }
13861
13862    pub fn go_to_definition_split(
13863        &mut self,
13864        _: &GoToDefinitionSplit,
13865        window: &mut Window,
13866        cx: &mut Context<Self>,
13867    ) -> Task<Result<Navigated>> {
13868        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13869    }
13870
13871    pub fn go_to_type_definition_split(
13872        &mut self,
13873        _: &GoToTypeDefinitionSplit,
13874        window: &mut Window,
13875        cx: &mut Context<Self>,
13876    ) -> Task<Result<Navigated>> {
13877        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13878    }
13879
13880    fn go_to_definition_of_kind(
13881        &mut self,
13882        kind: GotoDefinitionKind,
13883        split: bool,
13884        window: &mut Window,
13885        cx: &mut Context<Self>,
13886    ) -> Task<Result<Navigated>> {
13887        let Some(provider) = self.semantics_provider.clone() else {
13888            return Task::ready(Ok(Navigated::No));
13889        };
13890        let head = self.selections.newest::<usize>(cx).head();
13891        let buffer = self.buffer.read(cx);
13892        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13893            text_anchor
13894        } else {
13895            return Task::ready(Ok(Navigated::No));
13896        };
13897
13898        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13899            return Task::ready(Ok(Navigated::No));
13900        };
13901
13902        cx.spawn_in(window, async move |editor, cx| {
13903            let definitions = definitions.await?;
13904            let navigated = editor
13905                .update_in(cx, |editor, window, cx| {
13906                    editor.navigate_to_hover_links(
13907                        Some(kind),
13908                        definitions
13909                            .into_iter()
13910                            .filter(|location| {
13911                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13912                            })
13913                            .map(HoverLink::Text)
13914                            .collect::<Vec<_>>(),
13915                        split,
13916                        window,
13917                        cx,
13918                    )
13919                })?
13920                .await?;
13921            anyhow::Ok(navigated)
13922        })
13923    }
13924
13925    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13926        let selection = self.selections.newest_anchor();
13927        let head = selection.head();
13928        let tail = selection.tail();
13929
13930        let Some((buffer, start_position)) =
13931            self.buffer.read(cx).text_anchor_for_position(head, cx)
13932        else {
13933            return;
13934        };
13935
13936        let end_position = if head != tail {
13937            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13938                return;
13939            };
13940            Some(pos)
13941        } else {
13942            None
13943        };
13944
13945        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13946            let url = if let Some(end_pos) = end_position {
13947                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13948            } else {
13949                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13950            };
13951
13952            if let Some(url) = url {
13953                editor.update(cx, |_, cx| {
13954                    cx.open_url(&url);
13955                })
13956            } else {
13957                Ok(())
13958            }
13959        });
13960
13961        url_finder.detach();
13962    }
13963
13964    pub fn open_selected_filename(
13965        &mut self,
13966        _: &OpenSelectedFilename,
13967        window: &mut Window,
13968        cx: &mut Context<Self>,
13969    ) {
13970        let Some(workspace) = self.workspace() else {
13971            return;
13972        };
13973
13974        let position = self.selections.newest_anchor().head();
13975
13976        let Some((buffer, buffer_position)) =
13977            self.buffer.read(cx).text_anchor_for_position(position, cx)
13978        else {
13979            return;
13980        };
13981
13982        let project = self.project.clone();
13983
13984        cx.spawn_in(window, async move |_, cx| {
13985            let result = find_file(&buffer, project, buffer_position, cx).await;
13986
13987            if let Some((_, path)) = result {
13988                workspace
13989                    .update_in(cx, |workspace, window, cx| {
13990                        workspace.open_resolved_path(path, window, cx)
13991                    })?
13992                    .await?;
13993            }
13994            anyhow::Ok(())
13995        })
13996        .detach();
13997    }
13998
13999    pub(crate) fn navigate_to_hover_links(
14000        &mut self,
14001        kind: Option<GotoDefinitionKind>,
14002        mut definitions: Vec<HoverLink>,
14003        split: bool,
14004        window: &mut Window,
14005        cx: &mut Context<Editor>,
14006    ) -> Task<Result<Navigated>> {
14007        // If there is one definition, just open it directly
14008        if definitions.len() == 1 {
14009            let definition = definitions.pop().unwrap();
14010
14011            enum TargetTaskResult {
14012                Location(Option<Location>),
14013                AlreadyNavigated,
14014            }
14015
14016            let target_task = match definition {
14017                HoverLink::Text(link) => {
14018                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14019                }
14020                HoverLink::InlayHint(lsp_location, server_id) => {
14021                    let computation =
14022                        self.compute_target_location(lsp_location, server_id, window, cx);
14023                    cx.background_spawn(async move {
14024                        let location = computation.await?;
14025                        Ok(TargetTaskResult::Location(location))
14026                    })
14027                }
14028                HoverLink::Url(url) => {
14029                    cx.open_url(&url);
14030                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14031                }
14032                HoverLink::File(path) => {
14033                    if let Some(workspace) = self.workspace() {
14034                        cx.spawn_in(window, async move |_, cx| {
14035                            workspace
14036                                .update_in(cx, |workspace, window, cx| {
14037                                    workspace.open_resolved_path(path, window, cx)
14038                                })?
14039                                .await
14040                                .map(|_| TargetTaskResult::AlreadyNavigated)
14041                        })
14042                    } else {
14043                        Task::ready(Ok(TargetTaskResult::Location(None)))
14044                    }
14045                }
14046            };
14047            cx.spawn_in(window, async move |editor, cx| {
14048                let target = match target_task.await.context("target resolution task")? {
14049                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14050                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14051                    TargetTaskResult::Location(Some(target)) => target,
14052                };
14053
14054                editor.update_in(cx, |editor, window, cx| {
14055                    let Some(workspace) = editor.workspace() else {
14056                        return Navigated::No;
14057                    };
14058                    let pane = workspace.read(cx).active_pane().clone();
14059
14060                    let range = target.range.to_point(target.buffer.read(cx));
14061                    let range = editor.range_for_match(&range);
14062                    let range = collapse_multiline_range(range);
14063
14064                    if !split
14065                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14066                    {
14067                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14068                    } else {
14069                        window.defer(cx, move |window, cx| {
14070                            let target_editor: Entity<Self> =
14071                                workspace.update(cx, |workspace, cx| {
14072                                    let pane = if split {
14073                                        workspace.adjacent_pane(window, cx)
14074                                    } else {
14075                                        workspace.active_pane().clone()
14076                                    };
14077
14078                                    workspace.open_project_item(
14079                                        pane,
14080                                        target.buffer.clone(),
14081                                        true,
14082                                        true,
14083                                        window,
14084                                        cx,
14085                                    )
14086                                });
14087                            target_editor.update(cx, |target_editor, cx| {
14088                                // When selecting a definition in a different buffer, disable the nav history
14089                                // to avoid creating a history entry at the previous cursor location.
14090                                pane.update(cx, |pane, _| pane.disable_history());
14091                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14092                                pane.update(cx, |pane, _| pane.enable_history());
14093                            });
14094                        });
14095                    }
14096                    Navigated::Yes
14097                })
14098            })
14099        } else if !definitions.is_empty() {
14100            cx.spawn_in(window, async move |editor, cx| {
14101                let (title, location_tasks, workspace) = editor
14102                    .update_in(cx, |editor, window, cx| {
14103                        let tab_kind = match kind {
14104                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14105                            _ => "Definitions",
14106                        };
14107                        let title = definitions
14108                            .iter()
14109                            .find_map(|definition| match definition {
14110                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14111                                    let buffer = origin.buffer.read(cx);
14112                                    format!(
14113                                        "{} for {}",
14114                                        tab_kind,
14115                                        buffer
14116                                            .text_for_range(origin.range.clone())
14117                                            .collect::<String>()
14118                                    )
14119                                }),
14120                                HoverLink::InlayHint(_, _) => None,
14121                                HoverLink::Url(_) => None,
14122                                HoverLink::File(_) => None,
14123                            })
14124                            .unwrap_or(tab_kind.to_string());
14125                        let location_tasks = definitions
14126                            .into_iter()
14127                            .map(|definition| match definition {
14128                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14129                                HoverLink::InlayHint(lsp_location, server_id) => editor
14130                                    .compute_target_location(lsp_location, server_id, window, cx),
14131                                HoverLink::Url(_) => Task::ready(Ok(None)),
14132                                HoverLink::File(_) => Task::ready(Ok(None)),
14133                            })
14134                            .collect::<Vec<_>>();
14135                        (title, location_tasks, editor.workspace().clone())
14136                    })
14137                    .context("location tasks preparation")?;
14138
14139                let locations = future::join_all(location_tasks)
14140                    .await
14141                    .into_iter()
14142                    .filter_map(|location| location.transpose())
14143                    .collect::<Result<_>>()
14144                    .context("location tasks")?;
14145
14146                let Some(workspace) = workspace else {
14147                    return Ok(Navigated::No);
14148                };
14149                let opened = workspace
14150                    .update_in(cx, |workspace, window, cx| {
14151                        Self::open_locations_in_multibuffer(
14152                            workspace,
14153                            locations,
14154                            title,
14155                            split,
14156                            MultibufferSelectionMode::First,
14157                            window,
14158                            cx,
14159                        )
14160                    })
14161                    .ok();
14162
14163                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14164            })
14165        } else {
14166            Task::ready(Ok(Navigated::No))
14167        }
14168    }
14169
14170    fn compute_target_location(
14171        &self,
14172        lsp_location: lsp::Location,
14173        server_id: LanguageServerId,
14174        window: &mut Window,
14175        cx: &mut Context<Self>,
14176    ) -> Task<anyhow::Result<Option<Location>>> {
14177        let Some(project) = self.project.clone() else {
14178            return Task::ready(Ok(None));
14179        };
14180
14181        cx.spawn_in(window, async move |editor, cx| {
14182            let location_task = editor.update(cx, |_, cx| {
14183                project.update(cx, |project, cx| {
14184                    let language_server_name = project
14185                        .language_server_statuses(cx)
14186                        .find(|(id, _)| server_id == *id)
14187                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14188                    language_server_name.map(|language_server_name| {
14189                        project.open_local_buffer_via_lsp(
14190                            lsp_location.uri.clone(),
14191                            server_id,
14192                            language_server_name,
14193                            cx,
14194                        )
14195                    })
14196                })
14197            })?;
14198            let location = match location_task {
14199                Some(task) => Some({
14200                    let target_buffer_handle = task.await.context("open local buffer")?;
14201                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14202                        let target_start = target_buffer
14203                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14204                        let target_end = target_buffer
14205                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14206                        target_buffer.anchor_after(target_start)
14207                            ..target_buffer.anchor_before(target_end)
14208                    })?;
14209                    Location {
14210                        buffer: target_buffer_handle,
14211                        range,
14212                    }
14213                }),
14214                None => None,
14215            };
14216            Ok(location)
14217        })
14218    }
14219
14220    pub fn find_all_references(
14221        &mut self,
14222        _: &FindAllReferences,
14223        window: &mut Window,
14224        cx: &mut Context<Self>,
14225    ) -> Option<Task<Result<Navigated>>> {
14226        let selection = self.selections.newest::<usize>(cx);
14227        let multi_buffer = self.buffer.read(cx);
14228        let head = selection.head();
14229
14230        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14231        let head_anchor = multi_buffer_snapshot.anchor_at(
14232            head,
14233            if head < selection.tail() {
14234                Bias::Right
14235            } else {
14236                Bias::Left
14237            },
14238        );
14239
14240        match self
14241            .find_all_references_task_sources
14242            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14243        {
14244            Ok(_) => {
14245                log::info!(
14246                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14247                );
14248                return None;
14249            }
14250            Err(i) => {
14251                self.find_all_references_task_sources.insert(i, head_anchor);
14252            }
14253        }
14254
14255        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14256        let workspace = self.workspace()?;
14257        let project = workspace.read(cx).project().clone();
14258        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14259        Some(cx.spawn_in(window, async move |editor, cx| {
14260            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14261                if let Ok(i) = editor
14262                    .find_all_references_task_sources
14263                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14264                {
14265                    editor.find_all_references_task_sources.remove(i);
14266                }
14267            });
14268
14269            let locations = references.await?;
14270            if locations.is_empty() {
14271                return anyhow::Ok(Navigated::No);
14272            }
14273
14274            workspace.update_in(cx, |workspace, window, cx| {
14275                let title = locations
14276                    .first()
14277                    .as_ref()
14278                    .map(|location| {
14279                        let buffer = location.buffer.read(cx);
14280                        format!(
14281                            "References to `{}`",
14282                            buffer
14283                                .text_for_range(location.range.clone())
14284                                .collect::<String>()
14285                        )
14286                    })
14287                    .unwrap();
14288                Self::open_locations_in_multibuffer(
14289                    workspace,
14290                    locations,
14291                    title,
14292                    false,
14293                    MultibufferSelectionMode::First,
14294                    window,
14295                    cx,
14296                );
14297                Navigated::Yes
14298            })
14299        }))
14300    }
14301
14302    /// Opens a multibuffer with the given project locations in it
14303    pub fn open_locations_in_multibuffer(
14304        workspace: &mut Workspace,
14305        mut locations: Vec<Location>,
14306        title: String,
14307        split: bool,
14308        multibuffer_selection_mode: MultibufferSelectionMode,
14309        window: &mut Window,
14310        cx: &mut Context<Workspace>,
14311    ) {
14312        // If there are multiple definitions, open them in a multibuffer
14313        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14314        let mut locations = locations.into_iter().peekable();
14315        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14316        let capability = workspace.project().read(cx).capability();
14317
14318        let excerpt_buffer = cx.new(|cx| {
14319            let mut multibuffer = MultiBuffer::new(capability);
14320            while let Some(location) = locations.next() {
14321                let buffer = location.buffer.read(cx);
14322                let mut ranges_for_buffer = Vec::new();
14323                let range = location.range.to_point(buffer);
14324                ranges_for_buffer.push(range.clone());
14325
14326                while let Some(next_location) = locations.peek() {
14327                    if next_location.buffer == location.buffer {
14328                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14329                        locations.next();
14330                    } else {
14331                        break;
14332                    }
14333                }
14334
14335                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14336                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14337                    PathKey::for_buffer(&location.buffer, cx),
14338                    location.buffer.clone(),
14339                    ranges_for_buffer,
14340                    DEFAULT_MULTIBUFFER_CONTEXT,
14341                    cx,
14342                );
14343                ranges.extend(new_ranges)
14344            }
14345
14346            multibuffer.with_title(title)
14347        });
14348
14349        let editor = cx.new(|cx| {
14350            Editor::for_multibuffer(
14351                excerpt_buffer,
14352                Some(workspace.project().clone()),
14353                window,
14354                cx,
14355            )
14356        });
14357        editor.update(cx, |editor, cx| {
14358            match multibuffer_selection_mode {
14359                MultibufferSelectionMode::First => {
14360                    if let Some(first_range) = ranges.first() {
14361                        editor.change_selections(None, window, cx, |selections| {
14362                            selections.clear_disjoint();
14363                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14364                        });
14365                    }
14366                    editor.highlight_background::<Self>(
14367                        &ranges,
14368                        |theme| theme.editor_highlighted_line_background,
14369                        cx,
14370                    );
14371                }
14372                MultibufferSelectionMode::All => {
14373                    editor.change_selections(None, window, cx, |selections| {
14374                        selections.clear_disjoint();
14375                        selections.select_anchor_ranges(ranges);
14376                    });
14377                }
14378            }
14379            editor.register_buffers_with_language_servers(cx);
14380        });
14381
14382        let item = Box::new(editor);
14383        let item_id = item.item_id();
14384
14385        if split {
14386            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14387        } else {
14388            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14389                let (preview_item_id, preview_item_idx) =
14390                    workspace.active_pane().update(cx, |pane, _| {
14391                        (pane.preview_item_id(), pane.preview_item_idx())
14392                    });
14393
14394                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14395
14396                if let Some(preview_item_id) = preview_item_id {
14397                    workspace.active_pane().update(cx, |pane, cx| {
14398                        pane.remove_item(preview_item_id, false, false, window, cx);
14399                    });
14400                }
14401            } else {
14402                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14403            }
14404        }
14405        workspace.active_pane().update(cx, |pane, cx| {
14406            pane.set_preview_item_id(Some(item_id), cx);
14407        });
14408    }
14409
14410    pub fn rename(
14411        &mut self,
14412        _: &Rename,
14413        window: &mut Window,
14414        cx: &mut Context<Self>,
14415    ) -> Option<Task<Result<()>>> {
14416        use language::ToOffset as _;
14417
14418        let provider = self.semantics_provider.clone()?;
14419        let selection = self.selections.newest_anchor().clone();
14420        let (cursor_buffer, cursor_buffer_position) = self
14421            .buffer
14422            .read(cx)
14423            .text_anchor_for_position(selection.head(), cx)?;
14424        let (tail_buffer, cursor_buffer_position_end) = self
14425            .buffer
14426            .read(cx)
14427            .text_anchor_for_position(selection.tail(), cx)?;
14428        if tail_buffer != cursor_buffer {
14429            return None;
14430        }
14431
14432        let snapshot = cursor_buffer.read(cx).snapshot();
14433        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14434        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14435        let prepare_rename = provider
14436            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14437            .unwrap_or_else(|| Task::ready(Ok(None)));
14438        drop(snapshot);
14439
14440        Some(cx.spawn_in(window, async move |this, cx| {
14441            let rename_range = if let Some(range) = prepare_rename.await? {
14442                Some(range)
14443            } else {
14444                this.update(cx, |this, cx| {
14445                    let buffer = this.buffer.read(cx).snapshot(cx);
14446                    let mut buffer_highlights = this
14447                        .document_highlights_for_position(selection.head(), &buffer)
14448                        .filter(|highlight| {
14449                            highlight.start.excerpt_id == selection.head().excerpt_id
14450                                && highlight.end.excerpt_id == selection.head().excerpt_id
14451                        });
14452                    buffer_highlights
14453                        .next()
14454                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14455                })?
14456            };
14457            if let Some(rename_range) = rename_range {
14458                this.update_in(cx, |this, window, cx| {
14459                    let snapshot = cursor_buffer.read(cx).snapshot();
14460                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14461                    let cursor_offset_in_rename_range =
14462                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14463                    let cursor_offset_in_rename_range_end =
14464                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14465
14466                    this.take_rename(false, window, cx);
14467                    let buffer = this.buffer.read(cx).read(cx);
14468                    let cursor_offset = selection.head().to_offset(&buffer);
14469                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14470                    let rename_end = rename_start + rename_buffer_range.len();
14471                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14472                    let mut old_highlight_id = None;
14473                    let old_name: Arc<str> = buffer
14474                        .chunks(rename_start..rename_end, true)
14475                        .map(|chunk| {
14476                            if old_highlight_id.is_none() {
14477                                old_highlight_id = chunk.syntax_highlight_id;
14478                            }
14479                            chunk.text
14480                        })
14481                        .collect::<String>()
14482                        .into();
14483
14484                    drop(buffer);
14485
14486                    // Position the selection in the rename editor so that it matches the current selection.
14487                    this.show_local_selections = false;
14488                    let rename_editor = cx.new(|cx| {
14489                        let mut editor = Editor::single_line(window, cx);
14490                        editor.buffer.update(cx, |buffer, cx| {
14491                            buffer.edit([(0..0, old_name.clone())], None, cx)
14492                        });
14493                        let rename_selection_range = match cursor_offset_in_rename_range
14494                            .cmp(&cursor_offset_in_rename_range_end)
14495                        {
14496                            Ordering::Equal => {
14497                                editor.select_all(&SelectAll, window, cx);
14498                                return editor;
14499                            }
14500                            Ordering::Less => {
14501                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14502                            }
14503                            Ordering::Greater => {
14504                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14505                            }
14506                        };
14507                        if rename_selection_range.end > old_name.len() {
14508                            editor.select_all(&SelectAll, window, cx);
14509                        } else {
14510                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14511                                s.select_ranges([rename_selection_range]);
14512                            });
14513                        }
14514                        editor
14515                    });
14516                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14517                        if e == &EditorEvent::Focused {
14518                            cx.emit(EditorEvent::FocusedIn)
14519                        }
14520                    })
14521                    .detach();
14522
14523                    let write_highlights =
14524                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14525                    let read_highlights =
14526                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14527                    let ranges = write_highlights
14528                        .iter()
14529                        .flat_map(|(_, ranges)| ranges.iter())
14530                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14531                        .cloned()
14532                        .collect();
14533
14534                    this.highlight_text::<Rename>(
14535                        ranges,
14536                        HighlightStyle {
14537                            fade_out: Some(0.6),
14538                            ..Default::default()
14539                        },
14540                        cx,
14541                    );
14542                    let rename_focus_handle = rename_editor.focus_handle(cx);
14543                    window.focus(&rename_focus_handle);
14544                    let block_id = this.insert_blocks(
14545                        [BlockProperties {
14546                            style: BlockStyle::Flex,
14547                            placement: BlockPlacement::Below(range.start),
14548                            height: Some(1),
14549                            render: Arc::new({
14550                                let rename_editor = rename_editor.clone();
14551                                move |cx: &mut BlockContext| {
14552                                    let mut text_style = cx.editor_style.text.clone();
14553                                    if let Some(highlight_style) = old_highlight_id
14554                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14555                                    {
14556                                        text_style = text_style.highlight(highlight_style);
14557                                    }
14558                                    div()
14559                                        .block_mouse_down()
14560                                        .pl(cx.anchor_x)
14561                                        .child(EditorElement::new(
14562                                            &rename_editor,
14563                                            EditorStyle {
14564                                                background: cx.theme().system().transparent,
14565                                                local_player: cx.editor_style.local_player,
14566                                                text: text_style,
14567                                                scrollbar_width: cx.editor_style.scrollbar_width,
14568                                                syntax: cx.editor_style.syntax.clone(),
14569                                                status: cx.editor_style.status.clone(),
14570                                                inlay_hints_style: HighlightStyle {
14571                                                    font_weight: Some(FontWeight::BOLD),
14572                                                    ..make_inlay_hints_style(cx.app)
14573                                                },
14574                                                inline_completion_styles: make_suggestion_styles(
14575                                                    cx.app,
14576                                                ),
14577                                                ..EditorStyle::default()
14578                                            },
14579                                        ))
14580                                        .into_any_element()
14581                                }
14582                            }),
14583                            priority: 0,
14584                        }],
14585                        Some(Autoscroll::fit()),
14586                        cx,
14587                    )[0];
14588                    this.pending_rename = Some(RenameState {
14589                        range,
14590                        old_name,
14591                        editor: rename_editor,
14592                        block_id,
14593                    });
14594                })?;
14595            }
14596
14597            Ok(())
14598        }))
14599    }
14600
14601    pub fn confirm_rename(
14602        &mut self,
14603        _: &ConfirmRename,
14604        window: &mut Window,
14605        cx: &mut Context<Self>,
14606    ) -> Option<Task<Result<()>>> {
14607        let rename = self.take_rename(false, window, cx)?;
14608        let workspace = self.workspace()?.downgrade();
14609        let (buffer, start) = self
14610            .buffer
14611            .read(cx)
14612            .text_anchor_for_position(rename.range.start, cx)?;
14613        let (end_buffer, _) = self
14614            .buffer
14615            .read(cx)
14616            .text_anchor_for_position(rename.range.end, cx)?;
14617        if buffer != end_buffer {
14618            return None;
14619        }
14620
14621        let old_name = rename.old_name;
14622        let new_name = rename.editor.read(cx).text(cx);
14623
14624        let rename = self.semantics_provider.as_ref()?.perform_rename(
14625            &buffer,
14626            start,
14627            new_name.clone(),
14628            cx,
14629        )?;
14630
14631        Some(cx.spawn_in(window, async move |editor, cx| {
14632            let project_transaction = rename.await?;
14633            Self::open_project_transaction(
14634                &editor,
14635                workspace,
14636                project_transaction,
14637                format!("Rename: {}{}", old_name, new_name),
14638                cx,
14639            )
14640            .await?;
14641
14642            editor.update(cx, |editor, cx| {
14643                editor.refresh_document_highlights(cx);
14644            })?;
14645            Ok(())
14646        }))
14647    }
14648
14649    fn take_rename(
14650        &mut self,
14651        moving_cursor: bool,
14652        window: &mut Window,
14653        cx: &mut Context<Self>,
14654    ) -> Option<RenameState> {
14655        let rename = self.pending_rename.take()?;
14656        if rename.editor.focus_handle(cx).is_focused(window) {
14657            window.focus(&self.focus_handle);
14658        }
14659
14660        self.remove_blocks(
14661            [rename.block_id].into_iter().collect(),
14662            Some(Autoscroll::fit()),
14663            cx,
14664        );
14665        self.clear_highlights::<Rename>(cx);
14666        self.show_local_selections = true;
14667
14668        if moving_cursor {
14669            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14670                editor.selections.newest::<usize>(cx).head()
14671            });
14672
14673            // Update the selection to match the position of the selection inside
14674            // the rename editor.
14675            let snapshot = self.buffer.read(cx).read(cx);
14676            let rename_range = rename.range.to_offset(&snapshot);
14677            let cursor_in_editor = snapshot
14678                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14679                .min(rename_range.end);
14680            drop(snapshot);
14681
14682            self.change_selections(None, window, cx, |s| {
14683                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14684            });
14685        } else {
14686            self.refresh_document_highlights(cx);
14687        }
14688
14689        Some(rename)
14690    }
14691
14692    pub fn pending_rename(&self) -> Option<&RenameState> {
14693        self.pending_rename.as_ref()
14694    }
14695
14696    fn format(
14697        &mut self,
14698        _: &Format,
14699        window: &mut Window,
14700        cx: &mut Context<Self>,
14701    ) -> Option<Task<Result<()>>> {
14702        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14703
14704        let project = match &self.project {
14705            Some(project) => project.clone(),
14706            None => return None,
14707        };
14708
14709        Some(self.perform_format(
14710            project,
14711            FormatTrigger::Manual,
14712            FormatTarget::Buffers,
14713            window,
14714            cx,
14715        ))
14716    }
14717
14718    fn format_selections(
14719        &mut self,
14720        _: &FormatSelections,
14721        window: &mut Window,
14722        cx: &mut Context<Self>,
14723    ) -> Option<Task<Result<()>>> {
14724        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14725
14726        let project = match &self.project {
14727            Some(project) => project.clone(),
14728            None => return None,
14729        };
14730
14731        let ranges = self
14732            .selections
14733            .all_adjusted(cx)
14734            .into_iter()
14735            .map(|selection| selection.range())
14736            .collect_vec();
14737
14738        Some(self.perform_format(
14739            project,
14740            FormatTrigger::Manual,
14741            FormatTarget::Ranges(ranges),
14742            window,
14743            cx,
14744        ))
14745    }
14746
14747    fn perform_format(
14748        &mut self,
14749        project: Entity<Project>,
14750        trigger: FormatTrigger,
14751        target: FormatTarget,
14752        window: &mut Window,
14753        cx: &mut Context<Self>,
14754    ) -> Task<Result<()>> {
14755        let buffer = self.buffer.clone();
14756        let (buffers, target) = match target {
14757            FormatTarget::Buffers => {
14758                let mut buffers = buffer.read(cx).all_buffers();
14759                if trigger == FormatTrigger::Save {
14760                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14761                }
14762                (buffers, LspFormatTarget::Buffers)
14763            }
14764            FormatTarget::Ranges(selection_ranges) => {
14765                let multi_buffer = buffer.read(cx);
14766                let snapshot = multi_buffer.read(cx);
14767                let mut buffers = HashSet::default();
14768                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14769                    BTreeMap::new();
14770                for selection_range in selection_ranges {
14771                    for (buffer, buffer_range, _) in
14772                        snapshot.range_to_buffer_ranges(selection_range)
14773                    {
14774                        let buffer_id = buffer.remote_id();
14775                        let start = buffer.anchor_before(buffer_range.start);
14776                        let end = buffer.anchor_after(buffer_range.end);
14777                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14778                        buffer_id_to_ranges
14779                            .entry(buffer_id)
14780                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14781                            .or_insert_with(|| vec![start..end]);
14782                    }
14783                }
14784                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14785            }
14786        };
14787
14788        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14789        let selections_prev = transaction_id_prev
14790            .and_then(|transaction_id_prev| {
14791                // default to selections as they were after the last edit, if we have them,
14792                // instead of how they are now.
14793                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14794                // will take you back to where you made the last edit, instead of staying where you scrolled
14795                self.selection_history
14796                    .transaction(transaction_id_prev)
14797                    .map(|t| t.0.clone())
14798            })
14799            .unwrap_or_else(|| {
14800                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14801                self.selections.disjoint_anchors()
14802            });
14803
14804        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14805        let format = project.update(cx, |project, cx| {
14806            project.format(buffers, target, true, trigger, cx)
14807        });
14808
14809        cx.spawn_in(window, async move |editor, cx| {
14810            let transaction = futures::select_biased! {
14811                transaction = format.log_err().fuse() => transaction,
14812                () = timeout => {
14813                    log::warn!("timed out waiting for formatting");
14814                    None
14815                }
14816            };
14817
14818            buffer
14819                .update(cx, |buffer, cx| {
14820                    if let Some(transaction) = transaction {
14821                        if !buffer.is_singleton() {
14822                            buffer.push_transaction(&transaction.0, cx);
14823                        }
14824                    }
14825                    cx.notify();
14826                })
14827                .ok();
14828
14829            if let Some(transaction_id_now) =
14830                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14831            {
14832                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14833                if has_new_transaction {
14834                    _ = editor.update(cx, |editor, _| {
14835                        editor
14836                            .selection_history
14837                            .insert_transaction(transaction_id_now, selections_prev);
14838                    });
14839                }
14840            }
14841
14842            Ok(())
14843        })
14844    }
14845
14846    fn organize_imports(
14847        &mut self,
14848        _: &OrganizeImports,
14849        window: &mut Window,
14850        cx: &mut Context<Self>,
14851    ) -> Option<Task<Result<()>>> {
14852        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14853        let project = match &self.project {
14854            Some(project) => project.clone(),
14855            None => return None,
14856        };
14857        Some(self.perform_code_action_kind(
14858            project,
14859            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14860            window,
14861            cx,
14862        ))
14863    }
14864
14865    fn perform_code_action_kind(
14866        &mut self,
14867        project: Entity<Project>,
14868        kind: CodeActionKind,
14869        window: &mut Window,
14870        cx: &mut Context<Self>,
14871    ) -> Task<Result<()>> {
14872        let buffer = self.buffer.clone();
14873        let buffers = buffer.read(cx).all_buffers();
14874        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14875        let apply_action = project.update(cx, |project, cx| {
14876            project.apply_code_action_kind(buffers, kind, true, cx)
14877        });
14878        cx.spawn_in(window, async move |_, cx| {
14879            let transaction = futures::select_biased! {
14880                () = timeout => {
14881                    log::warn!("timed out waiting for executing code action");
14882                    None
14883                }
14884                transaction = apply_action.log_err().fuse() => transaction,
14885            };
14886            buffer
14887                .update(cx, |buffer, cx| {
14888                    // check if we need this
14889                    if let Some(transaction) = transaction {
14890                        if !buffer.is_singleton() {
14891                            buffer.push_transaction(&transaction.0, cx);
14892                        }
14893                    }
14894                    cx.notify();
14895                })
14896                .ok();
14897            Ok(())
14898        })
14899    }
14900
14901    fn restart_language_server(
14902        &mut self,
14903        _: &RestartLanguageServer,
14904        _: &mut Window,
14905        cx: &mut Context<Self>,
14906    ) {
14907        if let Some(project) = self.project.clone() {
14908            self.buffer.update(cx, |multi_buffer, cx| {
14909                project.update(cx, |project, cx| {
14910                    project.restart_language_servers_for_buffers(
14911                        multi_buffer.all_buffers().into_iter().collect(),
14912                        cx,
14913                    );
14914                });
14915            })
14916        }
14917    }
14918
14919    fn stop_language_server(
14920        &mut self,
14921        _: &StopLanguageServer,
14922        _: &mut Window,
14923        cx: &mut Context<Self>,
14924    ) {
14925        if let Some(project) = self.project.clone() {
14926            self.buffer.update(cx, |multi_buffer, cx| {
14927                project.update(cx, |project, cx| {
14928                    project.stop_language_servers_for_buffers(
14929                        multi_buffer.all_buffers().into_iter().collect(),
14930                        cx,
14931                    );
14932                    cx.emit(project::Event::RefreshInlayHints);
14933                });
14934            });
14935        }
14936    }
14937
14938    fn cancel_language_server_work(
14939        workspace: &mut Workspace,
14940        _: &actions::CancelLanguageServerWork,
14941        _: &mut Window,
14942        cx: &mut Context<Workspace>,
14943    ) {
14944        let project = workspace.project();
14945        let buffers = workspace
14946            .active_item(cx)
14947            .and_then(|item| item.act_as::<Editor>(cx))
14948            .map_or(HashSet::default(), |editor| {
14949                editor.read(cx).buffer.read(cx).all_buffers()
14950            });
14951        project.update(cx, |project, cx| {
14952            project.cancel_language_server_work_for_buffers(buffers, cx);
14953        });
14954    }
14955
14956    fn show_character_palette(
14957        &mut self,
14958        _: &ShowCharacterPalette,
14959        window: &mut Window,
14960        _: &mut Context<Self>,
14961    ) {
14962        window.show_character_palette();
14963    }
14964
14965    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14966        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14967            let buffer = self.buffer.read(cx).snapshot(cx);
14968            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14969            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14970            let is_valid = buffer
14971                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14972                .any(|entry| {
14973                    entry.diagnostic.is_primary
14974                        && !entry.range.is_empty()
14975                        && entry.range.start == primary_range_start
14976                        && entry.diagnostic.message == active_diagnostics.active_message
14977                });
14978
14979            if !is_valid {
14980                self.dismiss_diagnostics(cx);
14981            }
14982        }
14983    }
14984
14985    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14986        match &self.active_diagnostics {
14987            ActiveDiagnostic::Group(group) => Some(group),
14988            _ => None,
14989        }
14990    }
14991
14992    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14993        self.dismiss_diagnostics(cx);
14994        self.active_diagnostics = ActiveDiagnostic::All;
14995    }
14996
14997    fn activate_diagnostics(
14998        &mut self,
14999        buffer_id: BufferId,
15000        diagnostic: DiagnosticEntry<usize>,
15001        window: &mut Window,
15002        cx: &mut Context<Self>,
15003    ) {
15004        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15005            return;
15006        }
15007        self.dismiss_diagnostics(cx);
15008        let snapshot = self.snapshot(window, cx);
15009        let buffer = self.buffer.read(cx).snapshot(cx);
15010        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15011            return;
15012        };
15013
15014        let diagnostic_group = buffer
15015            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15016            .collect::<Vec<_>>();
15017
15018        let blocks =
15019            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15020
15021        let blocks = self.display_map.update(cx, |display_map, cx| {
15022            display_map.insert_blocks(blocks, cx).into_iter().collect()
15023        });
15024        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15025            active_range: buffer.anchor_before(diagnostic.range.start)
15026                ..buffer.anchor_after(diagnostic.range.end),
15027            active_message: diagnostic.diagnostic.message.clone(),
15028            group_id: diagnostic.diagnostic.group_id,
15029            blocks,
15030        });
15031        cx.notify();
15032    }
15033
15034    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15035        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15036            return;
15037        };
15038
15039        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15040        if let ActiveDiagnostic::Group(group) = prev {
15041            self.display_map.update(cx, |display_map, cx| {
15042                display_map.remove_blocks(group.blocks, cx);
15043            });
15044            cx.notify();
15045        }
15046    }
15047
15048    /// Disable inline diagnostics rendering for this editor.
15049    pub fn disable_inline_diagnostics(&mut self) {
15050        self.inline_diagnostics_enabled = false;
15051        self.inline_diagnostics_update = Task::ready(());
15052        self.inline_diagnostics.clear();
15053    }
15054
15055    pub fn inline_diagnostics_enabled(&self) -> bool {
15056        self.inline_diagnostics_enabled
15057    }
15058
15059    pub fn show_inline_diagnostics(&self) -> bool {
15060        self.show_inline_diagnostics
15061    }
15062
15063    pub fn toggle_inline_diagnostics(
15064        &mut self,
15065        _: &ToggleInlineDiagnostics,
15066        window: &mut Window,
15067        cx: &mut Context<Editor>,
15068    ) {
15069        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15070        self.refresh_inline_diagnostics(false, window, cx);
15071    }
15072
15073    fn refresh_inline_diagnostics(
15074        &mut self,
15075        debounce: bool,
15076        window: &mut Window,
15077        cx: &mut Context<Self>,
15078    ) {
15079        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15080            self.inline_diagnostics_update = Task::ready(());
15081            self.inline_diagnostics.clear();
15082            return;
15083        }
15084
15085        let debounce_ms = ProjectSettings::get_global(cx)
15086            .diagnostics
15087            .inline
15088            .update_debounce_ms;
15089        let debounce = if debounce && debounce_ms > 0 {
15090            Some(Duration::from_millis(debounce_ms))
15091        } else {
15092            None
15093        };
15094        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15095            let editor = editor.upgrade().unwrap();
15096
15097            if let Some(debounce) = debounce {
15098                cx.background_executor().timer(debounce).await;
15099            }
15100            let Some(snapshot) = editor
15101                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15102                .ok()
15103            else {
15104                return;
15105            };
15106
15107            let new_inline_diagnostics = cx
15108                .background_spawn(async move {
15109                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15110                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15111                        let message = diagnostic_entry
15112                            .diagnostic
15113                            .message
15114                            .split_once('\n')
15115                            .map(|(line, _)| line)
15116                            .map(SharedString::new)
15117                            .unwrap_or_else(|| {
15118                                SharedString::from(diagnostic_entry.diagnostic.message)
15119                            });
15120                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15121                        let (Ok(i) | Err(i)) = inline_diagnostics
15122                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15123                        inline_diagnostics.insert(
15124                            i,
15125                            (
15126                                start_anchor,
15127                                InlineDiagnostic {
15128                                    message,
15129                                    group_id: diagnostic_entry.diagnostic.group_id,
15130                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15131                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15132                                    severity: diagnostic_entry.diagnostic.severity,
15133                                },
15134                            ),
15135                        );
15136                    }
15137                    inline_diagnostics
15138                })
15139                .await;
15140
15141            editor
15142                .update(cx, |editor, cx| {
15143                    editor.inline_diagnostics = new_inline_diagnostics;
15144                    cx.notify();
15145                })
15146                .ok();
15147        });
15148    }
15149
15150    pub fn set_selections_from_remote(
15151        &mut self,
15152        selections: Vec<Selection<Anchor>>,
15153        pending_selection: Option<Selection<Anchor>>,
15154        window: &mut Window,
15155        cx: &mut Context<Self>,
15156    ) {
15157        let old_cursor_position = self.selections.newest_anchor().head();
15158        self.selections.change_with(cx, |s| {
15159            s.select_anchors(selections);
15160            if let Some(pending_selection) = pending_selection {
15161                s.set_pending(pending_selection, SelectMode::Character);
15162            } else {
15163                s.clear_pending();
15164            }
15165        });
15166        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15167    }
15168
15169    fn push_to_selection_history(&mut self) {
15170        self.selection_history.push(SelectionHistoryEntry {
15171            selections: self.selections.disjoint_anchors(),
15172            select_next_state: self.select_next_state.clone(),
15173            select_prev_state: self.select_prev_state.clone(),
15174            add_selections_state: self.add_selections_state.clone(),
15175        });
15176    }
15177
15178    pub fn transact(
15179        &mut self,
15180        window: &mut Window,
15181        cx: &mut Context<Self>,
15182        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15183    ) -> Option<TransactionId> {
15184        self.start_transaction_at(Instant::now(), window, cx);
15185        update(self, window, cx);
15186        self.end_transaction_at(Instant::now(), cx)
15187    }
15188
15189    pub fn start_transaction_at(
15190        &mut self,
15191        now: Instant,
15192        window: &mut Window,
15193        cx: &mut Context<Self>,
15194    ) {
15195        self.end_selection(window, cx);
15196        if let Some(tx_id) = self
15197            .buffer
15198            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15199        {
15200            self.selection_history
15201                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15202            cx.emit(EditorEvent::TransactionBegun {
15203                transaction_id: tx_id,
15204            })
15205        }
15206    }
15207
15208    pub fn end_transaction_at(
15209        &mut self,
15210        now: Instant,
15211        cx: &mut Context<Self>,
15212    ) -> Option<TransactionId> {
15213        if let Some(transaction_id) = self
15214            .buffer
15215            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15216        {
15217            if let Some((_, end_selections)) =
15218                self.selection_history.transaction_mut(transaction_id)
15219            {
15220                *end_selections = Some(self.selections.disjoint_anchors());
15221            } else {
15222                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15223            }
15224
15225            cx.emit(EditorEvent::Edited { transaction_id });
15226            Some(transaction_id)
15227        } else {
15228            None
15229        }
15230    }
15231
15232    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15233        if self.selection_mark_mode {
15234            self.change_selections(None, window, cx, |s| {
15235                s.move_with(|_, sel| {
15236                    sel.collapse_to(sel.head(), SelectionGoal::None);
15237                });
15238            })
15239        }
15240        self.selection_mark_mode = true;
15241        cx.notify();
15242    }
15243
15244    pub fn swap_selection_ends(
15245        &mut self,
15246        _: &actions::SwapSelectionEnds,
15247        window: &mut Window,
15248        cx: &mut Context<Self>,
15249    ) {
15250        self.change_selections(None, window, cx, |s| {
15251            s.move_with(|_, sel| {
15252                if sel.start != sel.end {
15253                    sel.reversed = !sel.reversed
15254                }
15255            });
15256        });
15257        self.request_autoscroll(Autoscroll::newest(), cx);
15258        cx.notify();
15259    }
15260
15261    pub fn toggle_fold(
15262        &mut self,
15263        _: &actions::ToggleFold,
15264        window: &mut Window,
15265        cx: &mut Context<Self>,
15266    ) {
15267        if self.is_singleton(cx) {
15268            let selection = self.selections.newest::<Point>(cx);
15269
15270            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15271            let range = if selection.is_empty() {
15272                let point = selection.head().to_display_point(&display_map);
15273                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15274                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15275                    .to_point(&display_map);
15276                start..end
15277            } else {
15278                selection.range()
15279            };
15280            if display_map.folds_in_range(range).next().is_some() {
15281                self.unfold_lines(&Default::default(), window, cx)
15282            } else {
15283                self.fold(&Default::default(), window, cx)
15284            }
15285        } else {
15286            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15287            let buffer_ids: HashSet<_> = self
15288                .selections
15289                .disjoint_anchor_ranges()
15290                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15291                .collect();
15292
15293            let should_unfold = buffer_ids
15294                .iter()
15295                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15296
15297            for buffer_id in buffer_ids {
15298                if should_unfold {
15299                    self.unfold_buffer(buffer_id, cx);
15300                } else {
15301                    self.fold_buffer(buffer_id, cx);
15302                }
15303            }
15304        }
15305    }
15306
15307    pub fn toggle_fold_recursive(
15308        &mut self,
15309        _: &actions::ToggleFoldRecursive,
15310        window: &mut Window,
15311        cx: &mut Context<Self>,
15312    ) {
15313        let selection = self.selections.newest::<Point>(cx);
15314
15315        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15316        let range = if selection.is_empty() {
15317            let point = selection.head().to_display_point(&display_map);
15318            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15319            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15320                .to_point(&display_map);
15321            start..end
15322        } else {
15323            selection.range()
15324        };
15325        if display_map.folds_in_range(range).next().is_some() {
15326            self.unfold_recursive(&Default::default(), window, cx)
15327        } else {
15328            self.fold_recursive(&Default::default(), window, cx)
15329        }
15330    }
15331
15332    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15333        if self.is_singleton(cx) {
15334            let mut to_fold = Vec::new();
15335            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15336            let selections = self.selections.all_adjusted(cx);
15337
15338            for selection in selections {
15339                let range = selection.range().sorted();
15340                let buffer_start_row = range.start.row;
15341
15342                if range.start.row != range.end.row {
15343                    let mut found = false;
15344                    let mut row = range.start.row;
15345                    while row <= range.end.row {
15346                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15347                        {
15348                            found = true;
15349                            row = crease.range().end.row + 1;
15350                            to_fold.push(crease);
15351                        } else {
15352                            row += 1
15353                        }
15354                    }
15355                    if found {
15356                        continue;
15357                    }
15358                }
15359
15360                for row in (0..=range.start.row).rev() {
15361                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15362                        if crease.range().end.row >= buffer_start_row {
15363                            to_fold.push(crease);
15364                            if row <= range.start.row {
15365                                break;
15366                            }
15367                        }
15368                    }
15369                }
15370            }
15371
15372            self.fold_creases(to_fold, true, window, cx);
15373        } else {
15374            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15375            let buffer_ids = self
15376                .selections
15377                .disjoint_anchor_ranges()
15378                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15379                .collect::<HashSet<_>>();
15380            for buffer_id in buffer_ids {
15381                self.fold_buffer(buffer_id, cx);
15382            }
15383        }
15384    }
15385
15386    fn fold_at_level(
15387        &mut self,
15388        fold_at: &FoldAtLevel,
15389        window: &mut Window,
15390        cx: &mut Context<Self>,
15391    ) {
15392        if !self.buffer.read(cx).is_singleton() {
15393            return;
15394        }
15395
15396        let fold_at_level = fold_at.0;
15397        let snapshot = self.buffer.read(cx).snapshot(cx);
15398        let mut to_fold = Vec::new();
15399        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15400
15401        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15402            while start_row < end_row {
15403                match self
15404                    .snapshot(window, cx)
15405                    .crease_for_buffer_row(MultiBufferRow(start_row))
15406                {
15407                    Some(crease) => {
15408                        let nested_start_row = crease.range().start.row + 1;
15409                        let nested_end_row = crease.range().end.row;
15410
15411                        if current_level < fold_at_level {
15412                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15413                        } else if current_level == fold_at_level {
15414                            to_fold.push(crease);
15415                        }
15416
15417                        start_row = nested_end_row + 1;
15418                    }
15419                    None => start_row += 1,
15420                }
15421            }
15422        }
15423
15424        self.fold_creases(to_fold, true, window, cx);
15425    }
15426
15427    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15428        if self.buffer.read(cx).is_singleton() {
15429            let mut fold_ranges = Vec::new();
15430            let snapshot = self.buffer.read(cx).snapshot(cx);
15431
15432            for row in 0..snapshot.max_row().0 {
15433                if let Some(foldable_range) = self
15434                    .snapshot(window, cx)
15435                    .crease_for_buffer_row(MultiBufferRow(row))
15436                {
15437                    fold_ranges.push(foldable_range);
15438                }
15439            }
15440
15441            self.fold_creases(fold_ranges, true, window, cx);
15442        } else {
15443            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15444                editor
15445                    .update_in(cx, |editor, _, cx| {
15446                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15447                            editor.fold_buffer(buffer_id, cx);
15448                        }
15449                    })
15450                    .ok();
15451            });
15452        }
15453    }
15454
15455    pub fn fold_function_bodies(
15456        &mut self,
15457        _: &actions::FoldFunctionBodies,
15458        window: &mut Window,
15459        cx: &mut Context<Self>,
15460    ) {
15461        let snapshot = self.buffer.read(cx).snapshot(cx);
15462
15463        let ranges = snapshot
15464            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15465            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15466            .collect::<Vec<_>>();
15467
15468        let creases = ranges
15469            .into_iter()
15470            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15471            .collect();
15472
15473        self.fold_creases(creases, true, window, cx);
15474    }
15475
15476    pub fn fold_recursive(
15477        &mut self,
15478        _: &actions::FoldRecursive,
15479        window: &mut Window,
15480        cx: &mut Context<Self>,
15481    ) {
15482        let mut to_fold = Vec::new();
15483        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15484        let selections = self.selections.all_adjusted(cx);
15485
15486        for selection in selections {
15487            let range = selection.range().sorted();
15488            let buffer_start_row = range.start.row;
15489
15490            if range.start.row != range.end.row {
15491                let mut found = false;
15492                for row in range.start.row..=range.end.row {
15493                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15494                        found = true;
15495                        to_fold.push(crease);
15496                    }
15497                }
15498                if found {
15499                    continue;
15500                }
15501            }
15502
15503            for row in (0..=range.start.row).rev() {
15504                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15505                    if crease.range().end.row >= buffer_start_row {
15506                        to_fold.push(crease);
15507                    } else {
15508                        break;
15509                    }
15510                }
15511            }
15512        }
15513
15514        self.fold_creases(to_fold, true, window, cx);
15515    }
15516
15517    pub fn fold_at(
15518        &mut self,
15519        buffer_row: MultiBufferRow,
15520        window: &mut Window,
15521        cx: &mut Context<Self>,
15522    ) {
15523        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15524
15525        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15526            let autoscroll = self
15527                .selections
15528                .all::<Point>(cx)
15529                .iter()
15530                .any(|selection| crease.range().overlaps(&selection.range()));
15531
15532            self.fold_creases(vec![crease], autoscroll, window, cx);
15533        }
15534    }
15535
15536    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15537        if self.is_singleton(cx) {
15538            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15539            let buffer = &display_map.buffer_snapshot;
15540            let selections = self.selections.all::<Point>(cx);
15541            let ranges = selections
15542                .iter()
15543                .map(|s| {
15544                    let range = s.display_range(&display_map).sorted();
15545                    let mut start = range.start.to_point(&display_map);
15546                    let mut end = range.end.to_point(&display_map);
15547                    start.column = 0;
15548                    end.column = buffer.line_len(MultiBufferRow(end.row));
15549                    start..end
15550                })
15551                .collect::<Vec<_>>();
15552
15553            self.unfold_ranges(&ranges, true, true, cx);
15554        } else {
15555            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15556            let buffer_ids = self
15557                .selections
15558                .disjoint_anchor_ranges()
15559                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15560                .collect::<HashSet<_>>();
15561            for buffer_id in buffer_ids {
15562                self.unfold_buffer(buffer_id, cx);
15563            }
15564        }
15565    }
15566
15567    pub fn unfold_recursive(
15568        &mut self,
15569        _: &UnfoldRecursive,
15570        _window: &mut Window,
15571        cx: &mut Context<Self>,
15572    ) {
15573        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15574        let selections = self.selections.all::<Point>(cx);
15575        let ranges = selections
15576            .iter()
15577            .map(|s| {
15578                let mut range = s.display_range(&display_map).sorted();
15579                *range.start.column_mut() = 0;
15580                *range.end.column_mut() = display_map.line_len(range.end.row());
15581                let start = range.start.to_point(&display_map);
15582                let end = range.end.to_point(&display_map);
15583                start..end
15584            })
15585            .collect::<Vec<_>>();
15586
15587        self.unfold_ranges(&ranges, true, true, cx);
15588    }
15589
15590    pub fn unfold_at(
15591        &mut self,
15592        buffer_row: MultiBufferRow,
15593        _window: &mut Window,
15594        cx: &mut Context<Self>,
15595    ) {
15596        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15597
15598        let intersection_range = Point::new(buffer_row.0, 0)
15599            ..Point::new(
15600                buffer_row.0,
15601                display_map.buffer_snapshot.line_len(buffer_row),
15602            );
15603
15604        let autoscroll = self
15605            .selections
15606            .all::<Point>(cx)
15607            .iter()
15608            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15609
15610        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15611    }
15612
15613    pub fn unfold_all(
15614        &mut self,
15615        _: &actions::UnfoldAll,
15616        _window: &mut Window,
15617        cx: &mut Context<Self>,
15618    ) {
15619        if self.buffer.read(cx).is_singleton() {
15620            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15621            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15622        } else {
15623            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15624                editor
15625                    .update(cx, |editor, cx| {
15626                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15627                            editor.unfold_buffer(buffer_id, cx);
15628                        }
15629                    })
15630                    .ok();
15631            });
15632        }
15633    }
15634
15635    pub fn fold_selected_ranges(
15636        &mut self,
15637        _: &FoldSelectedRanges,
15638        window: &mut Window,
15639        cx: &mut Context<Self>,
15640    ) {
15641        let selections = self.selections.all_adjusted(cx);
15642        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15643        let ranges = selections
15644            .into_iter()
15645            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15646            .collect::<Vec<_>>();
15647        self.fold_creases(ranges, true, window, cx);
15648    }
15649
15650    pub fn fold_ranges<T: ToOffset + Clone>(
15651        &mut self,
15652        ranges: Vec<Range<T>>,
15653        auto_scroll: bool,
15654        window: &mut Window,
15655        cx: &mut Context<Self>,
15656    ) {
15657        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15658        let ranges = ranges
15659            .into_iter()
15660            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15661            .collect::<Vec<_>>();
15662        self.fold_creases(ranges, auto_scroll, window, cx);
15663    }
15664
15665    pub fn fold_creases<T: ToOffset + Clone>(
15666        &mut self,
15667        creases: Vec<Crease<T>>,
15668        auto_scroll: bool,
15669        _window: &mut Window,
15670        cx: &mut Context<Self>,
15671    ) {
15672        if creases.is_empty() {
15673            return;
15674        }
15675
15676        let mut buffers_affected = HashSet::default();
15677        let multi_buffer = self.buffer().read(cx);
15678        for crease in &creases {
15679            if let Some((_, buffer, _)) =
15680                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15681            {
15682                buffers_affected.insert(buffer.read(cx).remote_id());
15683            };
15684        }
15685
15686        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15687
15688        if auto_scroll {
15689            self.request_autoscroll(Autoscroll::fit(), cx);
15690        }
15691
15692        cx.notify();
15693
15694        self.scrollbar_marker_state.dirty = true;
15695        self.folds_did_change(cx);
15696    }
15697
15698    /// Removes any folds whose ranges intersect any of the given ranges.
15699    pub fn unfold_ranges<T: ToOffset + Clone>(
15700        &mut self,
15701        ranges: &[Range<T>],
15702        inclusive: bool,
15703        auto_scroll: bool,
15704        cx: &mut Context<Self>,
15705    ) {
15706        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15707            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15708        });
15709        self.folds_did_change(cx);
15710    }
15711
15712    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15713        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15714            return;
15715        }
15716        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15717        self.display_map.update(cx, |display_map, cx| {
15718            display_map.fold_buffers([buffer_id], cx)
15719        });
15720        cx.emit(EditorEvent::BufferFoldToggled {
15721            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15722            folded: true,
15723        });
15724        cx.notify();
15725    }
15726
15727    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15728        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15729            return;
15730        }
15731        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15732        self.display_map.update(cx, |display_map, cx| {
15733            display_map.unfold_buffers([buffer_id], cx);
15734        });
15735        cx.emit(EditorEvent::BufferFoldToggled {
15736            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15737            folded: false,
15738        });
15739        cx.notify();
15740    }
15741
15742    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15743        self.display_map.read(cx).is_buffer_folded(buffer)
15744    }
15745
15746    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15747        self.display_map.read(cx).folded_buffers()
15748    }
15749
15750    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15751        self.display_map.update(cx, |display_map, cx| {
15752            display_map.disable_header_for_buffer(buffer_id, cx);
15753        });
15754        cx.notify();
15755    }
15756
15757    /// Removes any folds with the given ranges.
15758    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15759        &mut self,
15760        ranges: &[Range<T>],
15761        type_id: TypeId,
15762        auto_scroll: bool,
15763        cx: &mut Context<Self>,
15764    ) {
15765        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15766            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15767        });
15768        self.folds_did_change(cx);
15769    }
15770
15771    fn remove_folds_with<T: ToOffset + Clone>(
15772        &mut self,
15773        ranges: &[Range<T>],
15774        auto_scroll: bool,
15775        cx: &mut Context<Self>,
15776        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15777    ) {
15778        if ranges.is_empty() {
15779            return;
15780        }
15781
15782        let mut buffers_affected = HashSet::default();
15783        let multi_buffer = self.buffer().read(cx);
15784        for range in ranges {
15785            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15786                buffers_affected.insert(buffer.read(cx).remote_id());
15787            };
15788        }
15789
15790        self.display_map.update(cx, update);
15791
15792        if auto_scroll {
15793            self.request_autoscroll(Autoscroll::fit(), cx);
15794        }
15795
15796        cx.notify();
15797        self.scrollbar_marker_state.dirty = true;
15798        self.active_indent_guides_state.dirty = true;
15799    }
15800
15801    pub fn update_fold_widths(
15802        &mut self,
15803        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15804        cx: &mut Context<Self>,
15805    ) -> bool {
15806        self.display_map
15807            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15808    }
15809
15810    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15811        self.display_map.read(cx).fold_placeholder.clone()
15812    }
15813
15814    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15815        self.buffer.update(cx, |buffer, cx| {
15816            buffer.set_all_diff_hunks_expanded(cx);
15817        });
15818    }
15819
15820    pub fn expand_all_diff_hunks(
15821        &mut self,
15822        _: &ExpandAllDiffHunks,
15823        _window: &mut Window,
15824        cx: &mut Context<Self>,
15825    ) {
15826        self.buffer.update(cx, |buffer, cx| {
15827            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15828        });
15829    }
15830
15831    pub fn toggle_selected_diff_hunks(
15832        &mut self,
15833        _: &ToggleSelectedDiffHunks,
15834        _window: &mut Window,
15835        cx: &mut Context<Self>,
15836    ) {
15837        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15838        self.toggle_diff_hunks_in_ranges(ranges, cx);
15839    }
15840
15841    pub fn diff_hunks_in_ranges<'a>(
15842        &'a self,
15843        ranges: &'a [Range<Anchor>],
15844        buffer: &'a MultiBufferSnapshot,
15845    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15846        ranges.iter().flat_map(move |range| {
15847            let end_excerpt_id = range.end.excerpt_id;
15848            let range = range.to_point(buffer);
15849            let mut peek_end = range.end;
15850            if range.end.row < buffer.max_row().0 {
15851                peek_end = Point::new(range.end.row + 1, 0);
15852            }
15853            buffer
15854                .diff_hunks_in_range(range.start..peek_end)
15855                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15856        })
15857    }
15858
15859    pub fn has_stageable_diff_hunks_in_ranges(
15860        &self,
15861        ranges: &[Range<Anchor>],
15862        snapshot: &MultiBufferSnapshot,
15863    ) -> bool {
15864        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15865        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15866    }
15867
15868    pub fn toggle_staged_selected_diff_hunks(
15869        &mut self,
15870        _: &::git::ToggleStaged,
15871        _: &mut Window,
15872        cx: &mut Context<Self>,
15873    ) {
15874        let snapshot = self.buffer.read(cx).snapshot(cx);
15875        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15876        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15877        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15878    }
15879
15880    pub fn set_render_diff_hunk_controls(
15881        &mut self,
15882        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15883        cx: &mut Context<Self>,
15884    ) {
15885        self.render_diff_hunk_controls = render_diff_hunk_controls;
15886        cx.notify();
15887    }
15888
15889    pub fn stage_and_next(
15890        &mut self,
15891        _: &::git::StageAndNext,
15892        window: &mut Window,
15893        cx: &mut Context<Self>,
15894    ) {
15895        self.do_stage_or_unstage_and_next(true, window, cx);
15896    }
15897
15898    pub fn unstage_and_next(
15899        &mut self,
15900        _: &::git::UnstageAndNext,
15901        window: &mut Window,
15902        cx: &mut Context<Self>,
15903    ) {
15904        self.do_stage_or_unstage_and_next(false, window, cx);
15905    }
15906
15907    pub fn stage_or_unstage_diff_hunks(
15908        &mut self,
15909        stage: bool,
15910        ranges: Vec<Range<Anchor>>,
15911        cx: &mut Context<Self>,
15912    ) {
15913        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15914        cx.spawn(async move |this, cx| {
15915            task.await?;
15916            this.update(cx, |this, cx| {
15917                let snapshot = this.buffer.read(cx).snapshot(cx);
15918                let chunk_by = this
15919                    .diff_hunks_in_ranges(&ranges, &snapshot)
15920                    .chunk_by(|hunk| hunk.buffer_id);
15921                for (buffer_id, hunks) in &chunk_by {
15922                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15923                }
15924            })
15925        })
15926        .detach_and_log_err(cx);
15927    }
15928
15929    fn save_buffers_for_ranges_if_needed(
15930        &mut self,
15931        ranges: &[Range<Anchor>],
15932        cx: &mut Context<Editor>,
15933    ) -> Task<Result<()>> {
15934        let multibuffer = self.buffer.read(cx);
15935        let snapshot = multibuffer.read(cx);
15936        let buffer_ids: HashSet<_> = ranges
15937            .iter()
15938            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15939            .collect();
15940        drop(snapshot);
15941
15942        let mut buffers = HashSet::default();
15943        for buffer_id in buffer_ids {
15944            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15945                let buffer = buffer_entity.read(cx);
15946                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15947                {
15948                    buffers.insert(buffer_entity);
15949                }
15950            }
15951        }
15952
15953        if let Some(project) = &self.project {
15954            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15955        } else {
15956            Task::ready(Ok(()))
15957        }
15958    }
15959
15960    fn do_stage_or_unstage_and_next(
15961        &mut self,
15962        stage: bool,
15963        window: &mut Window,
15964        cx: &mut Context<Self>,
15965    ) {
15966        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15967
15968        if ranges.iter().any(|range| range.start != range.end) {
15969            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15970            return;
15971        }
15972
15973        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15974        let snapshot = self.snapshot(window, cx);
15975        let position = self.selections.newest::<Point>(cx).head();
15976        let mut row = snapshot
15977            .buffer_snapshot
15978            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15979            .find(|hunk| hunk.row_range.start.0 > position.row)
15980            .map(|hunk| hunk.row_range.start);
15981
15982        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15983        // Outside of the project diff editor, wrap around to the beginning.
15984        if !all_diff_hunks_expanded {
15985            row = row.or_else(|| {
15986                snapshot
15987                    .buffer_snapshot
15988                    .diff_hunks_in_range(Point::zero()..position)
15989                    .find(|hunk| hunk.row_range.end.0 < position.row)
15990                    .map(|hunk| hunk.row_range.start)
15991            });
15992        }
15993
15994        if let Some(row) = row {
15995            let destination = Point::new(row.0, 0);
15996            let autoscroll = Autoscroll::center();
15997
15998            self.unfold_ranges(&[destination..destination], false, false, cx);
15999            self.change_selections(Some(autoscroll), window, cx, |s| {
16000                s.select_ranges([destination..destination]);
16001            });
16002        }
16003    }
16004
16005    fn do_stage_or_unstage(
16006        &self,
16007        stage: bool,
16008        buffer_id: BufferId,
16009        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16010        cx: &mut App,
16011    ) -> Option<()> {
16012        let project = self.project.as_ref()?;
16013        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16014        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16015        let buffer_snapshot = buffer.read(cx).snapshot();
16016        let file_exists = buffer_snapshot
16017            .file()
16018            .is_some_and(|file| file.disk_state().exists());
16019        diff.update(cx, |diff, cx| {
16020            diff.stage_or_unstage_hunks(
16021                stage,
16022                &hunks
16023                    .map(|hunk| buffer_diff::DiffHunk {
16024                        buffer_range: hunk.buffer_range,
16025                        diff_base_byte_range: hunk.diff_base_byte_range,
16026                        secondary_status: hunk.secondary_status,
16027                        range: Point::zero()..Point::zero(), // unused
16028                    })
16029                    .collect::<Vec<_>>(),
16030                &buffer_snapshot,
16031                file_exists,
16032                cx,
16033            )
16034        });
16035        None
16036    }
16037
16038    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16039        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16040        self.buffer
16041            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16042    }
16043
16044    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16045        self.buffer.update(cx, |buffer, cx| {
16046            let ranges = vec![Anchor::min()..Anchor::max()];
16047            if !buffer.all_diff_hunks_expanded()
16048                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16049            {
16050                buffer.collapse_diff_hunks(ranges, cx);
16051                true
16052            } else {
16053                false
16054            }
16055        })
16056    }
16057
16058    fn toggle_diff_hunks_in_ranges(
16059        &mut self,
16060        ranges: Vec<Range<Anchor>>,
16061        cx: &mut Context<Editor>,
16062    ) {
16063        self.buffer.update(cx, |buffer, cx| {
16064            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16065            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16066        })
16067    }
16068
16069    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16070        self.buffer.update(cx, |buffer, cx| {
16071            let snapshot = buffer.snapshot(cx);
16072            let excerpt_id = range.end.excerpt_id;
16073            let point_range = range.to_point(&snapshot);
16074            let expand = !buffer.single_hunk_is_expanded(range, cx);
16075            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16076        })
16077    }
16078
16079    pub(crate) fn apply_all_diff_hunks(
16080        &mut self,
16081        _: &ApplyAllDiffHunks,
16082        window: &mut Window,
16083        cx: &mut Context<Self>,
16084    ) {
16085        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16086
16087        let buffers = self.buffer.read(cx).all_buffers();
16088        for branch_buffer in buffers {
16089            branch_buffer.update(cx, |branch_buffer, cx| {
16090                branch_buffer.merge_into_base(Vec::new(), cx);
16091            });
16092        }
16093
16094        if let Some(project) = self.project.clone() {
16095            self.save(true, project, window, cx).detach_and_log_err(cx);
16096        }
16097    }
16098
16099    pub(crate) fn apply_selected_diff_hunks(
16100        &mut self,
16101        _: &ApplyDiffHunk,
16102        window: &mut Window,
16103        cx: &mut Context<Self>,
16104    ) {
16105        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16106        let snapshot = self.snapshot(window, cx);
16107        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16108        let mut ranges_by_buffer = HashMap::default();
16109        self.transact(window, cx, |editor, _window, cx| {
16110            for hunk in hunks {
16111                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16112                    ranges_by_buffer
16113                        .entry(buffer.clone())
16114                        .or_insert_with(Vec::new)
16115                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16116                }
16117            }
16118
16119            for (buffer, ranges) in ranges_by_buffer {
16120                buffer.update(cx, |buffer, cx| {
16121                    buffer.merge_into_base(ranges, cx);
16122                });
16123            }
16124        });
16125
16126        if let Some(project) = self.project.clone() {
16127            self.save(true, project, window, cx).detach_and_log_err(cx);
16128        }
16129    }
16130
16131    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16132        if hovered != self.gutter_hovered {
16133            self.gutter_hovered = hovered;
16134            cx.notify();
16135        }
16136    }
16137
16138    pub fn insert_blocks(
16139        &mut self,
16140        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16141        autoscroll: Option<Autoscroll>,
16142        cx: &mut Context<Self>,
16143    ) -> Vec<CustomBlockId> {
16144        let blocks = self
16145            .display_map
16146            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16147        if let Some(autoscroll) = autoscroll {
16148            self.request_autoscroll(autoscroll, cx);
16149        }
16150        cx.notify();
16151        blocks
16152    }
16153
16154    pub fn resize_blocks(
16155        &mut self,
16156        heights: HashMap<CustomBlockId, u32>,
16157        autoscroll: Option<Autoscroll>,
16158        cx: &mut Context<Self>,
16159    ) {
16160        self.display_map
16161            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16162        if let Some(autoscroll) = autoscroll {
16163            self.request_autoscroll(autoscroll, cx);
16164        }
16165        cx.notify();
16166    }
16167
16168    pub fn replace_blocks(
16169        &mut self,
16170        renderers: HashMap<CustomBlockId, RenderBlock>,
16171        autoscroll: Option<Autoscroll>,
16172        cx: &mut Context<Self>,
16173    ) {
16174        self.display_map
16175            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16176        if let Some(autoscroll) = autoscroll {
16177            self.request_autoscroll(autoscroll, cx);
16178        }
16179        cx.notify();
16180    }
16181
16182    pub fn remove_blocks(
16183        &mut self,
16184        block_ids: HashSet<CustomBlockId>,
16185        autoscroll: Option<Autoscroll>,
16186        cx: &mut Context<Self>,
16187    ) {
16188        self.display_map.update(cx, |display_map, cx| {
16189            display_map.remove_blocks(block_ids, cx)
16190        });
16191        if let Some(autoscroll) = autoscroll {
16192            self.request_autoscroll(autoscroll, cx);
16193        }
16194        cx.notify();
16195    }
16196
16197    pub fn row_for_block(
16198        &self,
16199        block_id: CustomBlockId,
16200        cx: &mut Context<Self>,
16201    ) -> Option<DisplayRow> {
16202        self.display_map
16203            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16204    }
16205
16206    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16207        self.focused_block = Some(focused_block);
16208    }
16209
16210    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16211        self.focused_block.take()
16212    }
16213
16214    pub fn insert_creases(
16215        &mut self,
16216        creases: impl IntoIterator<Item = Crease<Anchor>>,
16217        cx: &mut Context<Self>,
16218    ) -> Vec<CreaseId> {
16219        self.display_map
16220            .update(cx, |map, cx| map.insert_creases(creases, cx))
16221    }
16222
16223    pub fn remove_creases(
16224        &mut self,
16225        ids: impl IntoIterator<Item = CreaseId>,
16226        cx: &mut Context<Self>,
16227    ) -> Vec<(CreaseId, Range<Anchor>)> {
16228        self.display_map
16229            .update(cx, |map, cx| map.remove_creases(ids, cx))
16230    }
16231
16232    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16233        self.display_map
16234            .update(cx, |map, cx| map.snapshot(cx))
16235            .longest_row()
16236    }
16237
16238    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16239        self.display_map
16240            .update(cx, |map, cx| map.snapshot(cx))
16241            .max_point()
16242    }
16243
16244    pub fn text(&self, cx: &App) -> String {
16245        self.buffer.read(cx).read(cx).text()
16246    }
16247
16248    pub fn is_empty(&self, cx: &App) -> bool {
16249        self.buffer.read(cx).read(cx).is_empty()
16250    }
16251
16252    pub fn text_option(&self, cx: &App) -> Option<String> {
16253        let text = self.text(cx);
16254        let text = text.trim();
16255
16256        if text.is_empty() {
16257            return None;
16258        }
16259
16260        Some(text.to_string())
16261    }
16262
16263    pub fn set_text(
16264        &mut self,
16265        text: impl Into<Arc<str>>,
16266        window: &mut Window,
16267        cx: &mut Context<Self>,
16268    ) {
16269        self.transact(window, cx, |this, _, cx| {
16270            this.buffer
16271                .read(cx)
16272                .as_singleton()
16273                .expect("you can only call set_text on editors for singleton buffers")
16274                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16275        });
16276    }
16277
16278    pub fn display_text(&self, cx: &mut App) -> String {
16279        self.display_map
16280            .update(cx, |map, cx| map.snapshot(cx))
16281            .text()
16282    }
16283
16284    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16285        let mut wrap_guides = smallvec::smallvec![];
16286
16287        if self.show_wrap_guides == Some(false) {
16288            return wrap_guides;
16289        }
16290
16291        let settings = self.buffer.read(cx).language_settings(cx);
16292        if settings.show_wrap_guides {
16293            match self.soft_wrap_mode(cx) {
16294                SoftWrap::Column(soft_wrap) => {
16295                    wrap_guides.push((soft_wrap as usize, true));
16296                }
16297                SoftWrap::Bounded(soft_wrap) => {
16298                    wrap_guides.push((soft_wrap as usize, true));
16299                }
16300                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16301            }
16302            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16303        }
16304
16305        wrap_guides
16306    }
16307
16308    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16309        let settings = self.buffer.read(cx).language_settings(cx);
16310        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16311        match mode {
16312            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16313                SoftWrap::None
16314            }
16315            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16316            language_settings::SoftWrap::PreferredLineLength => {
16317                SoftWrap::Column(settings.preferred_line_length)
16318            }
16319            language_settings::SoftWrap::Bounded => {
16320                SoftWrap::Bounded(settings.preferred_line_length)
16321            }
16322        }
16323    }
16324
16325    pub fn set_soft_wrap_mode(
16326        &mut self,
16327        mode: language_settings::SoftWrap,
16328
16329        cx: &mut Context<Self>,
16330    ) {
16331        self.soft_wrap_mode_override = Some(mode);
16332        cx.notify();
16333    }
16334
16335    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16336        self.hard_wrap = hard_wrap;
16337        cx.notify();
16338    }
16339
16340    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16341        self.text_style_refinement = Some(style);
16342    }
16343
16344    /// called by the Element so we know what style we were most recently rendered with.
16345    pub(crate) fn set_style(
16346        &mut self,
16347        style: EditorStyle,
16348        window: &mut Window,
16349        cx: &mut Context<Self>,
16350    ) {
16351        let rem_size = window.rem_size();
16352        self.display_map.update(cx, |map, cx| {
16353            map.set_font(
16354                style.text.font(),
16355                style.text.font_size.to_pixels(rem_size),
16356                cx,
16357            )
16358        });
16359        self.style = Some(style);
16360    }
16361
16362    pub fn style(&self) -> Option<&EditorStyle> {
16363        self.style.as_ref()
16364    }
16365
16366    // Called by the element. This method is not designed to be called outside of the editor
16367    // element's layout code because it does not notify when rewrapping is computed synchronously.
16368    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16369        self.display_map
16370            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16371    }
16372
16373    pub fn set_soft_wrap(&mut self) {
16374        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16375    }
16376
16377    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16378        if self.soft_wrap_mode_override.is_some() {
16379            self.soft_wrap_mode_override.take();
16380        } else {
16381            let soft_wrap = match self.soft_wrap_mode(cx) {
16382                SoftWrap::GitDiff => return,
16383                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16384                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16385                    language_settings::SoftWrap::None
16386                }
16387            };
16388            self.soft_wrap_mode_override = Some(soft_wrap);
16389        }
16390        cx.notify();
16391    }
16392
16393    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16394        let Some(workspace) = self.workspace() else {
16395            return;
16396        };
16397        let fs = workspace.read(cx).app_state().fs.clone();
16398        let current_show = TabBarSettings::get_global(cx).show;
16399        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16400            setting.show = Some(!current_show);
16401        });
16402    }
16403
16404    pub fn toggle_indent_guides(
16405        &mut self,
16406        _: &ToggleIndentGuides,
16407        _: &mut Window,
16408        cx: &mut Context<Self>,
16409    ) {
16410        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16411            self.buffer
16412                .read(cx)
16413                .language_settings(cx)
16414                .indent_guides
16415                .enabled
16416        });
16417        self.show_indent_guides = Some(!currently_enabled);
16418        cx.notify();
16419    }
16420
16421    fn should_show_indent_guides(&self) -> Option<bool> {
16422        self.show_indent_guides
16423    }
16424
16425    pub fn toggle_line_numbers(
16426        &mut self,
16427        _: &ToggleLineNumbers,
16428        _: &mut Window,
16429        cx: &mut Context<Self>,
16430    ) {
16431        let mut editor_settings = EditorSettings::get_global(cx).clone();
16432        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16433        EditorSettings::override_global(editor_settings, cx);
16434    }
16435
16436    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16437        if let Some(show_line_numbers) = self.show_line_numbers {
16438            return show_line_numbers;
16439        }
16440        EditorSettings::get_global(cx).gutter.line_numbers
16441    }
16442
16443    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16444        self.use_relative_line_numbers
16445            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16446    }
16447
16448    pub fn toggle_relative_line_numbers(
16449        &mut self,
16450        _: &ToggleRelativeLineNumbers,
16451        _: &mut Window,
16452        cx: &mut Context<Self>,
16453    ) {
16454        let is_relative = self.should_use_relative_line_numbers(cx);
16455        self.set_relative_line_number(Some(!is_relative), cx)
16456    }
16457
16458    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16459        self.use_relative_line_numbers = is_relative;
16460        cx.notify();
16461    }
16462
16463    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16464        self.show_gutter = show_gutter;
16465        cx.notify();
16466    }
16467
16468    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16469        self.show_scrollbars = show_scrollbars;
16470        cx.notify();
16471    }
16472
16473    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16474        self.show_line_numbers = Some(show_line_numbers);
16475        cx.notify();
16476    }
16477
16478    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16479        self.disable_expand_excerpt_buttons = true;
16480        cx.notify();
16481    }
16482
16483    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16484        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16485        cx.notify();
16486    }
16487
16488    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16489        self.show_code_actions = Some(show_code_actions);
16490        cx.notify();
16491    }
16492
16493    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16494        self.show_runnables = Some(show_runnables);
16495        cx.notify();
16496    }
16497
16498    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16499        self.show_breakpoints = Some(show_breakpoints);
16500        cx.notify();
16501    }
16502
16503    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16504        if self.display_map.read(cx).masked != masked {
16505            self.display_map.update(cx, |map, _| map.masked = masked);
16506        }
16507        cx.notify()
16508    }
16509
16510    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16511        self.show_wrap_guides = Some(show_wrap_guides);
16512        cx.notify();
16513    }
16514
16515    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16516        self.show_indent_guides = Some(show_indent_guides);
16517        cx.notify();
16518    }
16519
16520    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16521        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16522            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16523                if let Some(dir) = file.abs_path(cx).parent() {
16524                    return Some(dir.to_owned());
16525                }
16526            }
16527
16528            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16529                return Some(project_path.path.to_path_buf());
16530            }
16531        }
16532
16533        None
16534    }
16535
16536    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16537        self.active_excerpt(cx)?
16538            .1
16539            .read(cx)
16540            .file()
16541            .and_then(|f| f.as_local())
16542    }
16543
16544    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16545        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16546            let buffer = buffer.read(cx);
16547            if let Some(project_path) = buffer.project_path(cx) {
16548                let project = self.project.as_ref()?.read(cx);
16549                project.absolute_path(&project_path, cx)
16550            } else {
16551                buffer
16552                    .file()
16553                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16554            }
16555        })
16556    }
16557
16558    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16559        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16560            let project_path = buffer.read(cx).project_path(cx)?;
16561            let project = self.project.as_ref()?.read(cx);
16562            let entry = project.entry_for_path(&project_path, cx)?;
16563            let path = entry.path.to_path_buf();
16564            Some(path)
16565        })
16566    }
16567
16568    pub fn reveal_in_finder(
16569        &mut self,
16570        _: &RevealInFileManager,
16571        _window: &mut Window,
16572        cx: &mut Context<Self>,
16573    ) {
16574        if let Some(target) = self.target_file(cx) {
16575            cx.reveal_path(&target.abs_path(cx));
16576        }
16577    }
16578
16579    pub fn copy_path(
16580        &mut self,
16581        _: &zed_actions::workspace::CopyPath,
16582        _window: &mut Window,
16583        cx: &mut Context<Self>,
16584    ) {
16585        if let Some(path) = self.target_file_abs_path(cx) {
16586            if let Some(path) = path.to_str() {
16587                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16588            }
16589        }
16590    }
16591
16592    pub fn copy_relative_path(
16593        &mut self,
16594        _: &zed_actions::workspace::CopyRelativePath,
16595        _window: &mut Window,
16596        cx: &mut Context<Self>,
16597    ) {
16598        if let Some(path) = self.target_file_path(cx) {
16599            if let Some(path) = path.to_str() {
16600                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16601            }
16602        }
16603    }
16604
16605    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16606        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16607            buffer.read(cx).project_path(cx)
16608        } else {
16609            None
16610        }
16611    }
16612
16613    // Returns true if the editor handled a go-to-line request
16614    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16615        maybe!({
16616            let breakpoint_store = self.breakpoint_store.as_ref()?;
16617
16618            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16619            else {
16620                self.clear_row_highlights::<ActiveDebugLine>();
16621                return None;
16622            };
16623
16624            let position = active_stack_frame.position;
16625            let buffer_id = position.buffer_id?;
16626            let snapshot = self
16627                .project
16628                .as_ref()?
16629                .read(cx)
16630                .buffer_for_id(buffer_id, cx)?
16631                .read(cx)
16632                .snapshot();
16633
16634            let mut handled = false;
16635            for (id, ExcerptRange { context, .. }) in
16636                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16637            {
16638                if context.start.cmp(&position, &snapshot).is_ge()
16639                    || context.end.cmp(&position, &snapshot).is_lt()
16640                {
16641                    continue;
16642                }
16643                let snapshot = self.buffer.read(cx).snapshot(cx);
16644                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16645
16646                handled = true;
16647                self.clear_row_highlights::<ActiveDebugLine>();
16648                self.go_to_line::<ActiveDebugLine>(
16649                    multibuffer_anchor,
16650                    Some(cx.theme().colors().editor_debugger_active_line_background),
16651                    window,
16652                    cx,
16653                );
16654
16655                cx.notify();
16656            }
16657
16658            handled.then_some(())
16659        })
16660        .is_some()
16661    }
16662
16663    pub fn copy_file_name_without_extension(
16664        &mut self,
16665        _: &CopyFileNameWithoutExtension,
16666        _: &mut Window,
16667        cx: &mut Context<Self>,
16668    ) {
16669        if let Some(file) = self.target_file(cx) {
16670            if let Some(file_stem) = file.path().file_stem() {
16671                if let Some(name) = file_stem.to_str() {
16672                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16673                }
16674            }
16675        }
16676    }
16677
16678    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16679        if let Some(file) = self.target_file(cx) {
16680            if let Some(file_name) = file.path().file_name() {
16681                if let Some(name) = file_name.to_str() {
16682                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16683                }
16684            }
16685        }
16686    }
16687
16688    pub fn toggle_git_blame(
16689        &mut self,
16690        _: &::git::Blame,
16691        window: &mut Window,
16692        cx: &mut Context<Self>,
16693    ) {
16694        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16695
16696        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16697            self.start_git_blame(true, window, cx);
16698        }
16699
16700        cx.notify();
16701    }
16702
16703    pub fn toggle_git_blame_inline(
16704        &mut self,
16705        _: &ToggleGitBlameInline,
16706        window: &mut Window,
16707        cx: &mut Context<Self>,
16708    ) {
16709        self.toggle_git_blame_inline_internal(true, window, cx);
16710        cx.notify();
16711    }
16712
16713    pub fn open_git_blame_commit(
16714        &mut self,
16715        _: &OpenGitBlameCommit,
16716        window: &mut Window,
16717        cx: &mut Context<Self>,
16718    ) {
16719        self.open_git_blame_commit_internal(window, cx);
16720    }
16721
16722    fn open_git_blame_commit_internal(
16723        &mut self,
16724        window: &mut Window,
16725        cx: &mut Context<Self>,
16726    ) -> Option<()> {
16727        let blame = self.blame.as_ref()?;
16728        let snapshot = self.snapshot(window, cx);
16729        let cursor = self.selections.newest::<Point>(cx).head();
16730        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16731        let blame_entry = blame
16732            .update(cx, |blame, cx| {
16733                blame
16734                    .blame_for_rows(
16735                        &[RowInfo {
16736                            buffer_id: Some(buffer.remote_id()),
16737                            buffer_row: Some(point.row),
16738                            ..Default::default()
16739                        }],
16740                        cx,
16741                    )
16742                    .next()
16743            })
16744            .flatten()?;
16745        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16746        let repo = blame.read(cx).repository(cx)?;
16747        let workspace = self.workspace()?.downgrade();
16748        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16749        None
16750    }
16751
16752    pub fn git_blame_inline_enabled(&self) -> bool {
16753        self.git_blame_inline_enabled
16754    }
16755
16756    pub fn toggle_selection_menu(
16757        &mut self,
16758        _: &ToggleSelectionMenu,
16759        _: &mut Window,
16760        cx: &mut Context<Self>,
16761    ) {
16762        self.show_selection_menu = self
16763            .show_selection_menu
16764            .map(|show_selections_menu| !show_selections_menu)
16765            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16766
16767        cx.notify();
16768    }
16769
16770    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16771        self.show_selection_menu
16772            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16773    }
16774
16775    fn start_git_blame(
16776        &mut self,
16777        user_triggered: bool,
16778        window: &mut Window,
16779        cx: &mut Context<Self>,
16780    ) {
16781        if let Some(project) = self.project.as_ref() {
16782            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16783                return;
16784            };
16785
16786            if buffer.read(cx).file().is_none() {
16787                return;
16788            }
16789
16790            let focused = self.focus_handle(cx).contains_focused(window, cx);
16791
16792            let project = project.clone();
16793            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16794            self.blame_subscription =
16795                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16796            self.blame = Some(blame);
16797        }
16798    }
16799
16800    fn toggle_git_blame_inline_internal(
16801        &mut self,
16802        user_triggered: bool,
16803        window: &mut Window,
16804        cx: &mut Context<Self>,
16805    ) {
16806        if self.git_blame_inline_enabled {
16807            self.git_blame_inline_enabled = false;
16808            self.show_git_blame_inline = false;
16809            self.show_git_blame_inline_delay_task.take();
16810        } else {
16811            self.git_blame_inline_enabled = true;
16812            self.start_git_blame_inline(user_triggered, window, cx);
16813        }
16814
16815        cx.notify();
16816    }
16817
16818    fn start_git_blame_inline(
16819        &mut self,
16820        user_triggered: bool,
16821        window: &mut Window,
16822        cx: &mut Context<Self>,
16823    ) {
16824        self.start_git_blame(user_triggered, window, cx);
16825
16826        if ProjectSettings::get_global(cx)
16827            .git
16828            .inline_blame_delay()
16829            .is_some()
16830        {
16831            self.start_inline_blame_timer(window, cx);
16832        } else {
16833            self.show_git_blame_inline = true
16834        }
16835    }
16836
16837    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16838        self.blame.as_ref()
16839    }
16840
16841    pub fn show_git_blame_gutter(&self) -> bool {
16842        self.show_git_blame_gutter
16843    }
16844
16845    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16846        self.show_git_blame_gutter && self.has_blame_entries(cx)
16847    }
16848
16849    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16850        self.show_git_blame_inline
16851            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16852            && !self.newest_selection_head_on_empty_line(cx)
16853            && self.has_blame_entries(cx)
16854    }
16855
16856    fn has_blame_entries(&self, cx: &App) -> bool {
16857        self.blame()
16858            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16859    }
16860
16861    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16862        let cursor_anchor = self.selections.newest_anchor().head();
16863
16864        let snapshot = self.buffer.read(cx).snapshot(cx);
16865        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16866
16867        snapshot.line_len(buffer_row) == 0
16868    }
16869
16870    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16871        let buffer_and_selection = maybe!({
16872            let selection = self.selections.newest::<Point>(cx);
16873            let selection_range = selection.range();
16874
16875            let multi_buffer = self.buffer().read(cx);
16876            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16877            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16878
16879            let (buffer, range, _) = if selection.reversed {
16880                buffer_ranges.first()
16881            } else {
16882                buffer_ranges.last()
16883            }?;
16884
16885            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16886                ..text::ToPoint::to_point(&range.end, &buffer).row;
16887            Some((
16888                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16889                selection,
16890            ))
16891        });
16892
16893        let Some((buffer, selection)) = buffer_and_selection else {
16894            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16895        };
16896
16897        let Some(project) = self.project.as_ref() else {
16898            return Task::ready(Err(anyhow!("editor does not have project")));
16899        };
16900
16901        project.update(cx, |project, cx| {
16902            project.get_permalink_to_line(&buffer, selection, cx)
16903        })
16904    }
16905
16906    pub fn copy_permalink_to_line(
16907        &mut self,
16908        _: &CopyPermalinkToLine,
16909        window: &mut Window,
16910        cx: &mut Context<Self>,
16911    ) {
16912        let permalink_task = self.get_permalink_to_line(cx);
16913        let workspace = self.workspace();
16914
16915        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16916            Ok(permalink) => {
16917                cx.update(|_, cx| {
16918                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16919                })
16920                .ok();
16921            }
16922            Err(err) => {
16923                let message = format!("Failed to copy permalink: {err}");
16924
16925                Err::<(), anyhow::Error>(err).log_err();
16926
16927                if let Some(workspace) = workspace {
16928                    workspace
16929                        .update_in(cx, |workspace, _, cx| {
16930                            struct CopyPermalinkToLine;
16931
16932                            workspace.show_toast(
16933                                Toast::new(
16934                                    NotificationId::unique::<CopyPermalinkToLine>(),
16935                                    message,
16936                                ),
16937                                cx,
16938                            )
16939                        })
16940                        .ok();
16941                }
16942            }
16943        })
16944        .detach();
16945    }
16946
16947    pub fn copy_file_location(
16948        &mut self,
16949        _: &CopyFileLocation,
16950        _: &mut Window,
16951        cx: &mut Context<Self>,
16952    ) {
16953        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16954        if let Some(file) = self.target_file(cx) {
16955            if let Some(path) = file.path().to_str() {
16956                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16957            }
16958        }
16959    }
16960
16961    pub fn open_permalink_to_line(
16962        &mut self,
16963        _: &OpenPermalinkToLine,
16964        window: &mut Window,
16965        cx: &mut Context<Self>,
16966    ) {
16967        let permalink_task = self.get_permalink_to_line(cx);
16968        let workspace = self.workspace();
16969
16970        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16971            Ok(permalink) => {
16972                cx.update(|_, cx| {
16973                    cx.open_url(permalink.as_ref());
16974                })
16975                .ok();
16976            }
16977            Err(err) => {
16978                let message = format!("Failed to open permalink: {err}");
16979
16980                Err::<(), anyhow::Error>(err).log_err();
16981
16982                if let Some(workspace) = workspace {
16983                    workspace
16984                        .update(cx, |workspace, cx| {
16985                            struct OpenPermalinkToLine;
16986
16987                            workspace.show_toast(
16988                                Toast::new(
16989                                    NotificationId::unique::<OpenPermalinkToLine>(),
16990                                    message,
16991                                ),
16992                                cx,
16993                            )
16994                        })
16995                        .ok();
16996                }
16997            }
16998        })
16999        .detach();
17000    }
17001
17002    pub fn insert_uuid_v4(
17003        &mut self,
17004        _: &InsertUuidV4,
17005        window: &mut Window,
17006        cx: &mut Context<Self>,
17007    ) {
17008        self.insert_uuid(UuidVersion::V4, window, cx);
17009    }
17010
17011    pub fn insert_uuid_v7(
17012        &mut self,
17013        _: &InsertUuidV7,
17014        window: &mut Window,
17015        cx: &mut Context<Self>,
17016    ) {
17017        self.insert_uuid(UuidVersion::V7, window, cx);
17018    }
17019
17020    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17021        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17022        self.transact(window, cx, |this, window, cx| {
17023            let edits = this
17024                .selections
17025                .all::<Point>(cx)
17026                .into_iter()
17027                .map(|selection| {
17028                    let uuid = match version {
17029                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17030                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17031                    };
17032
17033                    (selection.range(), uuid.to_string())
17034                });
17035            this.edit(edits, cx);
17036            this.refresh_inline_completion(true, false, window, cx);
17037        });
17038    }
17039
17040    pub fn open_selections_in_multibuffer(
17041        &mut self,
17042        _: &OpenSelectionsInMultibuffer,
17043        window: &mut Window,
17044        cx: &mut Context<Self>,
17045    ) {
17046        let multibuffer = self.buffer.read(cx);
17047
17048        let Some(buffer) = multibuffer.as_singleton() else {
17049            return;
17050        };
17051
17052        let Some(workspace) = self.workspace() else {
17053            return;
17054        };
17055
17056        let locations = self
17057            .selections
17058            .disjoint_anchors()
17059            .iter()
17060            .map(|range| Location {
17061                buffer: buffer.clone(),
17062                range: range.start.text_anchor..range.end.text_anchor,
17063            })
17064            .collect::<Vec<_>>();
17065
17066        let title = multibuffer.title(cx).to_string();
17067
17068        cx.spawn_in(window, async move |_, cx| {
17069            workspace.update_in(cx, |workspace, window, cx| {
17070                Self::open_locations_in_multibuffer(
17071                    workspace,
17072                    locations,
17073                    format!("Selections for '{title}'"),
17074                    false,
17075                    MultibufferSelectionMode::All,
17076                    window,
17077                    cx,
17078                );
17079            })
17080        })
17081        .detach();
17082    }
17083
17084    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17085    /// last highlight added will be used.
17086    ///
17087    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17088    pub fn highlight_rows<T: 'static>(
17089        &mut self,
17090        range: Range<Anchor>,
17091        color: Hsla,
17092        options: RowHighlightOptions,
17093        cx: &mut Context<Self>,
17094    ) {
17095        let snapshot = self.buffer().read(cx).snapshot(cx);
17096        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17097        let ix = row_highlights.binary_search_by(|highlight| {
17098            Ordering::Equal
17099                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17100                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17101        });
17102
17103        if let Err(mut ix) = ix {
17104            let index = post_inc(&mut self.highlight_order);
17105
17106            // If this range intersects with the preceding highlight, then merge it with
17107            // the preceding highlight. Otherwise insert a new highlight.
17108            let mut merged = false;
17109            if ix > 0 {
17110                let prev_highlight = &mut row_highlights[ix - 1];
17111                if prev_highlight
17112                    .range
17113                    .end
17114                    .cmp(&range.start, &snapshot)
17115                    .is_ge()
17116                {
17117                    ix -= 1;
17118                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17119                        prev_highlight.range.end = range.end;
17120                    }
17121                    merged = true;
17122                    prev_highlight.index = index;
17123                    prev_highlight.color = color;
17124                    prev_highlight.options = options;
17125                }
17126            }
17127
17128            if !merged {
17129                row_highlights.insert(
17130                    ix,
17131                    RowHighlight {
17132                        range: range.clone(),
17133                        index,
17134                        color,
17135                        options,
17136                        type_id: TypeId::of::<T>(),
17137                    },
17138                );
17139            }
17140
17141            // If any of the following highlights intersect with this one, merge them.
17142            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17143                let highlight = &row_highlights[ix];
17144                if next_highlight
17145                    .range
17146                    .start
17147                    .cmp(&highlight.range.end, &snapshot)
17148                    .is_le()
17149                {
17150                    if next_highlight
17151                        .range
17152                        .end
17153                        .cmp(&highlight.range.end, &snapshot)
17154                        .is_gt()
17155                    {
17156                        row_highlights[ix].range.end = next_highlight.range.end;
17157                    }
17158                    row_highlights.remove(ix + 1);
17159                } else {
17160                    break;
17161                }
17162            }
17163        }
17164    }
17165
17166    /// Remove any highlighted row ranges of the given type that intersect the
17167    /// given ranges.
17168    pub fn remove_highlighted_rows<T: 'static>(
17169        &mut self,
17170        ranges_to_remove: Vec<Range<Anchor>>,
17171        cx: &mut Context<Self>,
17172    ) {
17173        let snapshot = self.buffer().read(cx).snapshot(cx);
17174        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17175        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17176        row_highlights.retain(|highlight| {
17177            while let Some(range_to_remove) = ranges_to_remove.peek() {
17178                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17179                    Ordering::Less | Ordering::Equal => {
17180                        ranges_to_remove.next();
17181                    }
17182                    Ordering::Greater => {
17183                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17184                            Ordering::Less | Ordering::Equal => {
17185                                return false;
17186                            }
17187                            Ordering::Greater => break,
17188                        }
17189                    }
17190                }
17191            }
17192
17193            true
17194        })
17195    }
17196
17197    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17198    pub fn clear_row_highlights<T: 'static>(&mut self) {
17199        self.highlighted_rows.remove(&TypeId::of::<T>());
17200    }
17201
17202    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17203    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17204        self.highlighted_rows
17205            .get(&TypeId::of::<T>())
17206            .map_or(&[] as &[_], |vec| vec.as_slice())
17207            .iter()
17208            .map(|highlight| (highlight.range.clone(), highlight.color))
17209    }
17210
17211    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17212    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17213    /// Allows to ignore certain kinds of highlights.
17214    pub fn highlighted_display_rows(
17215        &self,
17216        window: &mut Window,
17217        cx: &mut App,
17218    ) -> BTreeMap<DisplayRow, LineHighlight> {
17219        let snapshot = self.snapshot(window, cx);
17220        let mut used_highlight_orders = HashMap::default();
17221        self.highlighted_rows
17222            .iter()
17223            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17224            .fold(
17225                BTreeMap::<DisplayRow, LineHighlight>::new(),
17226                |mut unique_rows, highlight| {
17227                    let start = highlight.range.start.to_display_point(&snapshot);
17228                    let end = highlight.range.end.to_display_point(&snapshot);
17229                    let start_row = start.row().0;
17230                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17231                        && end.column() == 0
17232                    {
17233                        end.row().0.saturating_sub(1)
17234                    } else {
17235                        end.row().0
17236                    };
17237                    for row in start_row..=end_row {
17238                        let used_index =
17239                            used_highlight_orders.entry(row).or_insert(highlight.index);
17240                        if highlight.index >= *used_index {
17241                            *used_index = highlight.index;
17242                            unique_rows.insert(
17243                                DisplayRow(row),
17244                                LineHighlight {
17245                                    include_gutter: highlight.options.include_gutter,
17246                                    border: None,
17247                                    background: highlight.color.into(),
17248                                    type_id: Some(highlight.type_id),
17249                                },
17250                            );
17251                        }
17252                    }
17253                    unique_rows
17254                },
17255            )
17256    }
17257
17258    pub fn highlighted_display_row_for_autoscroll(
17259        &self,
17260        snapshot: &DisplaySnapshot,
17261    ) -> Option<DisplayRow> {
17262        self.highlighted_rows
17263            .values()
17264            .flat_map(|highlighted_rows| highlighted_rows.iter())
17265            .filter_map(|highlight| {
17266                if highlight.options.autoscroll {
17267                    Some(highlight.range.start.to_display_point(snapshot).row())
17268                } else {
17269                    None
17270                }
17271            })
17272            .min()
17273    }
17274
17275    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17276        self.highlight_background::<SearchWithinRange>(
17277            ranges,
17278            |colors| colors.editor_document_highlight_read_background,
17279            cx,
17280        )
17281    }
17282
17283    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17284        self.breadcrumb_header = Some(new_header);
17285    }
17286
17287    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17288        self.clear_background_highlights::<SearchWithinRange>(cx);
17289    }
17290
17291    pub fn highlight_background<T: 'static>(
17292        &mut self,
17293        ranges: &[Range<Anchor>],
17294        color_fetcher: fn(&ThemeColors) -> Hsla,
17295        cx: &mut Context<Self>,
17296    ) {
17297        self.background_highlights
17298            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17299        self.scrollbar_marker_state.dirty = true;
17300        cx.notify();
17301    }
17302
17303    pub fn clear_background_highlights<T: 'static>(
17304        &mut self,
17305        cx: &mut Context<Self>,
17306    ) -> Option<BackgroundHighlight> {
17307        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17308        if !text_highlights.1.is_empty() {
17309            self.scrollbar_marker_state.dirty = true;
17310            cx.notify();
17311        }
17312        Some(text_highlights)
17313    }
17314
17315    pub fn highlight_gutter<T: 'static>(
17316        &mut self,
17317        ranges: &[Range<Anchor>],
17318        color_fetcher: fn(&App) -> Hsla,
17319        cx: &mut Context<Self>,
17320    ) {
17321        self.gutter_highlights
17322            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17323        cx.notify();
17324    }
17325
17326    pub fn clear_gutter_highlights<T: 'static>(
17327        &mut self,
17328        cx: &mut Context<Self>,
17329    ) -> Option<GutterHighlight> {
17330        cx.notify();
17331        self.gutter_highlights.remove(&TypeId::of::<T>())
17332    }
17333
17334    #[cfg(feature = "test-support")]
17335    pub fn all_text_background_highlights(
17336        &self,
17337        window: &mut Window,
17338        cx: &mut Context<Self>,
17339    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17340        let snapshot = self.snapshot(window, cx);
17341        let buffer = &snapshot.buffer_snapshot;
17342        let start = buffer.anchor_before(0);
17343        let end = buffer.anchor_after(buffer.len());
17344        let theme = cx.theme().colors();
17345        self.background_highlights_in_range(start..end, &snapshot, theme)
17346    }
17347
17348    #[cfg(feature = "test-support")]
17349    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17350        let snapshot = self.buffer().read(cx).snapshot(cx);
17351
17352        let highlights = self
17353            .background_highlights
17354            .get(&TypeId::of::<items::BufferSearchHighlights>());
17355
17356        if let Some((_color, ranges)) = highlights {
17357            ranges
17358                .iter()
17359                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17360                .collect_vec()
17361        } else {
17362            vec![]
17363        }
17364    }
17365
17366    fn document_highlights_for_position<'a>(
17367        &'a self,
17368        position: Anchor,
17369        buffer: &'a MultiBufferSnapshot,
17370    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17371        let read_highlights = self
17372            .background_highlights
17373            .get(&TypeId::of::<DocumentHighlightRead>())
17374            .map(|h| &h.1);
17375        let write_highlights = self
17376            .background_highlights
17377            .get(&TypeId::of::<DocumentHighlightWrite>())
17378            .map(|h| &h.1);
17379        let left_position = position.bias_left(buffer);
17380        let right_position = position.bias_right(buffer);
17381        read_highlights
17382            .into_iter()
17383            .chain(write_highlights)
17384            .flat_map(move |ranges| {
17385                let start_ix = match ranges.binary_search_by(|probe| {
17386                    let cmp = probe.end.cmp(&left_position, buffer);
17387                    if cmp.is_ge() {
17388                        Ordering::Greater
17389                    } else {
17390                        Ordering::Less
17391                    }
17392                }) {
17393                    Ok(i) | Err(i) => i,
17394                };
17395
17396                ranges[start_ix..]
17397                    .iter()
17398                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17399            })
17400    }
17401
17402    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17403        self.background_highlights
17404            .get(&TypeId::of::<T>())
17405            .map_or(false, |(_, highlights)| !highlights.is_empty())
17406    }
17407
17408    pub fn background_highlights_in_range(
17409        &self,
17410        search_range: Range<Anchor>,
17411        display_snapshot: &DisplaySnapshot,
17412        theme: &ThemeColors,
17413    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17414        let mut results = Vec::new();
17415        for (color_fetcher, ranges) in self.background_highlights.values() {
17416            let color = color_fetcher(theme);
17417            let start_ix = match ranges.binary_search_by(|probe| {
17418                let cmp = probe
17419                    .end
17420                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17421                if cmp.is_gt() {
17422                    Ordering::Greater
17423                } else {
17424                    Ordering::Less
17425                }
17426            }) {
17427                Ok(i) | Err(i) => i,
17428            };
17429            for range in &ranges[start_ix..] {
17430                if range
17431                    .start
17432                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17433                    .is_ge()
17434                {
17435                    break;
17436                }
17437
17438                let start = range.start.to_display_point(display_snapshot);
17439                let end = range.end.to_display_point(display_snapshot);
17440                results.push((start..end, color))
17441            }
17442        }
17443        results
17444    }
17445
17446    pub fn background_highlight_row_ranges<T: 'static>(
17447        &self,
17448        search_range: Range<Anchor>,
17449        display_snapshot: &DisplaySnapshot,
17450        count: usize,
17451    ) -> Vec<RangeInclusive<DisplayPoint>> {
17452        let mut results = Vec::new();
17453        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17454            return vec![];
17455        };
17456
17457        let start_ix = match ranges.binary_search_by(|probe| {
17458            let cmp = probe
17459                .end
17460                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17461            if cmp.is_gt() {
17462                Ordering::Greater
17463            } else {
17464                Ordering::Less
17465            }
17466        }) {
17467            Ok(i) | Err(i) => i,
17468        };
17469        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17470            if let (Some(start_display), Some(end_display)) = (start, end) {
17471                results.push(
17472                    start_display.to_display_point(display_snapshot)
17473                        ..=end_display.to_display_point(display_snapshot),
17474                );
17475            }
17476        };
17477        let mut start_row: Option<Point> = None;
17478        let mut end_row: Option<Point> = None;
17479        if ranges.len() > count {
17480            return Vec::new();
17481        }
17482        for range in &ranges[start_ix..] {
17483            if range
17484                .start
17485                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17486                .is_ge()
17487            {
17488                break;
17489            }
17490            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17491            if let Some(current_row) = &end_row {
17492                if end.row == current_row.row {
17493                    continue;
17494                }
17495            }
17496            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17497            if start_row.is_none() {
17498                assert_eq!(end_row, None);
17499                start_row = Some(start);
17500                end_row = Some(end);
17501                continue;
17502            }
17503            if let Some(current_end) = end_row.as_mut() {
17504                if start.row > current_end.row + 1 {
17505                    push_region(start_row, end_row);
17506                    start_row = Some(start);
17507                    end_row = Some(end);
17508                } else {
17509                    // Merge two hunks.
17510                    *current_end = end;
17511                }
17512            } else {
17513                unreachable!();
17514            }
17515        }
17516        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17517        push_region(start_row, end_row);
17518        results
17519    }
17520
17521    pub fn gutter_highlights_in_range(
17522        &self,
17523        search_range: Range<Anchor>,
17524        display_snapshot: &DisplaySnapshot,
17525        cx: &App,
17526    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17527        let mut results = Vec::new();
17528        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17529            let color = color_fetcher(cx);
17530            let start_ix = match ranges.binary_search_by(|probe| {
17531                let cmp = probe
17532                    .end
17533                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17534                if cmp.is_gt() {
17535                    Ordering::Greater
17536                } else {
17537                    Ordering::Less
17538                }
17539            }) {
17540                Ok(i) | Err(i) => i,
17541            };
17542            for range in &ranges[start_ix..] {
17543                if range
17544                    .start
17545                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17546                    .is_ge()
17547                {
17548                    break;
17549                }
17550
17551                let start = range.start.to_display_point(display_snapshot);
17552                let end = range.end.to_display_point(display_snapshot);
17553                results.push((start..end, color))
17554            }
17555        }
17556        results
17557    }
17558
17559    /// Get the text ranges corresponding to the redaction query
17560    pub fn redacted_ranges(
17561        &self,
17562        search_range: Range<Anchor>,
17563        display_snapshot: &DisplaySnapshot,
17564        cx: &App,
17565    ) -> Vec<Range<DisplayPoint>> {
17566        display_snapshot
17567            .buffer_snapshot
17568            .redacted_ranges(search_range, |file| {
17569                if let Some(file) = file {
17570                    file.is_private()
17571                        && EditorSettings::get(
17572                            Some(SettingsLocation {
17573                                worktree_id: file.worktree_id(cx),
17574                                path: file.path().as_ref(),
17575                            }),
17576                            cx,
17577                        )
17578                        .redact_private_values
17579                } else {
17580                    false
17581                }
17582            })
17583            .map(|range| {
17584                range.start.to_display_point(display_snapshot)
17585                    ..range.end.to_display_point(display_snapshot)
17586            })
17587            .collect()
17588    }
17589
17590    pub fn highlight_text<T: 'static>(
17591        &mut self,
17592        ranges: Vec<Range<Anchor>>,
17593        style: HighlightStyle,
17594        cx: &mut Context<Self>,
17595    ) {
17596        self.display_map.update(cx, |map, _| {
17597            map.highlight_text(TypeId::of::<T>(), ranges, style)
17598        });
17599        cx.notify();
17600    }
17601
17602    pub(crate) fn highlight_inlays<T: 'static>(
17603        &mut self,
17604        highlights: Vec<InlayHighlight>,
17605        style: HighlightStyle,
17606        cx: &mut Context<Self>,
17607    ) {
17608        self.display_map.update(cx, |map, _| {
17609            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17610        });
17611        cx.notify();
17612    }
17613
17614    pub fn text_highlights<'a, T: 'static>(
17615        &'a self,
17616        cx: &'a App,
17617    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17618        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17619    }
17620
17621    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17622        let cleared = self
17623            .display_map
17624            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17625        if cleared {
17626            cx.notify();
17627        }
17628    }
17629
17630    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17631        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17632            && self.focus_handle.is_focused(window)
17633    }
17634
17635    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17636        self.show_cursor_when_unfocused = is_enabled;
17637        cx.notify();
17638    }
17639
17640    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17641        cx.notify();
17642    }
17643
17644    fn on_debug_session_event(
17645        &mut self,
17646        _session: Entity<Session>,
17647        event: &SessionEvent,
17648        cx: &mut Context<Self>,
17649    ) {
17650        match event {
17651            SessionEvent::InvalidateInlineValue => {
17652                self.refresh_inline_values(cx);
17653            }
17654            _ => {}
17655        }
17656    }
17657
17658    fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17659        let Some(project) = self.project.clone() else {
17660            return;
17661        };
17662        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17663            return;
17664        };
17665        if !self.inline_value_cache.enabled {
17666            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17667            self.splice_inlays(&inlays, Vec::new(), cx);
17668            return;
17669        }
17670
17671        let current_execution_position = self
17672            .highlighted_rows
17673            .get(&TypeId::of::<ActiveDebugLine>())
17674            .and_then(|lines| lines.last().map(|line| line.range.start));
17675
17676        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17677            let snapshot = editor
17678                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17679                .ok()?;
17680
17681            let inline_values = editor
17682                .update(cx, |_, cx| {
17683                    let Some(current_execution_position) = current_execution_position else {
17684                        return Some(Task::ready(Ok(Vec::new())));
17685                    };
17686
17687                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17688                    // anchor is in the same buffer
17689                    let range =
17690                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17691                    project.inline_values(buffer, range, cx)
17692                })
17693                .ok()
17694                .flatten()?
17695                .await
17696                .context("refreshing debugger inlays")
17697                .log_err()?;
17698
17699            let (excerpt_id, buffer_id) = snapshot
17700                .excerpts()
17701                .next()
17702                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17703            editor
17704                .update(cx, |editor, cx| {
17705                    let new_inlays = inline_values
17706                        .into_iter()
17707                        .map(|debugger_value| {
17708                            Inlay::debugger_hint(
17709                                post_inc(&mut editor.next_inlay_id),
17710                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17711                                debugger_value.text(),
17712                            )
17713                        })
17714                        .collect::<Vec<_>>();
17715                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17716                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17717
17718                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17719                })
17720                .ok()?;
17721            Some(())
17722        });
17723    }
17724
17725    fn on_buffer_event(
17726        &mut self,
17727        multibuffer: &Entity<MultiBuffer>,
17728        event: &multi_buffer::Event,
17729        window: &mut Window,
17730        cx: &mut Context<Self>,
17731    ) {
17732        match event {
17733            multi_buffer::Event::Edited {
17734                singleton_buffer_edited,
17735                edited_buffer: buffer_edited,
17736            } => {
17737                self.scrollbar_marker_state.dirty = true;
17738                self.active_indent_guides_state.dirty = true;
17739                self.refresh_active_diagnostics(cx);
17740                self.refresh_code_actions(window, cx);
17741                self.refresh_selected_text_highlights(true, window, cx);
17742                refresh_matching_bracket_highlights(self, window, cx);
17743                if self.has_active_inline_completion() {
17744                    self.update_visible_inline_completion(window, cx);
17745                }
17746                if let Some(buffer) = buffer_edited {
17747                    let buffer_id = buffer.read(cx).remote_id();
17748                    if !self.registered_buffers.contains_key(&buffer_id) {
17749                        if let Some(project) = self.project.as_ref() {
17750                            project.update(cx, |project, cx| {
17751                                self.registered_buffers.insert(
17752                                    buffer_id,
17753                                    project.register_buffer_with_language_servers(&buffer, cx),
17754                                );
17755                            })
17756                        }
17757                    }
17758                }
17759                cx.emit(EditorEvent::BufferEdited);
17760                cx.emit(SearchEvent::MatchesInvalidated);
17761                if *singleton_buffer_edited {
17762                    if let Some(project) = &self.project {
17763                        #[allow(clippy::mutable_key_type)]
17764                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17765                            multibuffer
17766                                .all_buffers()
17767                                .into_iter()
17768                                .filter_map(|buffer| {
17769                                    buffer.update(cx, |buffer, cx| {
17770                                        let language = buffer.language()?;
17771                                        let should_discard = project.update(cx, |project, cx| {
17772                                            project.is_local()
17773                                                && !project.has_language_servers_for(buffer, cx)
17774                                        });
17775                                        should_discard.not().then_some(language.clone())
17776                                    })
17777                                })
17778                                .collect::<HashSet<_>>()
17779                        });
17780                        if !languages_affected.is_empty() {
17781                            self.refresh_inlay_hints(
17782                                InlayHintRefreshReason::BufferEdited(languages_affected),
17783                                cx,
17784                            );
17785                        }
17786                    }
17787                }
17788
17789                let Some(project) = &self.project else { return };
17790                let (telemetry, is_via_ssh) = {
17791                    let project = project.read(cx);
17792                    let telemetry = project.client().telemetry().clone();
17793                    let is_via_ssh = project.is_via_ssh();
17794                    (telemetry, is_via_ssh)
17795                };
17796                refresh_linked_ranges(self, window, cx);
17797                telemetry.log_edit_event("editor", is_via_ssh);
17798            }
17799            multi_buffer::Event::ExcerptsAdded {
17800                buffer,
17801                predecessor,
17802                excerpts,
17803            } => {
17804                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17805                let buffer_id = buffer.read(cx).remote_id();
17806                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17807                    if let Some(project) = &self.project {
17808                        update_uncommitted_diff_for_buffer(
17809                            cx.entity(),
17810                            project,
17811                            [buffer.clone()],
17812                            self.buffer.clone(),
17813                            cx,
17814                        )
17815                        .detach();
17816                    }
17817                }
17818                cx.emit(EditorEvent::ExcerptsAdded {
17819                    buffer: buffer.clone(),
17820                    predecessor: *predecessor,
17821                    excerpts: excerpts.clone(),
17822                });
17823                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17824            }
17825            multi_buffer::Event::ExcerptsRemoved {
17826                ids,
17827                removed_buffer_ids,
17828            } => {
17829                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17830                let buffer = self.buffer.read(cx);
17831                self.registered_buffers
17832                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17833                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17834                cx.emit(EditorEvent::ExcerptsRemoved {
17835                    ids: ids.clone(),
17836                    removed_buffer_ids: removed_buffer_ids.clone(),
17837                })
17838            }
17839            multi_buffer::Event::ExcerptsEdited {
17840                excerpt_ids,
17841                buffer_ids,
17842            } => {
17843                self.display_map.update(cx, |map, cx| {
17844                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17845                });
17846                cx.emit(EditorEvent::ExcerptsEdited {
17847                    ids: excerpt_ids.clone(),
17848                })
17849            }
17850            multi_buffer::Event::ExcerptsExpanded { ids } => {
17851                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17852                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17853            }
17854            multi_buffer::Event::Reparsed(buffer_id) => {
17855                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17856                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17857
17858                cx.emit(EditorEvent::Reparsed(*buffer_id));
17859            }
17860            multi_buffer::Event::DiffHunksToggled => {
17861                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17862            }
17863            multi_buffer::Event::LanguageChanged(buffer_id) => {
17864                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17865                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17866                cx.emit(EditorEvent::Reparsed(*buffer_id));
17867                cx.notify();
17868            }
17869            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17870            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17871            multi_buffer::Event::FileHandleChanged
17872            | multi_buffer::Event::Reloaded
17873            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17874            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17875            multi_buffer::Event::DiagnosticsUpdated => {
17876                self.refresh_active_diagnostics(cx);
17877                self.refresh_inline_diagnostics(true, window, cx);
17878                self.scrollbar_marker_state.dirty = true;
17879                cx.notify();
17880            }
17881            _ => {}
17882        };
17883    }
17884
17885    pub fn start_temporary_diff_override(&mut self) {
17886        self.load_diff_task.take();
17887        self.temporary_diff_override = true;
17888    }
17889
17890    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17891        self.temporary_diff_override = false;
17892        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17893        self.buffer.update(cx, |buffer, cx| {
17894            buffer.set_all_diff_hunks_collapsed(cx);
17895        });
17896
17897        if let Some(project) = self.project.clone() {
17898            self.load_diff_task = Some(
17899                update_uncommitted_diff_for_buffer(
17900                    cx.entity(),
17901                    &project,
17902                    self.buffer.read(cx).all_buffers(),
17903                    self.buffer.clone(),
17904                    cx,
17905                )
17906                .shared(),
17907            );
17908        }
17909    }
17910
17911    fn on_display_map_changed(
17912        &mut self,
17913        _: Entity<DisplayMap>,
17914        _: &mut Window,
17915        cx: &mut Context<Self>,
17916    ) {
17917        cx.notify();
17918    }
17919
17920    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17921        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17922        self.update_edit_prediction_settings(cx);
17923        self.refresh_inline_completion(true, false, window, cx);
17924        self.refresh_inlay_hints(
17925            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17926                self.selections.newest_anchor().head(),
17927                &self.buffer.read(cx).snapshot(cx),
17928                cx,
17929            )),
17930            cx,
17931        );
17932
17933        let old_cursor_shape = self.cursor_shape;
17934
17935        {
17936            let editor_settings = EditorSettings::get_global(cx);
17937            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17938            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17939            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17940            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17941        }
17942
17943        if old_cursor_shape != self.cursor_shape {
17944            cx.emit(EditorEvent::CursorShapeChanged);
17945        }
17946
17947        let project_settings = ProjectSettings::get_global(cx);
17948        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17949
17950        if self.mode.is_full() {
17951            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17952            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17953            if self.show_inline_diagnostics != show_inline_diagnostics {
17954                self.show_inline_diagnostics = show_inline_diagnostics;
17955                self.refresh_inline_diagnostics(false, window, cx);
17956            }
17957
17958            if self.git_blame_inline_enabled != inline_blame_enabled {
17959                self.toggle_git_blame_inline_internal(false, window, cx);
17960            }
17961        }
17962
17963        cx.notify();
17964    }
17965
17966    pub fn set_searchable(&mut self, searchable: bool) {
17967        self.searchable = searchable;
17968    }
17969
17970    pub fn searchable(&self) -> bool {
17971        self.searchable
17972    }
17973
17974    fn open_proposed_changes_editor(
17975        &mut self,
17976        _: &OpenProposedChangesEditor,
17977        window: &mut Window,
17978        cx: &mut Context<Self>,
17979    ) {
17980        let Some(workspace) = self.workspace() else {
17981            cx.propagate();
17982            return;
17983        };
17984
17985        let selections = self.selections.all::<usize>(cx);
17986        let multi_buffer = self.buffer.read(cx);
17987        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17988        let mut new_selections_by_buffer = HashMap::default();
17989        for selection in selections {
17990            for (buffer, range, _) in
17991                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17992            {
17993                let mut range = range.to_point(buffer);
17994                range.start.column = 0;
17995                range.end.column = buffer.line_len(range.end.row);
17996                new_selections_by_buffer
17997                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17998                    .or_insert(Vec::new())
17999                    .push(range)
18000            }
18001        }
18002
18003        let proposed_changes_buffers = new_selections_by_buffer
18004            .into_iter()
18005            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18006            .collect::<Vec<_>>();
18007        let proposed_changes_editor = cx.new(|cx| {
18008            ProposedChangesEditor::new(
18009                "Proposed changes",
18010                proposed_changes_buffers,
18011                self.project.clone(),
18012                window,
18013                cx,
18014            )
18015        });
18016
18017        window.defer(cx, move |window, cx| {
18018            workspace.update(cx, |workspace, cx| {
18019                workspace.active_pane().update(cx, |pane, cx| {
18020                    pane.add_item(
18021                        Box::new(proposed_changes_editor),
18022                        true,
18023                        true,
18024                        None,
18025                        window,
18026                        cx,
18027                    );
18028                });
18029            });
18030        });
18031    }
18032
18033    pub fn open_excerpts_in_split(
18034        &mut self,
18035        _: &OpenExcerptsSplit,
18036        window: &mut Window,
18037        cx: &mut Context<Self>,
18038    ) {
18039        self.open_excerpts_common(None, true, window, cx)
18040    }
18041
18042    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18043        self.open_excerpts_common(None, false, window, cx)
18044    }
18045
18046    fn open_excerpts_common(
18047        &mut self,
18048        jump_data: Option<JumpData>,
18049        split: bool,
18050        window: &mut Window,
18051        cx: &mut Context<Self>,
18052    ) {
18053        let Some(workspace) = self.workspace() else {
18054            cx.propagate();
18055            return;
18056        };
18057
18058        if self.buffer.read(cx).is_singleton() {
18059            cx.propagate();
18060            return;
18061        }
18062
18063        let mut new_selections_by_buffer = HashMap::default();
18064        match &jump_data {
18065            Some(JumpData::MultiBufferPoint {
18066                excerpt_id,
18067                position,
18068                anchor,
18069                line_offset_from_top,
18070            }) => {
18071                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18072                if let Some(buffer) = multi_buffer_snapshot
18073                    .buffer_id_for_excerpt(*excerpt_id)
18074                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18075                {
18076                    let buffer_snapshot = buffer.read(cx).snapshot();
18077                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18078                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18079                    } else {
18080                        buffer_snapshot.clip_point(*position, Bias::Left)
18081                    };
18082                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18083                    new_selections_by_buffer.insert(
18084                        buffer,
18085                        (
18086                            vec![jump_to_offset..jump_to_offset],
18087                            Some(*line_offset_from_top),
18088                        ),
18089                    );
18090                }
18091            }
18092            Some(JumpData::MultiBufferRow {
18093                row,
18094                line_offset_from_top,
18095            }) => {
18096                let point = MultiBufferPoint::new(row.0, 0);
18097                if let Some((buffer, buffer_point, _)) =
18098                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18099                {
18100                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18101                    new_selections_by_buffer
18102                        .entry(buffer)
18103                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18104                        .0
18105                        .push(buffer_offset..buffer_offset)
18106                }
18107            }
18108            None => {
18109                let selections = self.selections.all::<usize>(cx);
18110                let multi_buffer = self.buffer.read(cx);
18111                for selection in selections {
18112                    for (snapshot, range, _, anchor) in multi_buffer
18113                        .snapshot(cx)
18114                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18115                    {
18116                        if let Some(anchor) = anchor {
18117                            // selection is in a deleted hunk
18118                            let Some(buffer_id) = anchor.buffer_id else {
18119                                continue;
18120                            };
18121                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18122                                continue;
18123                            };
18124                            let offset = text::ToOffset::to_offset(
18125                                &anchor.text_anchor,
18126                                &buffer_handle.read(cx).snapshot(),
18127                            );
18128                            let range = offset..offset;
18129                            new_selections_by_buffer
18130                                .entry(buffer_handle)
18131                                .or_insert((Vec::new(), None))
18132                                .0
18133                                .push(range)
18134                        } else {
18135                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18136                            else {
18137                                continue;
18138                            };
18139                            new_selections_by_buffer
18140                                .entry(buffer_handle)
18141                                .or_insert((Vec::new(), None))
18142                                .0
18143                                .push(range)
18144                        }
18145                    }
18146                }
18147            }
18148        }
18149
18150        new_selections_by_buffer
18151            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18152
18153        if new_selections_by_buffer.is_empty() {
18154            return;
18155        }
18156
18157        // We defer the pane interaction because we ourselves are a workspace item
18158        // and activating a new item causes the pane to call a method on us reentrantly,
18159        // which panics if we're on the stack.
18160        window.defer(cx, move |window, cx| {
18161            workspace.update(cx, |workspace, cx| {
18162                let pane = if split {
18163                    workspace.adjacent_pane(window, cx)
18164                } else {
18165                    workspace.active_pane().clone()
18166                };
18167
18168                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18169                    let editor = buffer
18170                        .read(cx)
18171                        .file()
18172                        .is_none()
18173                        .then(|| {
18174                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18175                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18176                            // Instead, we try to activate the existing editor in the pane first.
18177                            let (editor, pane_item_index) =
18178                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18179                                    let editor = item.downcast::<Editor>()?;
18180                                    let singleton_buffer =
18181                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18182                                    if singleton_buffer == buffer {
18183                                        Some((editor, i))
18184                                    } else {
18185                                        None
18186                                    }
18187                                })?;
18188                            pane.update(cx, |pane, cx| {
18189                                pane.activate_item(pane_item_index, true, true, window, cx)
18190                            });
18191                            Some(editor)
18192                        })
18193                        .flatten()
18194                        .unwrap_or_else(|| {
18195                            workspace.open_project_item::<Self>(
18196                                pane.clone(),
18197                                buffer,
18198                                true,
18199                                true,
18200                                window,
18201                                cx,
18202                            )
18203                        });
18204
18205                    editor.update(cx, |editor, cx| {
18206                        let autoscroll = match scroll_offset {
18207                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18208                            None => Autoscroll::newest(),
18209                        };
18210                        let nav_history = editor.nav_history.take();
18211                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18212                            s.select_ranges(ranges);
18213                        });
18214                        editor.nav_history = nav_history;
18215                    });
18216                }
18217            })
18218        });
18219    }
18220
18221    // For now, don't allow opening excerpts in buffers that aren't backed by
18222    // regular project files.
18223    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18224        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18225    }
18226
18227    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18228        let snapshot = self.buffer.read(cx).read(cx);
18229        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18230        Some(
18231            ranges
18232                .iter()
18233                .map(move |range| {
18234                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18235                })
18236                .collect(),
18237        )
18238    }
18239
18240    fn selection_replacement_ranges(
18241        &self,
18242        range: Range<OffsetUtf16>,
18243        cx: &mut App,
18244    ) -> Vec<Range<OffsetUtf16>> {
18245        let selections = self.selections.all::<OffsetUtf16>(cx);
18246        let newest_selection = selections
18247            .iter()
18248            .max_by_key(|selection| selection.id)
18249            .unwrap();
18250        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18251        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18252        let snapshot = self.buffer.read(cx).read(cx);
18253        selections
18254            .into_iter()
18255            .map(|mut selection| {
18256                selection.start.0 =
18257                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18258                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18259                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18260                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18261            })
18262            .collect()
18263    }
18264
18265    fn report_editor_event(
18266        &self,
18267        event_type: &'static str,
18268        file_extension: Option<String>,
18269        cx: &App,
18270    ) {
18271        if cfg!(any(test, feature = "test-support")) {
18272            return;
18273        }
18274
18275        let Some(project) = &self.project else { return };
18276
18277        // If None, we are in a file without an extension
18278        let file = self
18279            .buffer
18280            .read(cx)
18281            .as_singleton()
18282            .and_then(|b| b.read(cx).file());
18283        let file_extension = file_extension.or(file
18284            .as_ref()
18285            .and_then(|file| Path::new(file.file_name(cx)).extension())
18286            .and_then(|e| e.to_str())
18287            .map(|a| a.to_string()));
18288
18289        let vim_mode = vim_enabled(cx);
18290
18291        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18292        let copilot_enabled = edit_predictions_provider
18293            == language::language_settings::EditPredictionProvider::Copilot;
18294        let copilot_enabled_for_language = self
18295            .buffer
18296            .read(cx)
18297            .language_settings(cx)
18298            .show_edit_predictions;
18299
18300        let project = project.read(cx);
18301        telemetry::event!(
18302            event_type,
18303            file_extension,
18304            vim_mode,
18305            copilot_enabled,
18306            copilot_enabled_for_language,
18307            edit_predictions_provider,
18308            is_via_ssh = project.is_via_ssh(),
18309        );
18310    }
18311
18312    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18313    /// with each line being an array of {text, highlight} objects.
18314    fn copy_highlight_json(
18315        &mut self,
18316        _: &CopyHighlightJson,
18317        window: &mut Window,
18318        cx: &mut Context<Self>,
18319    ) {
18320        #[derive(Serialize)]
18321        struct Chunk<'a> {
18322            text: String,
18323            highlight: Option<&'a str>,
18324        }
18325
18326        let snapshot = self.buffer.read(cx).snapshot(cx);
18327        let range = self
18328            .selected_text_range(false, window, cx)
18329            .and_then(|selection| {
18330                if selection.range.is_empty() {
18331                    None
18332                } else {
18333                    Some(selection.range)
18334                }
18335            })
18336            .unwrap_or_else(|| 0..snapshot.len());
18337
18338        let chunks = snapshot.chunks(range, true);
18339        let mut lines = Vec::new();
18340        let mut line: VecDeque<Chunk> = VecDeque::new();
18341
18342        let Some(style) = self.style.as_ref() else {
18343            return;
18344        };
18345
18346        for chunk in chunks {
18347            let highlight = chunk
18348                .syntax_highlight_id
18349                .and_then(|id| id.name(&style.syntax));
18350            let mut chunk_lines = chunk.text.split('\n').peekable();
18351            while let Some(text) = chunk_lines.next() {
18352                let mut merged_with_last_token = false;
18353                if let Some(last_token) = line.back_mut() {
18354                    if last_token.highlight == highlight {
18355                        last_token.text.push_str(text);
18356                        merged_with_last_token = true;
18357                    }
18358                }
18359
18360                if !merged_with_last_token {
18361                    line.push_back(Chunk {
18362                        text: text.into(),
18363                        highlight,
18364                    });
18365                }
18366
18367                if chunk_lines.peek().is_some() {
18368                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18369                        line.pop_front();
18370                    }
18371                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18372                        line.pop_back();
18373                    }
18374
18375                    lines.push(mem::take(&mut line));
18376                }
18377            }
18378        }
18379
18380        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18381            return;
18382        };
18383        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18384    }
18385
18386    pub fn open_context_menu(
18387        &mut self,
18388        _: &OpenContextMenu,
18389        window: &mut Window,
18390        cx: &mut Context<Self>,
18391    ) {
18392        self.request_autoscroll(Autoscroll::newest(), cx);
18393        let position = self.selections.newest_display(cx).start;
18394        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18395    }
18396
18397    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18398        &self.inlay_hint_cache
18399    }
18400
18401    pub fn replay_insert_event(
18402        &mut self,
18403        text: &str,
18404        relative_utf16_range: Option<Range<isize>>,
18405        window: &mut Window,
18406        cx: &mut Context<Self>,
18407    ) {
18408        if !self.input_enabled {
18409            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18410            return;
18411        }
18412        if let Some(relative_utf16_range) = relative_utf16_range {
18413            let selections = self.selections.all::<OffsetUtf16>(cx);
18414            self.change_selections(None, window, cx, |s| {
18415                let new_ranges = selections.into_iter().map(|range| {
18416                    let start = OffsetUtf16(
18417                        range
18418                            .head()
18419                            .0
18420                            .saturating_add_signed(relative_utf16_range.start),
18421                    );
18422                    let end = OffsetUtf16(
18423                        range
18424                            .head()
18425                            .0
18426                            .saturating_add_signed(relative_utf16_range.end),
18427                    );
18428                    start..end
18429                });
18430                s.select_ranges(new_ranges);
18431            });
18432        }
18433
18434        self.handle_input(text, window, cx);
18435    }
18436
18437    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18438        let Some(provider) = self.semantics_provider.as_ref() else {
18439            return false;
18440        };
18441
18442        let mut supports = false;
18443        self.buffer().update(cx, |this, cx| {
18444            this.for_each_buffer(|buffer| {
18445                supports |= provider.supports_inlay_hints(buffer, cx);
18446            });
18447        });
18448
18449        supports
18450    }
18451
18452    pub fn is_focused(&self, window: &Window) -> bool {
18453        self.focus_handle.is_focused(window)
18454    }
18455
18456    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18457        cx.emit(EditorEvent::Focused);
18458
18459        if let Some(descendant) = self
18460            .last_focused_descendant
18461            .take()
18462            .and_then(|descendant| descendant.upgrade())
18463        {
18464            window.focus(&descendant);
18465        } else {
18466            if let Some(blame) = self.blame.as_ref() {
18467                blame.update(cx, GitBlame::focus)
18468            }
18469
18470            self.blink_manager.update(cx, BlinkManager::enable);
18471            self.show_cursor_names(window, cx);
18472            self.buffer.update(cx, |buffer, cx| {
18473                buffer.finalize_last_transaction(cx);
18474                if self.leader_id.is_none() {
18475                    buffer.set_active_selections(
18476                        &self.selections.disjoint_anchors(),
18477                        self.selections.line_mode,
18478                        self.cursor_shape,
18479                        cx,
18480                    );
18481                }
18482            });
18483        }
18484    }
18485
18486    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18487        cx.emit(EditorEvent::FocusedIn)
18488    }
18489
18490    fn handle_focus_out(
18491        &mut self,
18492        event: FocusOutEvent,
18493        _window: &mut Window,
18494        cx: &mut Context<Self>,
18495    ) {
18496        if event.blurred != self.focus_handle {
18497            self.last_focused_descendant = Some(event.blurred);
18498        }
18499        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18500    }
18501
18502    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18503        self.blink_manager.update(cx, BlinkManager::disable);
18504        self.buffer
18505            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18506
18507        if let Some(blame) = self.blame.as_ref() {
18508            blame.update(cx, GitBlame::blur)
18509        }
18510        if !self.hover_state.focused(window, cx) {
18511            hide_hover(self, cx);
18512        }
18513        if !self
18514            .context_menu
18515            .borrow()
18516            .as_ref()
18517            .is_some_and(|context_menu| context_menu.focused(window, cx))
18518        {
18519            self.hide_context_menu(window, cx);
18520        }
18521        self.discard_inline_completion(false, cx);
18522        cx.emit(EditorEvent::Blurred);
18523        cx.notify();
18524    }
18525
18526    pub fn register_action<A: Action>(
18527        &mut self,
18528        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18529    ) -> Subscription {
18530        let id = self.next_editor_action_id.post_inc();
18531        let listener = Arc::new(listener);
18532        self.editor_actions.borrow_mut().insert(
18533            id,
18534            Box::new(move |window, _| {
18535                let listener = listener.clone();
18536                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18537                    let action = action.downcast_ref().unwrap();
18538                    if phase == DispatchPhase::Bubble {
18539                        listener(action, window, cx)
18540                    }
18541                })
18542            }),
18543        );
18544
18545        let editor_actions = self.editor_actions.clone();
18546        Subscription::new(move || {
18547            editor_actions.borrow_mut().remove(&id);
18548        })
18549    }
18550
18551    pub fn file_header_size(&self) -> u32 {
18552        FILE_HEADER_HEIGHT
18553    }
18554
18555    pub fn restore(
18556        &mut self,
18557        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18558        window: &mut Window,
18559        cx: &mut Context<Self>,
18560    ) {
18561        let workspace = self.workspace();
18562        let project = self.project.as_ref();
18563        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18564            let mut tasks = Vec::new();
18565            for (buffer_id, changes) in revert_changes {
18566                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18567                    buffer.update(cx, |buffer, cx| {
18568                        buffer.edit(
18569                            changes
18570                                .into_iter()
18571                                .map(|(range, text)| (range, text.to_string())),
18572                            None,
18573                            cx,
18574                        );
18575                    });
18576
18577                    if let Some(project) =
18578                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18579                    {
18580                        project.update(cx, |project, cx| {
18581                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18582                        })
18583                    }
18584                }
18585            }
18586            tasks
18587        });
18588        cx.spawn_in(window, async move |_, cx| {
18589            for (buffer, task) in save_tasks {
18590                let result = task.await;
18591                if result.is_err() {
18592                    let Some(path) = buffer
18593                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18594                        .ok()
18595                    else {
18596                        continue;
18597                    };
18598                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18599                        let Some(task) = cx
18600                            .update_window_entity(&workspace, |workspace, window, cx| {
18601                                workspace
18602                                    .open_path_preview(path, None, false, false, false, window, cx)
18603                            })
18604                            .ok()
18605                        else {
18606                            continue;
18607                        };
18608                        task.await.log_err();
18609                    }
18610                }
18611            }
18612        })
18613        .detach();
18614        self.change_selections(None, window, cx, |selections| selections.refresh());
18615    }
18616
18617    pub fn to_pixel_point(
18618        &self,
18619        source: multi_buffer::Anchor,
18620        editor_snapshot: &EditorSnapshot,
18621        window: &mut Window,
18622    ) -> Option<gpui::Point<Pixels>> {
18623        let source_point = source.to_display_point(editor_snapshot);
18624        self.display_to_pixel_point(source_point, editor_snapshot, window)
18625    }
18626
18627    pub fn display_to_pixel_point(
18628        &self,
18629        source: DisplayPoint,
18630        editor_snapshot: &EditorSnapshot,
18631        window: &mut Window,
18632    ) -> Option<gpui::Point<Pixels>> {
18633        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18634        let text_layout_details = self.text_layout_details(window);
18635        let scroll_top = text_layout_details
18636            .scroll_anchor
18637            .scroll_position(editor_snapshot)
18638            .y;
18639
18640        if source.row().as_f32() < scroll_top.floor() {
18641            return None;
18642        }
18643        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18644        let source_y = line_height * (source.row().as_f32() - scroll_top);
18645        Some(gpui::Point::new(source_x, source_y))
18646    }
18647
18648    pub fn has_visible_completions_menu(&self) -> bool {
18649        !self.edit_prediction_preview_is_active()
18650            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18651                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18652            })
18653    }
18654
18655    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18656        self.addons
18657            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18658    }
18659
18660    pub fn unregister_addon<T: Addon>(&mut self) {
18661        self.addons.remove(&std::any::TypeId::of::<T>());
18662    }
18663
18664    pub fn addon<T: Addon>(&self) -> Option<&T> {
18665        let type_id = std::any::TypeId::of::<T>();
18666        self.addons
18667            .get(&type_id)
18668            .and_then(|item| item.to_any().downcast_ref::<T>())
18669    }
18670
18671    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18672        let type_id = std::any::TypeId::of::<T>();
18673        self.addons
18674            .get_mut(&type_id)
18675            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18676    }
18677
18678    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18679        let text_layout_details = self.text_layout_details(window);
18680        let style = &text_layout_details.editor_style;
18681        let font_id = window.text_system().resolve_font(&style.text.font());
18682        let font_size = style.text.font_size.to_pixels(window.rem_size());
18683        let line_height = style.text.line_height_in_pixels(window.rem_size());
18684        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18685
18686        gpui::Size::new(em_width, line_height)
18687    }
18688
18689    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18690        self.load_diff_task.clone()
18691    }
18692
18693    fn read_metadata_from_db(
18694        &mut self,
18695        item_id: u64,
18696        workspace_id: WorkspaceId,
18697        window: &mut Window,
18698        cx: &mut Context<Editor>,
18699    ) {
18700        if self.is_singleton(cx)
18701            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18702        {
18703            let buffer_snapshot = OnceCell::new();
18704
18705            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18706                if !folds.is_empty() {
18707                    let snapshot =
18708                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18709                    self.fold_ranges(
18710                        folds
18711                            .into_iter()
18712                            .map(|(start, end)| {
18713                                snapshot.clip_offset(start, Bias::Left)
18714                                    ..snapshot.clip_offset(end, Bias::Right)
18715                            })
18716                            .collect(),
18717                        false,
18718                        window,
18719                        cx,
18720                    );
18721                }
18722            }
18723
18724            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18725                if !selections.is_empty() {
18726                    let snapshot =
18727                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18728                    self.change_selections(None, window, cx, |s| {
18729                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18730                            snapshot.clip_offset(start, Bias::Left)
18731                                ..snapshot.clip_offset(end, Bias::Right)
18732                        }));
18733                    });
18734                }
18735            };
18736        }
18737
18738        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18739    }
18740}
18741
18742fn vim_enabled(cx: &App) -> bool {
18743    cx.global::<SettingsStore>()
18744        .raw_user_settings()
18745        .get("vim_mode")
18746        == Some(&serde_json::Value::Bool(true))
18747}
18748
18749// Consider user intent and default settings
18750fn choose_completion_range(
18751    completion: &Completion,
18752    intent: CompletionIntent,
18753    buffer: &Entity<Buffer>,
18754    cx: &mut Context<Editor>,
18755) -> Range<usize> {
18756    fn should_replace(
18757        completion: &Completion,
18758        insert_range: &Range<text::Anchor>,
18759        intent: CompletionIntent,
18760        completion_mode_setting: LspInsertMode,
18761        buffer: &Buffer,
18762    ) -> bool {
18763        // specific actions take precedence over settings
18764        match intent {
18765            CompletionIntent::CompleteWithInsert => return false,
18766            CompletionIntent::CompleteWithReplace => return true,
18767            CompletionIntent::Complete | CompletionIntent::Compose => {}
18768        }
18769
18770        match completion_mode_setting {
18771            LspInsertMode::Insert => false,
18772            LspInsertMode::Replace => true,
18773            LspInsertMode::ReplaceSubsequence => {
18774                let mut text_to_replace = buffer.chars_for_range(
18775                    buffer.anchor_before(completion.replace_range.start)
18776                        ..buffer.anchor_after(completion.replace_range.end),
18777                );
18778                let mut completion_text = completion.new_text.chars();
18779
18780                // is `text_to_replace` a subsequence of `completion_text`
18781                text_to_replace
18782                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18783            }
18784            LspInsertMode::ReplaceSuffix => {
18785                let range_after_cursor = insert_range.end..completion.replace_range.end;
18786
18787                let text_after_cursor = buffer
18788                    .text_for_range(
18789                        buffer.anchor_before(range_after_cursor.start)
18790                            ..buffer.anchor_after(range_after_cursor.end),
18791                    )
18792                    .collect::<String>();
18793                completion.new_text.ends_with(&text_after_cursor)
18794            }
18795        }
18796    }
18797
18798    let buffer = buffer.read(cx);
18799
18800    if let CompletionSource::Lsp {
18801        insert_range: Some(insert_range),
18802        ..
18803    } = &completion.source
18804    {
18805        let completion_mode_setting =
18806            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18807                .completions
18808                .lsp_insert_mode;
18809
18810        if !should_replace(
18811            completion,
18812            &insert_range,
18813            intent,
18814            completion_mode_setting,
18815            buffer,
18816        ) {
18817            return insert_range.to_offset(buffer);
18818        }
18819    }
18820
18821    completion.replace_range.to_offset(buffer)
18822}
18823
18824fn insert_extra_newline_brackets(
18825    buffer: &MultiBufferSnapshot,
18826    range: Range<usize>,
18827    language: &language::LanguageScope,
18828) -> bool {
18829    let leading_whitespace_len = buffer
18830        .reversed_chars_at(range.start)
18831        .take_while(|c| c.is_whitespace() && *c != '\n')
18832        .map(|c| c.len_utf8())
18833        .sum::<usize>();
18834    let trailing_whitespace_len = buffer
18835        .chars_at(range.end)
18836        .take_while(|c| c.is_whitespace() && *c != '\n')
18837        .map(|c| c.len_utf8())
18838        .sum::<usize>();
18839    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18840
18841    language.brackets().any(|(pair, enabled)| {
18842        let pair_start = pair.start.trim_end();
18843        let pair_end = pair.end.trim_start();
18844
18845        enabled
18846            && pair.newline
18847            && buffer.contains_str_at(range.end, pair_end)
18848            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18849    })
18850}
18851
18852fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18853    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18854        [(buffer, range, _)] => (*buffer, range.clone()),
18855        _ => return false,
18856    };
18857    let pair = {
18858        let mut result: Option<BracketMatch> = None;
18859
18860        for pair in buffer
18861            .all_bracket_ranges(range.clone())
18862            .filter(move |pair| {
18863                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18864            })
18865        {
18866            let len = pair.close_range.end - pair.open_range.start;
18867
18868            if let Some(existing) = &result {
18869                let existing_len = existing.close_range.end - existing.open_range.start;
18870                if len > existing_len {
18871                    continue;
18872                }
18873            }
18874
18875            result = Some(pair);
18876        }
18877
18878        result
18879    };
18880    let Some(pair) = pair else {
18881        return false;
18882    };
18883    pair.newline_only
18884        && buffer
18885            .chars_for_range(pair.open_range.end..range.start)
18886            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18887            .all(|c| c.is_whitespace() && c != '\n')
18888}
18889
18890fn update_uncommitted_diff_for_buffer(
18891    editor: Entity<Editor>,
18892    project: &Entity<Project>,
18893    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18894    buffer: Entity<MultiBuffer>,
18895    cx: &mut App,
18896) -> Task<()> {
18897    let mut tasks = Vec::new();
18898    project.update(cx, |project, cx| {
18899        for buffer in buffers {
18900            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18901                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18902            }
18903        }
18904    });
18905    cx.spawn(async move |cx| {
18906        let diffs = future::join_all(tasks).await;
18907        if editor
18908            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18909            .unwrap_or(false)
18910        {
18911            return;
18912        }
18913
18914        buffer
18915            .update(cx, |buffer, cx| {
18916                for diff in diffs.into_iter().flatten() {
18917                    buffer.add_diff(diff, cx);
18918                }
18919            })
18920            .ok();
18921    })
18922}
18923
18924fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18925    let tab_size = tab_size.get() as usize;
18926    let mut width = offset;
18927
18928    for ch in text.chars() {
18929        width += if ch == '\t' {
18930            tab_size - (width % tab_size)
18931        } else {
18932            1
18933        };
18934    }
18935
18936    width - offset
18937}
18938
18939#[cfg(test)]
18940mod tests {
18941    use super::*;
18942
18943    #[test]
18944    fn test_string_size_with_expanded_tabs() {
18945        let nz = |val| NonZeroU32::new(val).unwrap();
18946        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18947        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18948        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18949        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18950        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18951        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18952        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18953        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18954    }
18955}
18956
18957/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18958struct WordBreakingTokenizer<'a> {
18959    input: &'a str,
18960}
18961
18962impl<'a> WordBreakingTokenizer<'a> {
18963    fn new(input: &'a str) -> Self {
18964        Self { input }
18965    }
18966}
18967
18968fn is_char_ideographic(ch: char) -> bool {
18969    use unicode_script::Script::*;
18970    use unicode_script::UnicodeScript;
18971    matches!(ch.script(), Han | Tangut | Yi)
18972}
18973
18974fn is_grapheme_ideographic(text: &str) -> bool {
18975    text.chars().any(is_char_ideographic)
18976}
18977
18978fn is_grapheme_whitespace(text: &str) -> bool {
18979    text.chars().any(|x| x.is_whitespace())
18980}
18981
18982fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18983    text.chars().next().map_or(false, |ch| {
18984        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18985    })
18986}
18987
18988#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18989enum WordBreakToken<'a> {
18990    Word { token: &'a str, grapheme_len: usize },
18991    InlineWhitespace { token: &'a str, grapheme_len: usize },
18992    Newline,
18993}
18994
18995impl<'a> Iterator for WordBreakingTokenizer<'a> {
18996    /// Yields a span, the count of graphemes in the token, and whether it was
18997    /// whitespace. Note that it also breaks at word boundaries.
18998    type Item = WordBreakToken<'a>;
18999
19000    fn next(&mut self) -> Option<Self::Item> {
19001        use unicode_segmentation::UnicodeSegmentation;
19002        if self.input.is_empty() {
19003            return None;
19004        }
19005
19006        let mut iter = self.input.graphemes(true).peekable();
19007        let mut offset = 0;
19008        let mut grapheme_len = 0;
19009        if let Some(first_grapheme) = iter.next() {
19010            let is_newline = first_grapheme == "\n";
19011            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19012            offset += first_grapheme.len();
19013            grapheme_len += 1;
19014            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19015                if let Some(grapheme) = iter.peek().copied() {
19016                    if should_stay_with_preceding_ideograph(grapheme) {
19017                        offset += grapheme.len();
19018                        grapheme_len += 1;
19019                    }
19020                }
19021            } else {
19022                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19023                let mut next_word_bound = words.peek().copied();
19024                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19025                    next_word_bound = words.next();
19026                }
19027                while let Some(grapheme) = iter.peek().copied() {
19028                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19029                        break;
19030                    };
19031                    if is_grapheme_whitespace(grapheme) != is_whitespace
19032                        || (grapheme == "\n") != is_newline
19033                    {
19034                        break;
19035                    };
19036                    offset += grapheme.len();
19037                    grapheme_len += 1;
19038                    iter.next();
19039                }
19040            }
19041            let token = &self.input[..offset];
19042            self.input = &self.input[offset..];
19043            if token == "\n" {
19044                Some(WordBreakToken::Newline)
19045            } else if is_whitespace {
19046                Some(WordBreakToken::InlineWhitespace {
19047                    token,
19048                    grapheme_len,
19049                })
19050            } else {
19051                Some(WordBreakToken::Word {
19052                    token,
19053                    grapheme_len,
19054                })
19055            }
19056        } else {
19057            None
19058        }
19059    }
19060}
19061
19062#[test]
19063fn test_word_breaking_tokenizer() {
19064    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19065        ("", &[]),
19066        ("  ", &[whitespace("  ", 2)]),
19067        ("Ʒ", &[word("Ʒ", 1)]),
19068        ("Ǽ", &[word("Ǽ", 1)]),
19069        ("", &[word("", 1)]),
19070        ("⋑⋑", &[word("⋑⋑", 2)]),
19071        (
19072            "原理,进而",
19073            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19074        ),
19075        (
19076            "hello world",
19077            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19078        ),
19079        (
19080            "hello, world",
19081            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19082        ),
19083        (
19084            "  hello world",
19085            &[
19086                whitespace("  ", 2),
19087                word("hello", 5),
19088                whitespace(" ", 1),
19089                word("world", 5),
19090            ],
19091        ),
19092        (
19093            "这是什么 \n 钢笔",
19094            &[
19095                word("", 1),
19096                word("", 1),
19097                word("", 1),
19098                word("", 1),
19099                whitespace(" ", 1),
19100                newline(),
19101                whitespace(" ", 1),
19102                word("", 1),
19103                word("", 1),
19104            ],
19105        ),
19106        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19107    ];
19108
19109    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19110        WordBreakToken::Word {
19111            token,
19112            grapheme_len,
19113        }
19114    }
19115
19116    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19117        WordBreakToken::InlineWhitespace {
19118            token,
19119            grapheme_len,
19120        }
19121    }
19122
19123    fn newline() -> WordBreakToken<'static> {
19124        WordBreakToken::Newline
19125    }
19126
19127    for (input, result) in tests {
19128        assert_eq!(
19129            WordBreakingTokenizer::new(input)
19130                .collect::<Vec<_>>()
19131                .as_slice(),
19132            *result,
19133        );
19134    }
19135}
19136
19137fn wrap_with_prefix(
19138    line_prefix: String,
19139    unwrapped_text: String,
19140    wrap_column: usize,
19141    tab_size: NonZeroU32,
19142    preserve_existing_whitespace: bool,
19143) -> String {
19144    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19145    let mut wrapped_text = String::new();
19146    let mut current_line = line_prefix.clone();
19147
19148    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19149    let mut current_line_len = line_prefix_len;
19150    let mut in_whitespace = false;
19151    for token in tokenizer {
19152        let have_preceding_whitespace = in_whitespace;
19153        match token {
19154            WordBreakToken::Word {
19155                token,
19156                grapheme_len,
19157            } => {
19158                in_whitespace = false;
19159                if current_line_len + grapheme_len > wrap_column
19160                    && current_line_len != line_prefix_len
19161                {
19162                    wrapped_text.push_str(current_line.trim_end());
19163                    wrapped_text.push('\n');
19164                    current_line.truncate(line_prefix.len());
19165                    current_line_len = line_prefix_len;
19166                }
19167                current_line.push_str(token);
19168                current_line_len += grapheme_len;
19169            }
19170            WordBreakToken::InlineWhitespace {
19171                mut token,
19172                mut grapheme_len,
19173            } => {
19174                in_whitespace = true;
19175                if have_preceding_whitespace && !preserve_existing_whitespace {
19176                    continue;
19177                }
19178                if !preserve_existing_whitespace {
19179                    token = " ";
19180                    grapheme_len = 1;
19181                }
19182                if current_line_len + grapheme_len > wrap_column {
19183                    wrapped_text.push_str(current_line.trim_end());
19184                    wrapped_text.push('\n');
19185                    current_line.truncate(line_prefix.len());
19186                    current_line_len = line_prefix_len;
19187                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19188                    current_line.push_str(token);
19189                    current_line_len += grapheme_len;
19190                }
19191            }
19192            WordBreakToken::Newline => {
19193                in_whitespace = true;
19194                if preserve_existing_whitespace {
19195                    wrapped_text.push_str(current_line.trim_end());
19196                    wrapped_text.push('\n');
19197                    current_line.truncate(line_prefix.len());
19198                    current_line_len = line_prefix_len;
19199                } else if have_preceding_whitespace {
19200                    continue;
19201                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19202                {
19203                    wrapped_text.push_str(current_line.trim_end());
19204                    wrapped_text.push('\n');
19205                    current_line.truncate(line_prefix.len());
19206                    current_line_len = line_prefix_len;
19207                } else if current_line_len != line_prefix_len {
19208                    current_line.push(' ');
19209                    current_line_len += 1;
19210                }
19211            }
19212        }
19213    }
19214
19215    if !current_line.is_empty() {
19216        wrapped_text.push_str(&current_line);
19217    }
19218    wrapped_text
19219}
19220
19221#[test]
19222fn test_wrap_with_prefix() {
19223    assert_eq!(
19224        wrap_with_prefix(
19225            "# ".to_string(),
19226            "abcdefg".to_string(),
19227            4,
19228            NonZeroU32::new(4).unwrap(),
19229            false,
19230        ),
19231        "# abcdefg"
19232    );
19233    assert_eq!(
19234        wrap_with_prefix(
19235            "".to_string(),
19236            "\thello world".to_string(),
19237            8,
19238            NonZeroU32::new(4).unwrap(),
19239            false,
19240        ),
19241        "hello\nworld"
19242    );
19243    assert_eq!(
19244        wrap_with_prefix(
19245            "// ".to_string(),
19246            "xx \nyy zz aa bb cc".to_string(),
19247            12,
19248            NonZeroU32::new(4).unwrap(),
19249            false,
19250        ),
19251        "// xx yy zz\n// aa bb cc"
19252    );
19253    assert_eq!(
19254        wrap_with_prefix(
19255            String::new(),
19256            "这是什么 \n 钢笔".to_string(),
19257            3,
19258            NonZeroU32::new(4).unwrap(),
19259            false,
19260        ),
19261        "这是什\n么 钢\n"
19262    );
19263}
19264
19265pub trait CollaborationHub {
19266    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19267    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19268    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19269}
19270
19271impl CollaborationHub for Entity<Project> {
19272    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19273        self.read(cx).collaborators()
19274    }
19275
19276    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19277        self.read(cx).user_store().read(cx).participant_indices()
19278    }
19279
19280    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19281        let this = self.read(cx);
19282        let user_ids = this.collaborators().values().map(|c| c.user_id);
19283        this.user_store().read_with(cx, |user_store, cx| {
19284            user_store.participant_names(user_ids, cx)
19285        })
19286    }
19287}
19288
19289pub trait SemanticsProvider {
19290    fn hover(
19291        &self,
19292        buffer: &Entity<Buffer>,
19293        position: text::Anchor,
19294        cx: &mut App,
19295    ) -> Option<Task<Vec<project::Hover>>>;
19296
19297    fn inline_values(
19298        &self,
19299        buffer_handle: Entity<Buffer>,
19300        range: Range<text::Anchor>,
19301        cx: &mut App,
19302    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19303
19304    fn inlay_hints(
19305        &self,
19306        buffer_handle: Entity<Buffer>,
19307        range: Range<text::Anchor>,
19308        cx: &mut App,
19309    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19310
19311    fn resolve_inlay_hint(
19312        &self,
19313        hint: InlayHint,
19314        buffer_handle: Entity<Buffer>,
19315        server_id: LanguageServerId,
19316        cx: &mut App,
19317    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19318
19319    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19320
19321    fn document_highlights(
19322        &self,
19323        buffer: &Entity<Buffer>,
19324        position: text::Anchor,
19325        cx: &mut App,
19326    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19327
19328    fn definitions(
19329        &self,
19330        buffer: &Entity<Buffer>,
19331        position: text::Anchor,
19332        kind: GotoDefinitionKind,
19333        cx: &mut App,
19334    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19335
19336    fn range_for_rename(
19337        &self,
19338        buffer: &Entity<Buffer>,
19339        position: text::Anchor,
19340        cx: &mut App,
19341    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19342
19343    fn perform_rename(
19344        &self,
19345        buffer: &Entity<Buffer>,
19346        position: text::Anchor,
19347        new_name: String,
19348        cx: &mut App,
19349    ) -> Option<Task<Result<ProjectTransaction>>>;
19350}
19351
19352pub trait CompletionProvider {
19353    fn completions(
19354        &self,
19355        excerpt_id: ExcerptId,
19356        buffer: &Entity<Buffer>,
19357        buffer_position: text::Anchor,
19358        trigger: CompletionContext,
19359        window: &mut Window,
19360        cx: &mut Context<Editor>,
19361    ) -> Task<Result<Option<Vec<Completion>>>>;
19362
19363    fn resolve_completions(
19364        &self,
19365        buffer: Entity<Buffer>,
19366        completion_indices: Vec<usize>,
19367        completions: Rc<RefCell<Box<[Completion]>>>,
19368        cx: &mut Context<Editor>,
19369    ) -> Task<Result<bool>>;
19370
19371    fn apply_additional_edits_for_completion(
19372        &self,
19373        _buffer: Entity<Buffer>,
19374        _completions: Rc<RefCell<Box<[Completion]>>>,
19375        _completion_index: usize,
19376        _push_to_history: bool,
19377        _cx: &mut Context<Editor>,
19378    ) -> Task<Result<Option<language::Transaction>>> {
19379        Task::ready(Ok(None))
19380    }
19381
19382    fn is_completion_trigger(
19383        &self,
19384        buffer: &Entity<Buffer>,
19385        position: language::Anchor,
19386        text: &str,
19387        trigger_in_words: bool,
19388        cx: &mut Context<Editor>,
19389    ) -> bool;
19390
19391    fn sort_completions(&self) -> bool {
19392        true
19393    }
19394
19395    fn filter_completions(&self) -> bool {
19396        true
19397    }
19398}
19399
19400pub trait CodeActionProvider {
19401    fn id(&self) -> Arc<str>;
19402
19403    fn code_actions(
19404        &self,
19405        buffer: &Entity<Buffer>,
19406        range: Range<text::Anchor>,
19407        window: &mut Window,
19408        cx: &mut App,
19409    ) -> Task<Result<Vec<CodeAction>>>;
19410
19411    fn apply_code_action(
19412        &self,
19413        buffer_handle: Entity<Buffer>,
19414        action: CodeAction,
19415        excerpt_id: ExcerptId,
19416        push_to_history: bool,
19417        window: &mut Window,
19418        cx: &mut App,
19419    ) -> Task<Result<ProjectTransaction>>;
19420}
19421
19422impl CodeActionProvider for Entity<Project> {
19423    fn id(&self) -> Arc<str> {
19424        "project".into()
19425    }
19426
19427    fn code_actions(
19428        &self,
19429        buffer: &Entity<Buffer>,
19430        range: Range<text::Anchor>,
19431        _window: &mut Window,
19432        cx: &mut App,
19433    ) -> Task<Result<Vec<CodeAction>>> {
19434        self.update(cx, |project, cx| {
19435            let code_lens = project.code_lens(buffer, range.clone(), cx);
19436            let code_actions = project.code_actions(buffer, range, None, cx);
19437            cx.background_spawn(async move {
19438                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19439                Ok(code_lens
19440                    .context("code lens fetch")?
19441                    .into_iter()
19442                    .chain(code_actions.context("code action fetch")?)
19443                    .collect())
19444            })
19445        })
19446    }
19447
19448    fn apply_code_action(
19449        &self,
19450        buffer_handle: Entity<Buffer>,
19451        action: CodeAction,
19452        _excerpt_id: ExcerptId,
19453        push_to_history: bool,
19454        _window: &mut Window,
19455        cx: &mut App,
19456    ) -> Task<Result<ProjectTransaction>> {
19457        self.update(cx, |project, cx| {
19458            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19459        })
19460    }
19461}
19462
19463fn snippet_completions(
19464    project: &Project,
19465    buffer: &Entity<Buffer>,
19466    buffer_position: text::Anchor,
19467    cx: &mut App,
19468) -> Task<Result<Vec<Completion>>> {
19469    let languages = buffer.read(cx).languages_at(buffer_position);
19470    let snippet_store = project.snippets().read(cx);
19471
19472    let scopes: Vec<_> = languages
19473        .iter()
19474        .filter_map(|language| {
19475            let language_name = language.lsp_id();
19476            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19477
19478            if snippets.is_empty() {
19479                None
19480            } else {
19481                Some((language.default_scope(), snippets))
19482            }
19483        })
19484        .collect();
19485
19486    if scopes.is_empty() {
19487        return Task::ready(Ok(vec![]));
19488    }
19489
19490    let snapshot = buffer.read(cx).text_snapshot();
19491    let chars: String = snapshot
19492        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19493        .collect();
19494    let executor = cx.background_executor().clone();
19495
19496    cx.background_spawn(async move {
19497        let mut all_results: Vec<Completion> = Vec::new();
19498        for (scope, snippets) in scopes.into_iter() {
19499            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19500            let mut last_word = chars
19501                .chars()
19502                .take_while(|c| classifier.is_word(*c))
19503                .collect::<String>();
19504            last_word = last_word.chars().rev().collect();
19505
19506            if last_word.is_empty() {
19507                return Ok(vec![]);
19508            }
19509
19510            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19511            let to_lsp = |point: &text::Anchor| {
19512                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19513                point_to_lsp(end)
19514            };
19515            let lsp_end = to_lsp(&buffer_position);
19516
19517            let candidates = snippets
19518                .iter()
19519                .enumerate()
19520                .flat_map(|(ix, snippet)| {
19521                    snippet
19522                        .prefix
19523                        .iter()
19524                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19525                })
19526                .collect::<Vec<StringMatchCandidate>>();
19527
19528            let mut matches = fuzzy::match_strings(
19529                &candidates,
19530                &last_word,
19531                last_word.chars().any(|c| c.is_uppercase()),
19532                100,
19533                &Default::default(),
19534                executor.clone(),
19535            )
19536            .await;
19537
19538            // Remove all candidates where the query's start does not match the start of any word in the candidate
19539            if let Some(query_start) = last_word.chars().next() {
19540                matches.retain(|string_match| {
19541                    split_words(&string_match.string).any(|word| {
19542                        // Check that the first codepoint of the word as lowercase matches the first
19543                        // codepoint of the query as lowercase
19544                        word.chars()
19545                            .flat_map(|codepoint| codepoint.to_lowercase())
19546                            .zip(query_start.to_lowercase())
19547                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19548                    })
19549                });
19550            }
19551
19552            let matched_strings = matches
19553                .into_iter()
19554                .map(|m| m.string)
19555                .collect::<HashSet<_>>();
19556
19557            let mut result: Vec<Completion> = snippets
19558                .iter()
19559                .filter_map(|snippet| {
19560                    let matching_prefix = snippet
19561                        .prefix
19562                        .iter()
19563                        .find(|prefix| matched_strings.contains(*prefix))?;
19564                    let start = as_offset - last_word.len();
19565                    let start = snapshot.anchor_before(start);
19566                    let range = start..buffer_position;
19567                    let lsp_start = to_lsp(&start);
19568                    let lsp_range = lsp::Range {
19569                        start: lsp_start,
19570                        end: lsp_end,
19571                    };
19572                    Some(Completion {
19573                        replace_range: range,
19574                        new_text: snippet.body.clone(),
19575                        source: CompletionSource::Lsp {
19576                            insert_range: None,
19577                            server_id: LanguageServerId(usize::MAX),
19578                            resolved: true,
19579                            lsp_completion: Box::new(lsp::CompletionItem {
19580                                label: snippet.prefix.first().unwrap().clone(),
19581                                kind: Some(CompletionItemKind::SNIPPET),
19582                                label_details: snippet.description.as_ref().map(|description| {
19583                                    lsp::CompletionItemLabelDetails {
19584                                        detail: Some(description.clone()),
19585                                        description: None,
19586                                    }
19587                                }),
19588                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19589                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19590                                    lsp::InsertReplaceEdit {
19591                                        new_text: snippet.body.clone(),
19592                                        insert: lsp_range,
19593                                        replace: lsp_range,
19594                                    },
19595                                )),
19596                                filter_text: Some(snippet.body.clone()),
19597                                sort_text: Some(char::MAX.to_string()),
19598                                ..lsp::CompletionItem::default()
19599                            }),
19600                            lsp_defaults: None,
19601                        },
19602                        label: CodeLabel {
19603                            text: matching_prefix.clone(),
19604                            runs: Vec::new(),
19605                            filter_range: 0..matching_prefix.len(),
19606                        },
19607                        icon_path: None,
19608                        documentation: snippet.description.clone().map(|description| {
19609                            CompletionDocumentation::SingleLine(description.into())
19610                        }),
19611                        insert_text_mode: None,
19612                        confirm: None,
19613                    })
19614                })
19615                .collect();
19616
19617            all_results.append(&mut result);
19618        }
19619
19620        Ok(all_results)
19621    })
19622}
19623
19624impl CompletionProvider for Entity<Project> {
19625    fn completions(
19626        &self,
19627        _excerpt_id: ExcerptId,
19628        buffer: &Entity<Buffer>,
19629        buffer_position: text::Anchor,
19630        options: CompletionContext,
19631        _window: &mut Window,
19632        cx: &mut Context<Editor>,
19633    ) -> Task<Result<Option<Vec<Completion>>>> {
19634        self.update(cx, |project, cx| {
19635            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19636            let project_completions = project.completions(buffer, buffer_position, options, cx);
19637            cx.background_spawn(async move {
19638                let snippets_completions = snippets.await?;
19639                match project_completions.await? {
19640                    Some(mut completions) => {
19641                        completions.extend(snippets_completions);
19642                        Ok(Some(completions))
19643                    }
19644                    None => {
19645                        if snippets_completions.is_empty() {
19646                            Ok(None)
19647                        } else {
19648                            Ok(Some(snippets_completions))
19649                        }
19650                    }
19651                }
19652            })
19653        })
19654    }
19655
19656    fn resolve_completions(
19657        &self,
19658        buffer: Entity<Buffer>,
19659        completion_indices: Vec<usize>,
19660        completions: Rc<RefCell<Box<[Completion]>>>,
19661        cx: &mut Context<Editor>,
19662    ) -> Task<Result<bool>> {
19663        self.update(cx, |project, cx| {
19664            project.lsp_store().update(cx, |lsp_store, cx| {
19665                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19666            })
19667        })
19668    }
19669
19670    fn apply_additional_edits_for_completion(
19671        &self,
19672        buffer: Entity<Buffer>,
19673        completions: Rc<RefCell<Box<[Completion]>>>,
19674        completion_index: usize,
19675        push_to_history: bool,
19676        cx: &mut Context<Editor>,
19677    ) -> Task<Result<Option<language::Transaction>>> {
19678        self.update(cx, |project, cx| {
19679            project.lsp_store().update(cx, |lsp_store, cx| {
19680                lsp_store.apply_additional_edits_for_completion(
19681                    buffer,
19682                    completions,
19683                    completion_index,
19684                    push_to_history,
19685                    cx,
19686                )
19687            })
19688        })
19689    }
19690
19691    fn is_completion_trigger(
19692        &self,
19693        buffer: &Entity<Buffer>,
19694        position: language::Anchor,
19695        text: &str,
19696        trigger_in_words: bool,
19697        cx: &mut Context<Editor>,
19698    ) -> bool {
19699        let mut chars = text.chars();
19700        let char = if let Some(char) = chars.next() {
19701            char
19702        } else {
19703            return false;
19704        };
19705        if chars.next().is_some() {
19706            return false;
19707        }
19708
19709        let buffer = buffer.read(cx);
19710        let snapshot = buffer.snapshot();
19711        if !snapshot.settings_at(position, cx).show_completions_on_input {
19712            return false;
19713        }
19714        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19715        if trigger_in_words && classifier.is_word(char) {
19716            return true;
19717        }
19718
19719        buffer.completion_triggers().contains(text)
19720    }
19721}
19722
19723impl SemanticsProvider for Entity<Project> {
19724    fn hover(
19725        &self,
19726        buffer: &Entity<Buffer>,
19727        position: text::Anchor,
19728        cx: &mut App,
19729    ) -> Option<Task<Vec<project::Hover>>> {
19730        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19731    }
19732
19733    fn document_highlights(
19734        &self,
19735        buffer: &Entity<Buffer>,
19736        position: text::Anchor,
19737        cx: &mut App,
19738    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19739        Some(self.update(cx, |project, cx| {
19740            project.document_highlights(buffer, position, cx)
19741        }))
19742    }
19743
19744    fn definitions(
19745        &self,
19746        buffer: &Entity<Buffer>,
19747        position: text::Anchor,
19748        kind: GotoDefinitionKind,
19749        cx: &mut App,
19750    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19751        Some(self.update(cx, |project, cx| match kind {
19752            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19753            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19754            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19755            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19756        }))
19757    }
19758
19759    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19760        // TODO: make this work for remote projects
19761        self.update(cx, |project, cx| {
19762            if project
19763                .active_debug_session(cx)
19764                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19765            {
19766                return true;
19767            }
19768
19769            buffer.update(cx, |buffer, cx| {
19770                project.any_language_server_supports_inlay_hints(buffer, cx)
19771            })
19772        })
19773    }
19774
19775    fn inline_values(
19776        &self,
19777        buffer_handle: Entity<Buffer>,
19778        range: Range<text::Anchor>,
19779        cx: &mut App,
19780    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19781        self.update(cx, |project, cx| {
19782            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19783
19784            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19785        })
19786    }
19787
19788    fn inlay_hints(
19789        &self,
19790        buffer_handle: Entity<Buffer>,
19791        range: Range<text::Anchor>,
19792        cx: &mut App,
19793    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19794        Some(self.update(cx, |project, cx| {
19795            project.inlay_hints(buffer_handle, range, cx)
19796        }))
19797    }
19798
19799    fn resolve_inlay_hint(
19800        &self,
19801        hint: InlayHint,
19802        buffer_handle: Entity<Buffer>,
19803        server_id: LanguageServerId,
19804        cx: &mut App,
19805    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19806        Some(self.update(cx, |project, cx| {
19807            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19808        }))
19809    }
19810
19811    fn range_for_rename(
19812        &self,
19813        buffer: &Entity<Buffer>,
19814        position: text::Anchor,
19815        cx: &mut App,
19816    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19817        Some(self.update(cx, |project, cx| {
19818            let buffer = buffer.clone();
19819            let task = project.prepare_rename(buffer.clone(), position, cx);
19820            cx.spawn(async move |_, cx| {
19821                Ok(match task.await? {
19822                    PrepareRenameResponse::Success(range) => Some(range),
19823                    PrepareRenameResponse::InvalidPosition => None,
19824                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19825                        // Fallback on using TreeSitter info to determine identifier range
19826                        buffer.update(cx, |buffer, _| {
19827                            let snapshot = buffer.snapshot();
19828                            let (range, kind) = snapshot.surrounding_word(position);
19829                            if kind != Some(CharKind::Word) {
19830                                return None;
19831                            }
19832                            Some(
19833                                snapshot.anchor_before(range.start)
19834                                    ..snapshot.anchor_after(range.end),
19835                            )
19836                        })?
19837                    }
19838                })
19839            })
19840        }))
19841    }
19842
19843    fn perform_rename(
19844        &self,
19845        buffer: &Entity<Buffer>,
19846        position: text::Anchor,
19847        new_name: String,
19848        cx: &mut App,
19849    ) -> Option<Task<Result<ProjectTransaction>>> {
19850        Some(self.update(cx, |project, cx| {
19851            project.perform_rename(buffer.clone(), position, new_name, cx)
19852        }))
19853    }
19854}
19855
19856fn inlay_hint_settings(
19857    location: Anchor,
19858    snapshot: &MultiBufferSnapshot,
19859    cx: &mut Context<Editor>,
19860) -> InlayHintSettings {
19861    let file = snapshot.file_at(location);
19862    let language = snapshot.language_at(location).map(|l| l.name());
19863    language_settings(language, file, cx).inlay_hints
19864}
19865
19866fn consume_contiguous_rows(
19867    contiguous_row_selections: &mut Vec<Selection<Point>>,
19868    selection: &Selection<Point>,
19869    display_map: &DisplaySnapshot,
19870    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19871) -> (MultiBufferRow, MultiBufferRow) {
19872    contiguous_row_selections.push(selection.clone());
19873    let start_row = MultiBufferRow(selection.start.row);
19874    let mut end_row = ending_row(selection, display_map);
19875
19876    while let Some(next_selection) = selections.peek() {
19877        if next_selection.start.row <= end_row.0 {
19878            end_row = ending_row(next_selection, display_map);
19879            contiguous_row_selections.push(selections.next().unwrap().clone());
19880        } else {
19881            break;
19882        }
19883    }
19884    (start_row, end_row)
19885}
19886
19887fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19888    if next_selection.end.column > 0 || next_selection.is_empty() {
19889        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19890    } else {
19891        MultiBufferRow(next_selection.end.row)
19892    }
19893}
19894
19895impl EditorSnapshot {
19896    pub fn remote_selections_in_range<'a>(
19897        &'a self,
19898        range: &'a Range<Anchor>,
19899        collaboration_hub: &dyn CollaborationHub,
19900        cx: &'a App,
19901    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19902        let participant_names = collaboration_hub.user_names(cx);
19903        let participant_indices = collaboration_hub.user_participant_indices(cx);
19904        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19905        let collaborators_by_replica_id = collaborators_by_peer_id
19906            .iter()
19907            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19908            .collect::<HashMap<_, _>>();
19909        self.buffer_snapshot
19910            .selections_in_range(range, false)
19911            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19912                if replica_id == AGENT_REPLICA_ID {
19913                    Some(RemoteSelection {
19914                        replica_id,
19915                        selection,
19916                        cursor_shape,
19917                        line_mode,
19918                        collaborator_id: CollaboratorId::Agent,
19919                        user_name: Some("Agent".into()),
19920                        color: cx.theme().players().agent(),
19921                    })
19922                } else {
19923                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19924                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19925                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19926                    Some(RemoteSelection {
19927                        replica_id,
19928                        selection,
19929                        cursor_shape,
19930                        line_mode,
19931                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19932                        user_name,
19933                        color: if let Some(index) = participant_index {
19934                            cx.theme().players().color_for_participant(index.0)
19935                        } else {
19936                            cx.theme().players().absent()
19937                        },
19938                    })
19939                }
19940            })
19941    }
19942
19943    pub fn hunks_for_ranges(
19944        &self,
19945        ranges: impl IntoIterator<Item = Range<Point>>,
19946    ) -> Vec<MultiBufferDiffHunk> {
19947        let mut hunks = Vec::new();
19948        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19949            HashMap::default();
19950        for query_range in ranges {
19951            let query_rows =
19952                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19953            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19954                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19955            ) {
19956                // Include deleted hunks that are adjacent to the query range, because
19957                // otherwise they would be missed.
19958                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19959                if hunk.status().is_deleted() {
19960                    intersects_range |= hunk.row_range.start == query_rows.end;
19961                    intersects_range |= hunk.row_range.end == query_rows.start;
19962                }
19963                if intersects_range {
19964                    if !processed_buffer_rows
19965                        .entry(hunk.buffer_id)
19966                        .or_default()
19967                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19968                    {
19969                        continue;
19970                    }
19971                    hunks.push(hunk);
19972                }
19973            }
19974        }
19975
19976        hunks
19977    }
19978
19979    fn display_diff_hunks_for_rows<'a>(
19980        &'a self,
19981        display_rows: Range<DisplayRow>,
19982        folded_buffers: &'a HashSet<BufferId>,
19983    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19984        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19985        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19986
19987        self.buffer_snapshot
19988            .diff_hunks_in_range(buffer_start..buffer_end)
19989            .filter_map(|hunk| {
19990                if folded_buffers.contains(&hunk.buffer_id) {
19991                    return None;
19992                }
19993
19994                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19995                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19996
19997                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19998                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19999
20000                let display_hunk = if hunk_display_start.column() != 0 {
20001                    DisplayDiffHunk::Folded {
20002                        display_row: hunk_display_start.row(),
20003                    }
20004                } else {
20005                    let mut end_row = hunk_display_end.row();
20006                    if hunk_display_end.column() > 0 {
20007                        end_row.0 += 1;
20008                    }
20009                    let is_created_file = hunk.is_created_file();
20010                    DisplayDiffHunk::Unfolded {
20011                        status: hunk.status(),
20012                        diff_base_byte_range: hunk.diff_base_byte_range,
20013                        display_row_range: hunk_display_start.row()..end_row,
20014                        multi_buffer_range: Anchor::range_in_buffer(
20015                            hunk.excerpt_id,
20016                            hunk.buffer_id,
20017                            hunk.buffer_range,
20018                        ),
20019                        is_created_file,
20020                    }
20021                };
20022
20023                Some(display_hunk)
20024            })
20025    }
20026
20027    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20028        self.display_snapshot.buffer_snapshot.language_at(position)
20029    }
20030
20031    pub fn is_focused(&self) -> bool {
20032        self.is_focused
20033    }
20034
20035    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20036        self.placeholder_text.as_ref()
20037    }
20038
20039    pub fn scroll_position(&self) -> gpui::Point<f32> {
20040        self.scroll_anchor.scroll_position(&self.display_snapshot)
20041    }
20042
20043    fn gutter_dimensions(
20044        &self,
20045        font_id: FontId,
20046        font_size: Pixels,
20047        max_line_number_width: Pixels,
20048        cx: &App,
20049    ) -> Option<GutterDimensions> {
20050        if !self.show_gutter {
20051            return None;
20052        }
20053
20054        let descent = cx.text_system().descent(font_id, font_size);
20055        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20056        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20057
20058        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20059            matches!(
20060                ProjectSettings::get_global(cx).git.git_gutter,
20061                Some(GitGutterSetting::TrackedFiles)
20062            )
20063        });
20064        let gutter_settings = EditorSettings::get_global(cx).gutter;
20065        let show_line_numbers = self
20066            .show_line_numbers
20067            .unwrap_or(gutter_settings.line_numbers);
20068        let line_gutter_width = if show_line_numbers {
20069            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20070            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20071            max_line_number_width.max(min_width_for_number_on_gutter)
20072        } else {
20073            0.0.into()
20074        };
20075
20076        let show_code_actions = self
20077            .show_code_actions
20078            .unwrap_or(gutter_settings.code_actions);
20079
20080        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20081        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20082
20083        let git_blame_entries_width =
20084            self.git_blame_gutter_max_author_length
20085                .map(|max_author_length| {
20086                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20087                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20088
20089                    /// The number of characters to dedicate to gaps and margins.
20090                    const SPACING_WIDTH: usize = 4;
20091
20092                    let max_char_count = max_author_length.min(renderer.max_author_length())
20093                        + ::git::SHORT_SHA_LENGTH
20094                        + MAX_RELATIVE_TIMESTAMP.len()
20095                        + SPACING_WIDTH;
20096
20097                    em_advance * max_char_count
20098                });
20099
20100        let is_singleton = self.buffer_snapshot.is_singleton();
20101
20102        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20103        left_padding += if !is_singleton {
20104            em_width * 4.0
20105        } else if show_code_actions || show_runnables || show_breakpoints {
20106            em_width * 3.0
20107        } else if show_git_gutter && show_line_numbers {
20108            em_width * 2.0
20109        } else if show_git_gutter || show_line_numbers {
20110            em_width
20111        } else {
20112            px(0.)
20113        };
20114
20115        let shows_folds = is_singleton && gutter_settings.folds;
20116
20117        let right_padding = if shows_folds && show_line_numbers {
20118            em_width * 4.0
20119        } else if shows_folds || (!is_singleton && show_line_numbers) {
20120            em_width * 3.0
20121        } else if show_line_numbers {
20122            em_width
20123        } else {
20124            px(0.)
20125        };
20126
20127        Some(GutterDimensions {
20128            left_padding,
20129            right_padding,
20130            width: line_gutter_width + left_padding + right_padding,
20131            margin: -descent,
20132            git_blame_entries_width,
20133        })
20134    }
20135
20136    pub fn render_crease_toggle(
20137        &self,
20138        buffer_row: MultiBufferRow,
20139        row_contains_cursor: bool,
20140        editor: Entity<Editor>,
20141        window: &mut Window,
20142        cx: &mut App,
20143    ) -> Option<AnyElement> {
20144        let folded = self.is_line_folded(buffer_row);
20145        let mut is_foldable = false;
20146
20147        if let Some(crease) = self
20148            .crease_snapshot
20149            .query_row(buffer_row, &self.buffer_snapshot)
20150        {
20151            is_foldable = true;
20152            match crease {
20153                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20154                    if let Some(render_toggle) = render_toggle {
20155                        let toggle_callback =
20156                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20157                                if folded {
20158                                    editor.update(cx, |editor, cx| {
20159                                        editor.fold_at(buffer_row, window, cx)
20160                                    });
20161                                } else {
20162                                    editor.update(cx, |editor, cx| {
20163                                        editor.unfold_at(buffer_row, window, cx)
20164                                    });
20165                                }
20166                            });
20167                        return Some((render_toggle)(
20168                            buffer_row,
20169                            folded,
20170                            toggle_callback,
20171                            window,
20172                            cx,
20173                        ));
20174                    }
20175                }
20176            }
20177        }
20178
20179        is_foldable |= self.starts_indent(buffer_row);
20180
20181        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20182            Some(
20183                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20184                    .toggle_state(folded)
20185                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20186                        if folded {
20187                            this.unfold_at(buffer_row, window, cx);
20188                        } else {
20189                            this.fold_at(buffer_row, window, cx);
20190                        }
20191                    }))
20192                    .into_any_element(),
20193            )
20194        } else {
20195            None
20196        }
20197    }
20198
20199    pub fn render_crease_trailer(
20200        &self,
20201        buffer_row: MultiBufferRow,
20202        window: &mut Window,
20203        cx: &mut App,
20204    ) -> Option<AnyElement> {
20205        let folded = self.is_line_folded(buffer_row);
20206        if let Crease::Inline { render_trailer, .. } = self
20207            .crease_snapshot
20208            .query_row(buffer_row, &self.buffer_snapshot)?
20209        {
20210            let render_trailer = render_trailer.as_ref()?;
20211            Some(render_trailer(buffer_row, folded, window, cx))
20212        } else {
20213            None
20214        }
20215    }
20216}
20217
20218impl Deref for EditorSnapshot {
20219    type Target = DisplaySnapshot;
20220
20221    fn deref(&self) -> &Self::Target {
20222        &self.display_snapshot
20223    }
20224}
20225
20226#[derive(Clone, Debug, PartialEq, Eq)]
20227pub enum EditorEvent {
20228    InputIgnored {
20229        text: Arc<str>,
20230    },
20231    InputHandled {
20232        utf16_range_to_replace: Option<Range<isize>>,
20233        text: Arc<str>,
20234    },
20235    ExcerptsAdded {
20236        buffer: Entity<Buffer>,
20237        predecessor: ExcerptId,
20238        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20239    },
20240    ExcerptsRemoved {
20241        ids: Vec<ExcerptId>,
20242        removed_buffer_ids: Vec<BufferId>,
20243    },
20244    BufferFoldToggled {
20245        ids: Vec<ExcerptId>,
20246        folded: bool,
20247    },
20248    ExcerptsEdited {
20249        ids: Vec<ExcerptId>,
20250    },
20251    ExcerptsExpanded {
20252        ids: Vec<ExcerptId>,
20253    },
20254    BufferEdited,
20255    Edited {
20256        transaction_id: clock::Lamport,
20257    },
20258    Reparsed(BufferId),
20259    Focused,
20260    FocusedIn,
20261    Blurred,
20262    DirtyChanged,
20263    Saved,
20264    TitleChanged,
20265    DiffBaseChanged,
20266    SelectionsChanged {
20267        local: bool,
20268    },
20269    ScrollPositionChanged {
20270        local: bool,
20271        autoscroll: bool,
20272    },
20273    Closed,
20274    TransactionUndone {
20275        transaction_id: clock::Lamport,
20276    },
20277    TransactionBegun {
20278        transaction_id: clock::Lamport,
20279    },
20280    Reloaded,
20281    CursorShapeChanged,
20282    PushedToNavHistory {
20283        anchor: Anchor,
20284        is_deactivate: bool,
20285    },
20286}
20287
20288impl EventEmitter<EditorEvent> for Editor {}
20289
20290impl Focusable for Editor {
20291    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20292        self.focus_handle.clone()
20293    }
20294}
20295
20296impl Render for Editor {
20297    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20298        let settings = ThemeSettings::get_global(cx);
20299
20300        let mut text_style = match self.mode {
20301            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20302                color: cx.theme().colors().editor_foreground,
20303                font_family: settings.ui_font.family.clone(),
20304                font_features: settings.ui_font.features.clone(),
20305                font_fallbacks: settings.ui_font.fallbacks.clone(),
20306                font_size: rems(0.875).into(),
20307                font_weight: settings.ui_font.weight,
20308                line_height: relative(settings.buffer_line_height.value()),
20309                ..Default::default()
20310            },
20311            EditorMode::Full { .. } => TextStyle {
20312                color: cx.theme().colors().editor_foreground,
20313                font_family: settings.buffer_font.family.clone(),
20314                font_features: settings.buffer_font.features.clone(),
20315                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20316                font_size: settings.buffer_font_size(cx).into(),
20317                font_weight: settings.buffer_font.weight,
20318                line_height: relative(settings.buffer_line_height.value()),
20319                ..Default::default()
20320            },
20321        };
20322        if let Some(text_style_refinement) = &self.text_style_refinement {
20323            text_style.refine(text_style_refinement)
20324        }
20325
20326        let background = match self.mode {
20327            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20328            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20329            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20330        };
20331
20332        EditorElement::new(
20333            &cx.entity(),
20334            EditorStyle {
20335                background,
20336                horizontal_padding: Pixels::default(),
20337                local_player: cx.theme().players().local(),
20338                text: text_style,
20339                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20340                syntax: cx.theme().syntax().clone(),
20341                status: cx.theme().status().clone(),
20342                inlay_hints_style: make_inlay_hints_style(cx),
20343                inline_completion_styles: make_suggestion_styles(cx),
20344                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20345            },
20346        )
20347    }
20348}
20349
20350impl EntityInputHandler for Editor {
20351    fn text_for_range(
20352        &mut self,
20353        range_utf16: Range<usize>,
20354        adjusted_range: &mut Option<Range<usize>>,
20355        _: &mut Window,
20356        cx: &mut Context<Self>,
20357    ) -> Option<String> {
20358        let snapshot = self.buffer.read(cx).read(cx);
20359        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20360        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20361        if (start.0..end.0) != range_utf16 {
20362            adjusted_range.replace(start.0..end.0);
20363        }
20364        Some(snapshot.text_for_range(start..end).collect())
20365    }
20366
20367    fn selected_text_range(
20368        &mut self,
20369        ignore_disabled_input: bool,
20370        _: &mut Window,
20371        cx: &mut Context<Self>,
20372    ) -> Option<UTF16Selection> {
20373        // Prevent the IME menu from appearing when holding down an alphabetic key
20374        // while input is disabled.
20375        if !ignore_disabled_input && !self.input_enabled {
20376            return None;
20377        }
20378
20379        let selection = self.selections.newest::<OffsetUtf16>(cx);
20380        let range = selection.range();
20381
20382        Some(UTF16Selection {
20383            range: range.start.0..range.end.0,
20384            reversed: selection.reversed,
20385        })
20386    }
20387
20388    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20389        let snapshot = self.buffer.read(cx).read(cx);
20390        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20391        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20392    }
20393
20394    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20395        self.clear_highlights::<InputComposition>(cx);
20396        self.ime_transaction.take();
20397    }
20398
20399    fn replace_text_in_range(
20400        &mut self,
20401        range_utf16: Option<Range<usize>>,
20402        text: &str,
20403        window: &mut Window,
20404        cx: &mut Context<Self>,
20405    ) {
20406        if !self.input_enabled {
20407            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20408            return;
20409        }
20410
20411        self.transact(window, cx, |this, window, cx| {
20412            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20413                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20414                Some(this.selection_replacement_ranges(range_utf16, cx))
20415            } else {
20416                this.marked_text_ranges(cx)
20417            };
20418
20419            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20420                let newest_selection_id = this.selections.newest_anchor().id;
20421                this.selections
20422                    .all::<OffsetUtf16>(cx)
20423                    .iter()
20424                    .zip(ranges_to_replace.iter())
20425                    .find_map(|(selection, range)| {
20426                        if selection.id == newest_selection_id {
20427                            Some(
20428                                (range.start.0 as isize - selection.head().0 as isize)
20429                                    ..(range.end.0 as isize - selection.head().0 as isize),
20430                            )
20431                        } else {
20432                            None
20433                        }
20434                    })
20435            });
20436
20437            cx.emit(EditorEvent::InputHandled {
20438                utf16_range_to_replace: range_to_replace,
20439                text: text.into(),
20440            });
20441
20442            if let Some(new_selected_ranges) = new_selected_ranges {
20443                this.change_selections(None, window, cx, |selections| {
20444                    selections.select_ranges(new_selected_ranges)
20445                });
20446                this.backspace(&Default::default(), window, cx);
20447            }
20448
20449            this.handle_input(text, window, cx);
20450        });
20451
20452        if let Some(transaction) = self.ime_transaction {
20453            self.buffer.update(cx, |buffer, cx| {
20454                buffer.group_until_transaction(transaction, cx);
20455            });
20456        }
20457
20458        self.unmark_text(window, cx);
20459    }
20460
20461    fn replace_and_mark_text_in_range(
20462        &mut self,
20463        range_utf16: Option<Range<usize>>,
20464        text: &str,
20465        new_selected_range_utf16: Option<Range<usize>>,
20466        window: &mut Window,
20467        cx: &mut Context<Self>,
20468    ) {
20469        if !self.input_enabled {
20470            return;
20471        }
20472
20473        let transaction = self.transact(window, cx, |this, window, cx| {
20474            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20475                let snapshot = this.buffer.read(cx).read(cx);
20476                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20477                    for marked_range in &mut marked_ranges {
20478                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20479                        marked_range.start.0 += relative_range_utf16.start;
20480                        marked_range.start =
20481                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20482                        marked_range.end =
20483                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20484                    }
20485                }
20486                Some(marked_ranges)
20487            } else if let Some(range_utf16) = range_utf16 {
20488                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20489                Some(this.selection_replacement_ranges(range_utf16, cx))
20490            } else {
20491                None
20492            };
20493
20494            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20495                let newest_selection_id = this.selections.newest_anchor().id;
20496                this.selections
20497                    .all::<OffsetUtf16>(cx)
20498                    .iter()
20499                    .zip(ranges_to_replace.iter())
20500                    .find_map(|(selection, range)| {
20501                        if selection.id == newest_selection_id {
20502                            Some(
20503                                (range.start.0 as isize - selection.head().0 as isize)
20504                                    ..(range.end.0 as isize - selection.head().0 as isize),
20505                            )
20506                        } else {
20507                            None
20508                        }
20509                    })
20510            });
20511
20512            cx.emit(EditorEvent::InputHandled {
20513                utf16_range_to_replace: range_to_replace,
20514                text: text.into(),
20515            });
20516
20517            if let Some(ranges) = ranges_to_replace {
20518                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20519            }
20520
20521            let marked_ranges = {
20522                let snapshot = this.buffer.read(cx).read(cx);
20523                this.selections
20524                    .disjoint_anchors()
20525                    .iter()
20526                    .map(|selection| {
20527                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20528                    })
20529                    .collect::<Vec<_>>()
20530            };
20531
20532            if text.is_empty() {
20533                this.unmark_text(window, cx);
20534            } else {
20535                this.highlight_text::<InputComposition>(
20536                    marked_ranges.clone(),
20537                    HighlightStyle {
20538                        underline: Some(UnderlineStyle {
20539                            thickness: px(1.),
20540                            color: None,
20541                            wavy: false,
20542                        }),
20543                        ..Default::default()
20544                    },
20545                    cx,
20546                );
20547            }
20548
20549            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20550            let use_autoclose = this.use_autoclose;
20551            let use_auto_surround = this.use_auto_surround;
20552            this.set_use_autoclose(false);
20553            this.set_use_auto_surround(false);
20554            this.handle_input(text, window, cx);
20555            this.set_use_autoclose(use_autoclose);
20556            this.set_use_auto_surround(use_auto_surround);
20557
20558            if let Some(new_selected_range) = new_selected_range_utf16 {
20559                let snapshot = this.buffer.read(cx).read(cx);
20560                let new_selected_ranges = marked_ranges
20561                    .into_iter()
20562                    .map(|marked_range| {
20563                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20564                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20565                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20566                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20567                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20568                    })
20569                    .collect::<Vec<_>>();
20570
20571                drop(snapshot);
20572                this.change_selections(None, window, cx, |selections| {
20573                    selections.select_ranges(new_selected_ranges)
20574                });
20575            }
20576        });
20577
20578        self.ime_transaction = self.ime_transaction.or(transaction);
20579        if let Some(transaction) = self.ime_transaction {
20580            self.buffer.update(cx, |buffer, cx| {
20581                buffer.group_until_transaction(transaction, cx);
20582            });
20583        }
20584
20585        if self.text_highlights::<InputComposition>(cx).is_none() {
20586            self.ime_transaction.take();
20587        }
20588    }
20589
20590    fn bounds_for_range(
20591        &mut self,
20592        range_utf16: Range<usize>,
20593        element_bounds: gpui::Bounds<Pixels>,
20594        window: &mut Window,
20595        cx: &mut Context<Self>,
20596    ) -> Option<gpui::Bounds<Pixels>> {
20597        let text_layout_details = self.text_layout_details(window);
20598        let gpui::Size {
20599            width: em_width,
20600            height: line_height,
20601        } = self.character_size(window);
20602
20603        let snapshot = self.snapshot(window, cx);
20604        let scroll_position = snapshot.scroll_position();
20605        let scroll_left = scroll_position.x * em_width;
20606
20607        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20608        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20609            + self.gutter_dimensions.width
20610            + self.gutter_dimensions.margin;
20611        let y = line_height * (start.row().as_f32() - scroll_position.y);
20612
20613        Some(Bounds {
20614            origin: element_bounds.origin + point(x, y),
20615            size: size(em_width, line_height),
20616        })
20617    }
20618
20619    fn character_index_for_point(
20620        &mut self,
20621        point: gpui::Point<Pixels>,
20622        _window: &mut Window,
20623        _cx: &mut Context<Self>,
20624    ) -> Option<usize> {
20625        let position_map = self.last_position_map.as_ref()?;
20626        if !position_map.text_hitbox.contains(&point) {
20627            return None;
20628        }
20629        let display_point = position_map.point_for_position(point).previous_valid;
20630        let anchor = position_map
20631            .snapshot
20632            .display_point_to_anchor(display_point, Bias::Left);
20633        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20634        Some(utf16_offset.0)
20635    }
20636}
20637
20638trait SelectionExt {
20639    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20640    fn spanned_rows(
20641        &self,
20642        include_end_if_at_line_start: bool,
20643        map: &DisplaySnapshot,
20644    ) -> Range<MultiBufferRow>;
20645}
20646
20647impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20648    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20649        let start = self
20650            .start
20651            .to_point(&map.buffer_snapshot)
20652            .to_display_point(map);
20653        let end = self
20654            .end
20655            .to_point(&map.buffer_snapshot)
20656            .to_display_point(map);
20657        if self.reversed {
20658            end..start
20659        } else {
20660            start..end
20661        }
20662    }
20663
20664    fn spanned_rows(
20665        &self,
20666        include_end_if_at_line_start: bool,
20667        map: &DisplaySnapshot,
20668    ) -> Range<MultiBufferRow> {
20669        let start = self.start.to_point(&map.buffer_snapshot);
20670        let mut end = self.end.to_point(&map.buffer_snapshot);
20671        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20672            end.row -= 1;
20673        }
20674
20675        let buffer_start = map.prev_line_boundary(start).0;
20676        let buffer_end = map.next_line_boundary(end).0;
20677        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20678    }
20679}
20680
20681impl<T: InvalidationRegion> InvalidationStack<T> {
20682    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20683    where
20684        S: Clone + ToOffset,
20685    {
20686        while let Some(region) = self.last() {
20687            let all_selections_inside_invalidation_ranges =
20688                if selections.len() == region.ranges().len() {
20689                    selections
20690                        .iter()
20691                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20692                        .all(|(selection, invalidation_range)| {
20693                            let head = selection.head().to_offset(buffer);
20694                            invalidation_range.start <= head && invalidation_range.end >= head
20695                        })
20696                } else {
20697                    false
20698                };
20699
20700            if all_selections_inside_invalidation_ranges {
20701                break;
20702            } else {
20703                self.pop();
20704            }
20705        }
20706    }
20707}
20708
20709impl<T> Default for InvalidationStack<T> {
20710    fn default() -> Self {
20711        Self(Default::default())
20712    }
20713}
20714
20715impl<T> Deref for InvalidationStack<T> {
20716    type Target = Vec<T>;
20717
20718    fn deref(&self) -> &Self::Target {
20719        &self.0
20720    }
20721}
20722
20723impl<T> DerefMut for InvalidationStack<T> {
20724    fn deref_mut(&mut self) -> &mut Self::Target {
20725        &mut self.0
20726    }
20727}
20728
20729impl InvalidationRegion for SnippetState {
20730    fn ranges(&self) -> &[Range<Anchor>] {
20731        &self.ranges[self.active_index]
20732    }
20733}
20734
20735fn inline_completion_edit_text(
20736    current_snapshot: &BufferSnapshot,
20737    edits: &[(Range<Anchor>, String)],
20738    edit_preview: &EditPreview,
20739    include_deletions: bool,
20740    cx: &App,
20741) -> HighlightedText {
20742    let edits = edits
20743        .iter()
20744        .map(|(anchor, text)| {
20745            (
20746                anchor.start.text_anchor..anchor.end.text_anchor,
20747                text.clone(),
20748            )
20749        })
20750        .collect::<Vec<_>>();
20751
20752    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20753}
20754
20755pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20756    match severity {
20757        DiagnosticSeverity::ERROR => colors.error,
20758        DiagnosticSeverity::WARNING => colors.warning,
20759        DiagnosticSeverity::INFORMATION => colors.info,
20760        DiagnosticSeverity::HINT => colors.info,
20761        _ => colors.ignored,
20762    }
20763}
20764
20765pub fn styled_runs_for_code_label<'a>(
20766    label: &'a CodeLabel,
20767    syntax_theme: &'a theme::SyntaxTheme,
20768) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20769    let fade_out = HighlightStyle {
20770        fade_out: Some(0.35),
20771        ..Default::default()
20772    };
20773
20774    let mut prev_end = label.filter_range.end;
20775    label
20776        .runs
20777        .iter()
20778        .enumerate()
20779        .flat_map(move |(ix, (range, highlight_id))| {
20780            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20781                style
20782            } else {
20783                return Default::default();
20784            };
20785            let mut muted_style = style;
20786            muted_style.highlight(fade_out);
20787
20788            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20789            if range.start >= label.filter_range.end {
20790                if range.start > prev_end {
20791                    runs.push((prev_end..range.start, fade_out));
20792                }
20793                runs.push((range.clone(), muted_style));
20794            } else if range.end <= label.filter_range.end {
20795                runs.push((range.clone(), style));
20796            } else {
20797                runs.push((range.start..label.filter_range.end, style));
20798                runs.push((label.filter_range.end..range.end, muted_style));
20799            }
20800            prev_end = cmp::max(prev_end, range.end);
20801
20802            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20803                runs.push((prev_end..label.text.len(), fade_out));
20804            }
20805
20806            runs
20807        })
20808}
20809
20810pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20811    let mut prev_index = 0;
20812    let mut prev_codepoint: Option<char> = None;
20813    text.char_indices()
20814        .chain([(text.len(), '\0')])
20815        .filter_map(move |(index, codepoint)| {
20816            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20817            let is_boundary = index == text.len()
20818                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20819                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20820            if is_boundary {
20821                let chunk = &text[prev_index..index];
20822                prev_index = index;
20823                Some(chunk)
20824            } else {
20825                None
20826            }
20827        })
20828}
20829
20830pub trait RangeToAnchorExt: Sized {
20831    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20832
20833    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20834        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20835        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20836    }
20837}
20838
20839impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20840    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20841        let start_offset = self.start.to_offset(snapshot);
20842        let end_offset = self.end.to_offset(snapshot);
20843        if start_offset == end_offset {
20844            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20845        } else {
20846            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20847        }
20848    }
20849}
20850
20851pub trait RowExt {
20852    fn as_f32(&self) -> f32;
20853
20854    fn next_row(&self) -> Self;
20855
20856    fn previous_row(&self) -> Self;
20857
20858    fn minus(&self, other: Self) -> u32;
20859}
20860
20861impl RowExt for DisplayRow {
20862    fn as_f32(&self) -> f32 {
20863        self.0 as f32
20864    }
20865
20866    fn next_row(&self) -> Self {
20867        Self(self.0 + 1)
20868    }
20869
20870    fn previous_row(&self) -> Self {
20871        Self(self.0.saturating_sub(1))
20872    }
20873
20874    fn minus(&self, other: Self) -> u32 {
20875        self.0 - other.0
20876    }
20877}
20878
20879impl RowExt for MultiBufferRow {
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
20897trait RowRangeExt {
20898    type Row;
20899
20900    fn len(&self) -> usize;
20901
20902    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20903}
20904
20905impl RowRangeExt for Range<MultiBufferRow> {
20906    type Row = MultiBufferRow;
20907
20908    fn len(&self) -> usize {
20909        (self.end.0 - self.start.0) as usize
20910    }
20911
20912    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20913        (self.start.0..self.end.0).map(MultiBufferRow)
20914    }
20915}
20916
20917impl RowRangeExt for Range<DisplayRow> {
20918    type Row = DisplayRow;
20919
20920    fn len(&self) -> usize {
20921        (self.end.0 - self.start.0) as usize
20922    }
20923
20924    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20925        (self.start.0..self.end.0).map(DisplayRow)
20926    }
20927}
20928
20929/// If select range has more than one line, we
20930/// just point the cursor to range.start.
20931fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20932    if range.start.row == range.end.row {
20933        range
20934    } else {
20935        range.start..range.start
20936    }
20937}
20938pub struct KillRing(ClipboardItem);
20939impl Global for KillRing {}
20940
20941const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20942
20943enum BreakpointPromptEditAction {
20944    Log,
20945    Condition,
20946    HitCondition,
20947}
20948
20949struct BreakpointPromptEditor {
20950    pub(crate) prompt: Entity<Editor>,
20951    editor: WeakEntity<Editor>,
20952    breakpoint_anchor: Anchor,
20953    breakpoint: Breakpoint,
20954    edit_action: BreakpointPromptEditAction,
20955    block_ids: HashSet<CustomBlockId>,
20956    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20957    _subscriptions: Vec<Subscription>,
20958}
20959
20960impl BreakpointPromptEditor {
20961    const MAX_LINES: u8 = 4;
20962
20963    fn new(
20964        editor: WeakEntity<Editor>,
20965        breakpoint_anchor: Anchor,
20966        breakpoint: Breakpoint,
20967        edit_action: BreakpointPromptEditAction,
20968        window: &mut Window,
20969        cx: &mut Context<Self>,
20970    ) -> Self {
20971        let base_text = match edit_action {
20972            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20973            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20974            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20975        }
20976        .map(|msg| msg.to_string())
20977        .unwrap_or_default();
20978
20979        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20980        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20981
20982        let prompt = cx.new(|cx| {
20983            let mut prompt = Editor::new(
20984                EditorMode::AutoHeight {
20985                    max_lines: Self::MAX_LINES as usize,
20986                },
20987                buffer,
20988                None,
20989                window,
20990                cx,
20991            );
20992            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20993            prompt.set_show_cursor_when_unfocused(false, cx);
20994            prompt.set_placeholder_text(
20995                match edit_action {
20996                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20997                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20998                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20999                },
21000                cx,
21001            );
21002
21003            prompt
21004        });
21005
21006        Self {
21007            prompt,
21008            editor,
21009            breakpoint_anchor,
21010            breakpoint,
21011            edit_action,
21012            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21013            block_ids: Default::default(),
21014            _subscriptions: vec![],
21015        }
21016    }
21017
21018    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21019        self.block_ids.extend(block_ids)
21020    }
21021
21022    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21023        if let Some(editor) = self.editor.upgrade() {
21024            let message = self
21025                .prompt
21026                .read(cx)
21027                .buffer
21028                .read(cx)
21029                .as_singleton()
21030                .expect("A multi buffer in breakpoint prompt isn't possible")
21031                .read(cx)
21032                .as_rope()
21033                .to_string();
21034
21035            editor.update(cx, |editor, cx| {
21036                editor.edit_breakpoint_at_anchor(
21037                    self.breakpoint_anchor,
21038                    self.breakpoint.clone(),
21039                    match self.edit_action {
21040                        BreakpointPromptEditAction::Log => {
21041                            BreakpointEditAction::EditLogMessage(message.into())
21042                        }
21043                        BreakpointPromptEditAction::Condition => {
21044                            BreakpointEditAction::EditCondition(message.into())
21045                        }
21046                        BreakpointPromptEditAction::HitCondition => {
21047                            BreakpointEditAction::EditHitCondition(message.into())
21048                        }
21049                    },
21050                    cx,
21051                );
21052
21053                editor.remove_blocks(self.block_ids.clone(), None, cx);
21054                cx.focus_self(window);
21055            });
21056        }
21057    }
21058
21059    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21060        self.editor
21061            .update(cx, |editor, cx| {
21062                editor.remove_blocks(self.block_ids.clone(), None, cx);
21063                window.focus(&editor.focus_handle);
21064            })
21065            .log_err();
21066    }
21067
21068    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21069        let settings = ThemeSettings::get_global(cx);
21070        let text_style = TextStyle {
21071            color: if self.prompt.read(cx).read_only(cx) {
21072                cx.theme().colors().text_disabled
21073            } else {
21074                cx.theme().colors().text
21075            },
21076            font_family: settings.buffer_font.family.clone(),
21077            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21078            font_size: settings.buffer_font_size(cx).into(),
21079            font_weight: settings.buffer_font.weight,
21080            line_height: relative(settings.buffer_line_height.value()),
21081            ..Default::default()
21082        };
21083        EditorElement::new(
21084            &self.prompt,
21085            EditorStyle {
21086                background: cx.theme().colors().editor_background,
21087                local_player: cx.theme().players().local(),
21088                text: text_style,
21089                ..Default::default()
21090            },
21091        )
21092    }
21093}
21094
21095impl Render for BreakpointPromptEditor {
21096    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21097        let gutter_dimensions = *self.gutter_dimensions.lock();
21098        h_flex()
21099            .key_context("Editor")
21100            .bg(cx.theme().colors().editor_background)
21101            .border_y_1()
21102            .border_color(cx.theme().status().info_border)
21103            .size_full()
21104            .py(window.line_height() / 2.5)
21105            .on_action(cx.listener(Self::confirm))
21106            .on_action(cx.listener(Self::cancel))
21107            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21108            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21109    }
21110}
21111
21112impl Focusable for BreakpointPromptEditor {
21113    fn focus_handle(&self, cx: &App) -> FocusHandle {
21114        self.prompt.focus_handle(cx)
21115    }
21116}
21117
21118fn all_edits_insertions_or_deletions(
21119    edits: &Vec<(Range<Anchor>, String)>,
21120    snapshot: &MultiBufferSnapshot,
21121) -> bool {
21122    let mut all_insertions = true;
21123    let mut all_deletions = true;
21124
21125    for (range, new_text) in edits.iter() {
21126        let range_is_empty = range.to_offset(&snapshot).is_empty();
21127        let text_is_empty = new_text.is_empty();
21128
21129        if range_is_empty != text_is_empty {
21130            if range_is_empty {
21131                all_deletions = false;
21132            } else {
21133                all_insertions = false;
21134            }
21135        } else {
21136            return false;
21137        }
21138
21139        if !all_insertions && !all_deletions {
21140            return false;
21141        }
21142    }
21143    all_insertions || all_deletions
21144}
21145
21146struct MissingEditPredictionKeybindingTooltip;
21147
21148impl Render for MissingEditPredictionKeybindingTooltip {
21149    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21150        ui::tooltip_container(window, cx, |container, _, cx| {
21151            container
21152                .flex_shrink_0()
21153                .max_w_80()
21154                .min_h(rems_from_px(124.))
21155                .justify_between()
21156                .child(
21157                    v_flex()
21158                        .flex_1()
21159                        .text_ui_sm(cx)
21160                        .child(Label::new("Conflict with Accept Keybinding"))
21161                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21162                )
21163                .child(
21164                    h_flex()
21165                        .pb_1()
21166                        .gap_1()
21167                        .items_end()
21168                        .w_full()
21169                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21170                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21171                        }))
21172                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21173                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21174                        })),
21175                )
21176        })
21177    }
21178}
21179
21180#[derive(Debug, Clone, Copy, PartialEq)]
21181pub struct LineHighlight {
21182    pub background: Background,
21183    pub border: Option<gpui::Hsla>,
21184    pub include_gutter: bool,
21185    pub type_id: Option<TypeId>,
21186}
21187
21188fn render_diff_hunk_controls(
21189    row: u32,
21190    status: &DiffHunkStatus,
21191    hunk_range: Range<Anchor>,
21192    is_created_file: bool,
21193    line_height: Pixels,
21194    editor: &Entity<Editor>,
21195    _window: &mut Window,
21196    cx: &mut App,
21197) -> AnyElement {
21198    h_flex()
21199        .h(line_height)
21200        .mr_1()
21201        .gap_1()
21202        .px_0p5()
21203        .pb_1()
21204        .border_x_1()
21205        .border_b_1()
21206        .border_color(cx.theme().colors().border_variant)
21207        .rounded_b_lg()
21208        .bg(cx.theme().colors().editor_background)
21209        .gap_1()
21210        .occlude()
21211        .shadow_md()
21212        .child(if status.has_secondary_hunk() {
21213            Button::new(("stage", row as u64), "Stage")
21214                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21215                .tooltip({
21216                    let focus_handle = editor.focus_handle(cx);
21217                    move |window, cx| {
21218                        Tooltip::for_action_in(
21219                            "Stage Hunk",
21220                            &::git::ToggleStaged,
21221                            &focus_handle,
21222                            window,
21223                            cx,
21224                        )
21225                    }
21226                })
21227                .on_click({
21228                    let editor = editor.clone();
21229                    move |_event, _window, cx| {
21230                        editor.update(cx, |editor, cx| {
21231                            editor.stage_or_unstage_diff_hunks(
21232                                true,
21233                                vec![hunk_range.start..hunk_range.start],
21234                                cx,
21235                            );
21236                        });
21237                    }
21238                })
21239        } else {
21240            Button::new(("unstage", row as u64), "Unstage")
21241                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21242                .tooltip({
21243                    let focus_handle = editor.focus_handle(cx);
21244                    move |window, cx| {
21245                        Tooltip::for_action_in(
21246                            "Unstage Hunk",
21247                            &::git::ToggleStaged,
21248                            &focus_handle,
21249                            window,
21250                            cx,
21251                        )
21252                    }
21253                })
21254                .on_click({
21255                    let editor = editor.clone();
21256                    move |_event, _window, cx| {
21257                        editor.update(cx, |editor, cx| {
21258                            editor.stage_or_unstage_diff_hunks(
21259                                false,
21260                                vec![hunk_range.start..hunk_range.start],
21261                                cx,
21262                            );
21263                        });
21264                    }
21265                })
21266        })
21267        .child(
21268            Button::new(("restore", row as u64), "Restore")
21269                .tooltip({
21270                    let focus_handle = editor.focus_handle(cx);
21271                    move |window, cx| {
21272                        Tooltip::for_action_in(
21273                            "Restore Hunk",
21274                            &::git::Restore,
21275                            &focus_handle,
21276                            window,
21277                            cx,
21278                        )
21279                    }
21280                })
21281                .on_click({
21282                    let editor = editor.clone();
21283                    move |_event, window, cx| {
21284                        editor.update(cx, |editor, cx| {
21285                            let snapshot = editor.snapshot(window, cx);
21286                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21287                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21288                        });
21289                    }
21290                })
21291                .disabled(is_created_file),
21292        )
21293        .when(
21294            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21295            |el| {
21296                el.child(
21297                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21298                        .shape(IconButtonShape::Square)
21299                        .icon_size(IconSize::Small)
21300                        // .disabled(!has_multiple_hunks)
21301                        .tooltip({
21302                            let focus_handle = editor.focus_handle(cx);
21303                            move |window, cx| {
21304                                Tooltip::for_action_in(
21305                                    "Next Hunk",
21306                                    &GoToHunk,
21307                                    &focus_handle,
21308                                    window,
21309                                    cx,
21310                                )
21311                            }
21312                        })
21313                        .on_click({
21314                            let editor = editor.clone();
21315                            move |_event, window, cx| {
21316                                editor.update(cx, |editor, cx| {
21317                                    let snapshot = editor.snapshot(window, cx);
21318                                    let position =
21319                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21320                                    editor.go_to_hunk_before_or_after_position(
21321                                        &snapshot,
21322                                        position,
21323                                        Direction::Next,
21324                                        window,
21325                                        cx,
21326                                    );
21327                                    editor.expand_selected_diff_hunks(cx);
21328                                });
21329                            }
21330                        }),
21331                )
21332                .child(
21333                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21334                        .shape(IconButtonShape::Square)
21335                        .icon_size(IconSize::Small)
21336                        // .disabled(!has_multiple_hunks)
21337                        .tooltip({
21338                            let focus_handle = editor.focus_handle(cx);
21339                            move |window, cx| {
21340                                Tooltip::for_action_in(
21341                                    "Previous Hunk",
21342                                    &GoToPreviousHunk,
21343                                    &focus_handle,
21344                                    window,
21345                                    cx,
21346                                )
21347                            }
21348                        })
21349                        .on_click({
21350                            let editor = editor.clone();
21351                            move |_event, window, cx| {
21352                                editor.update(cx, |editor, cx| {
21353                                    let snapshot = editor.snapshot(window, cx);
21354                                    let point =
21355                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21356                                    editor.go_to_hunk_before_or_after_position(
21357                                        &snapshot,
21358                                        point,
21359                                        Direction::Prev,
21360                                        window,
21361                                        cx,
21362                                    );
21363                                    editor.expand_selected_diff_hunks(cx);
21364                                });
21365                            }
21366                        }),
21367                )
21368            },
21369        )
21370        .into_any_element()
21371}