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::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::{Debugger, 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    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 DebugCurrentRowHighlight {}
  290enum DocumentHighlightRead {}
  291enum DocumentHighlightWrite {}
  292enum InputComposition {}
  293enum SelectedTextHighlight {}
  294
  295pub enum ConflictsOuter {}
  296pub enum ConflictsOurs {}
  297pub enum ConflictsTheirs {}
  298pub enum ConflictsOursMarker {}
  299pub enum ConflictsTheirsMarker {}
  300
  301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  302pub enum Navigated {
  303    Yes,
  304    No,
  305}
  306
  307impl Navigated {
  308    pub fn from_bool(yes: bool) -> Navigated {
  309        if yes { Navigated::Yes } else { Navigated::No }
  310    }
  311}
  312
  313#[derive(Debug, Clone, PartialEq, Eq)]
  314enum DisplayDiffHunk {
  315    Folded {
  316        display_row: DisplayRow,
  317    },
  318    Unfolded {
  319        is_created_file: bool,
  320        diff_base_byte_range: Range<usize>,
  321        display_row_range: Range<DisplayRow>,
  322        multi_buffer_range: Range<Anchor>,
  323        status: DiffHunkStatus,
  324    },
  325}
  326
  327pub enum HideMouseCursorOrigin {
  328    TypingAction,
  329    MovementAction,
  330}
  331
  332pub fn init_settings(cx: &mut App) {
  333    EditorSettings::register(cx);
  334}
  335
  336pub fn init(cx: &mut App) {
  337    init_settings(cx);
  338
  339    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  340
  341    workspace::register_project_item::<Editor>(cx);
  342    workspace::FollowableViewRegistry::register::<Editor>(cx);
  343    workspace::register_serializable_item::<Editor>(cx);
  344
  345    cx.observe_new(
  346        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  347            workspace.register_action(Editor::new_file);
  348            workspace.register_action(Editor::new_file_vertical);
  349            workspace.register_action(Editor::new_file_horizontal);
  350            workspace.register_action(Editor::cancel_language_server_work);
  351        },
  352    )
  353    .detach();
  354
  355    cx.on_action(move |_: &workspace::NewFile, cx| {
  356        let app_state = workspace::AppState::global(cx);
  357        if let Some(app_state) = app_state.upgrade() {
  358            workspace::open_new(
  359                Default::default(),
  360                app_state,
  361                cx,
  362                |workspace, window, cx| {
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369    cx.on_action(move |_: &workspace::NewWindow, cx| {
  370        let app_state = workspace::AppState::global(cx);
  371        if let Some(app_state) = app_state.upgrade() {
  372            workspace::open_new(
  373                Default::default(),
  374                app_state,
  375                cx,
  376                |workspace, window, cx| {
  377                    cx.activate(true);
  378                    Editor::new_file(workspace, &Default::default(), window, cx)
  379                },
  380            )
  381            .detach();
  382        }
  383    });
  384}
  385
  386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  387    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  388}
  389
  390pub trait DiagnosticRenderer {
  391    fn render_group(
  392        &self,
  393        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  394        buffer_id: BufferId,
  395        snapshot: EditorSnapshot,
  396        editor: WeakEntity<Editor>,
  397        cx: &mut App,
  398    ) -> Vec<BlockProperties<Anchor>>;
  399
  400    fn render_hover(
  401        &self,
  402        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  403        range: Range<Point>,
  404        buffer_id: BufferId,
  405        cx: &mut App,
  406    ) -> Option<Entity<markdown::Markdown>>;
  407
  408    fn open_link(
  409        &self,
  410        editor: &mut Editor,
  411        link: SharedString,
  412        window: &mut Window,
  413        cx: &mut Context<Editor>,
  414    );
  415}
  416
  417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  418
  419impl GlobalDiagnosticRenderer {
  420    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  421        cx.try_global::<Self>().map(|g| g.0.clone())
  422    }
  423}
  424
  425impl gpui::Global for GlobalDiagnosticRenderer {}
  426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  427    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  428}
  429
  430pub struct SearchWithinRange;
  431
  432trait InvalidationRegion {
  433    fn ranges(&self) -> &[Range<Anchor>];
  434}
  435
  436#[derive(Clone, Debug, PartialEq)]
  437pub enum SelectPhase {
  438    Begin {
  439        position: DisplayPoint,
  440        add: bool,
  441        click_count: usize,
  442    },
  443    BeginColumnar {
  444        position: DisplayPoint,
  445        reset: bool,
  446        goal_column: u32,
  447    },
  448    Extend {
  449        position: DisplayPoint,
  450        click_count: usize,
  451    },
  452    Update {
  453        position: DisplayPoint,
  454        goal_column: u32,
  455        scroll_delta: gpui::Point<f32>,
  456    },
  457    End,
  458}
  459
  460#[derive(Clone, Debug)]
  461pub enum SelectMode {
  462    Character,
  463    Word(Range<Anchor>),
  464    Line(Range<Anchor>),
  465    All,
  466}
  467
  468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  469pub enum EditorMode {
  470    SingleLine {
  471        auto_width: bool,
  472    },
  473    AutoHeight {
  474        max_lines: usize,
  475    },
  476    Full {
  477        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  478        scale_ui_elements_with_buffer_font_size: bool,
  479        /// When set to `true`, the editor will render a background for the active line.
  480        show_active_line_background: bool,
  481        /// When set to `true`, the editor's height will be determined by its content.
  482        sized_by_content: bool,
  483    },
  484}
  485
  486impl EditorMode {
  487    pub fn full() -> Self {
  488        Self::Full {
  489            scale_ui_elements_with_buffer_font_size: true,
  490            show_active_line_background: true,
  491            sized_by_content: false,
  492        }
  493    }
  494
  495    pub fn is_full(&self) -> bool {
  496        matches!(self, Self::Full { .. })
  497    }
  498}
  499
  500#[derive(Copy, Clone, Debug)]
  501pub enum SoftWrap {
  502    /// Prefer not to wrap at all.
  503    ///
  504    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  505    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  506    GitDiff,
  507    /// Prefer a single line generally, unless an overly long line is encountered.
  508    None,
  509    /// Soft wrap lines that exceed the editor width.
  510    EditorWidth,
  511    /// Soft wrap lines at the preferred line length.
  512    Column(u32),
  513    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  514    Bounded(u32),
  515}
  516
  517#[derive(Clone)]
  518pub struct EditorStyle {
  519    pub background: Hsla,
  520    pub local_player: PlayerColor,
  521    pub text: TextStyle,
  522    pub scrollbar_width: Pixels,
  523    pub syntax: Arc<SyntaxTheme>,
  524    pub status: StatusColors,
  525    pub inlay_hints_style: HighlightStyle,
  526    pub inline_completion_styles: InlineCompletionStyles,
  527    pub unnecessary_code_fade: f32,
  528}
  529
  530impl Default for EditorStyle {
  531    fn default() -> Self {
  532        Self {
  533            background: Hsla::default(),
  534            local_player: PlayerColor::default(),
  535            text: TextStyle::default(),
  536            scrollbar_width: Pixels::default(),
  537            syntax: Default::default(),
  538            // HACK: Status colors don't have a real default.
  539            // We should look into removing the status colors from the editor
  540            // style and retrieve them directly from the theme.
  541            status: StatusColors::dark(),
  542            inlay_hints_style: HighlightStyle::default(),
  543            inline_completion_styles: InlineCompletionStyles {
  544                insertion: HighlightStyle::default(),
  545                whitespace: HighlightStyle::default(),
  546            },
  547            unnecessary_code_fade: Default::default(),
  548        }
  549    }
  550}
  551
  552pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  553    let show_background = language_settings::language_settings(None, None, cx)
  554        .inlay_hints
  555        .show_background;
  556
  557    HighlightStyle {
  558        color: Some(cx.theme().status().hint),
  559        background_color: show_background.then(|| cx.theme().status().hint_background),
  560        ..HighlightStyle::default()
  561    }
  562}
  563
  564pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  565    InlineCompletionStyles {
  566        insertion: HighlightStyle {
  567            color: Some(cx.theme().status().predictive),
  568            ..HighlightStyle::default()
  569        },
  570        whitespace: HighlightStyle {
  571            background_color: Some(cx.theme().status().created_background),
  572            ..HighlightStyle::default()
  573        },
  574    }
  575}
  576
  577type CompletionId = usize;
  578
  579pub(crate) enum EditDisplayMode {
  580    TabAccept,
  581    DiffPopover,
  582    Inline,
  583}
  584
  585enum InlineCompletion {
  586    Edit {
  587        edits: Vec<(Range<Anchor>, String)>,
  588        edit_preview: Option<EditPreview>,
  589        display_mode: EditDisplayMode,
  590        snapshot: BufferSnapshot,
  591    },
  592    Move {
  593        target: Anchor,
  594        snapshot: BufferSnapshot,
  595    },
  596}
  597
  598struct InlineCompletionState {
  599    inlay_ids: Vec<InlayId>,
  600    completion: InlineCompletion,
  601    completion_id: Option<SharedString>,
  602    invalidation_range: Range<Anchor>,
  603}
  604
  605enum EditPredictionSettings {
  606    Disabled,
  607    Enabled {
  608        show_in_menu: bool,
  609        preview_requires_modifier: bool,
  610    },
  611}
  612
  613enum InlineCompletionHighlight {}
  614
  615#[derive(Debug, Clone)]
  616struct InlineDiagnostic {
  617    message: SharedString,
  618    group_id: usize,
  619    is_primary: bool,
  620    start: Point,
  621    severity: DiagnosticSeverity,
  622}
  623
  624pub enum MenuInlineCompletionsPolicy {
  625    Never,
  626    ByProvider,
  627}
  628
  629pub enum EditPredictionPreview {
  630    /// Modifier is not pressed
  631    Inactive { released_too_fast: bool },
  632    /// Modifier pressed
  633    Active {
  634        since: Instant,
  635        previous_scroll_position: Option<ScrollAnchor>,
  636    },
  637}
  638
  639impl EditPredictionPreview {
  640    pub fn released_too_fast(&self) -> bool {
  641        match self {
  642            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  643            EditPredictionPreview::Active { .. } => false,
  644        }
  645    }
  646
  647    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  648        if let EditPredictionPreview::Active {
  649            previous_scroll_position,
  650            ..
  651        } = self
  652        {
  653            *previous_scroll_position = scroll_position;
  654        }
  655    }
  656}
  657
  658pub struct ContextMenuOptions {
  659    pub min_entries_visible: usize,
  660    pub max_entries_visible: usize,
  661    pub placement: Option<ContextMenuPlacement>,
  662}
  663
  664#[derive(Debug, Clone, PartialEq, Eq)]
  665pub enum ContextMenuPlacement {
  666    Above,
  667    Below,
  668}
  669
  670#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  671struct EditorActionId(usize);
  672
  673impl EditorActionId {
  674    pub fn post_inc(&mut self) -> Self {
  675        let answer = self.0;
  676
  677        *self = Self(answer + 1);
  678
  679        Self(answer)
  680    }
  681}
  682
  683// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  684// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  685
  686type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  687type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  688
  689#[derive(Default)]
  690struct ScrollbarMarkerState {
  691    scrollbar_size: Size<Pixels>,
  692    dirty: bool,
  693    markers: Arc<[PaintQuad]>,
  694    pending_refresh: Option<Task<Result<()>>>,
  695}
  696
  697impl ScrollbarMarkerState {
  698    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  699        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  700    }
  701}
  702
  703#[derive(Clone, Debug)]
  704struct RunnableTasks {
  705    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  706    offset: multi_buffer::Anchor,
  707    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  708    column: u32,
  709    // Values of all named captures, including those starting with '_'
  710    extra_variables: HashMap<String, String>,
  711    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  712    context_range: Range<BufferOffset>,
  713}
  714
  715impl RunnableTasks {
  716    fn resolve<'a>(
  717        &'a self,
  718        cx: &'a task::TaskContext,
  719    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  720        self.templates.iter().filter_map(|(kind, template)| {
  721            template
  722                .resolve_task(&kind.to_id_base(), cx)
  723                .map(|task| (kind.clone(), task))
  724        })
  725    }
  726}
  727
  728#[derive(Clone)]
  729struct ResolvedTasks {
  730    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  731    position: Anchor,
  732}
  733
  734#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  735struct BufferOffset(usize);
  736
  737// Addons allow storing per-editor state in other crates (e.g. Vim)
  738pub trait Addon: 'static {
  739    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  740
  741    fn render_buffer_header_controls(
  742        &self,
  743        _: &ExcerptInfo,
  744        _: &Window,
  745        _: &App,
  746    ) -> Option<AnyElement> {
  747        None
  748    }
  749
  750    fn to_any(&self) -> &dyn std::any::Any;
  751
  752    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  753        None
  754    }
  755}
  756
  757/// A set of caret positions, registered when the editor was edited.
  758pub struct ChangeList {
  759    changes: Vec<Vec<Anchor>>,
  760    /// Currently "selected" change.
  761    position: Option<usize>,
  762}
  763
  764impl ChangeList {
  765    pub fn new() -> Self {
  766        Self {
  767            changes: Vec::new(),
  768            position: None,
  769        }
  770    }
  771
  772    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  773    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  774    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  775        if self.changes.is_empty() {
  776            return None;
  777        }
  778
  779        let prev = self.position.unwrap_or(self.changes.len());
  780        let next = if direction == Direction::Prev {
  781            prev.saturating_sub(count)
  782        } else {
  783            (prev + count).min(self.changes.len() - 1)
  784        };
  785        self.position = Some(next);
  786        self.changes.get(next).map(|anchors| anchors.as_slice())
  787    }
  788
  789    /// Adds a new change to the list, resetting the change list position.
  790    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  791        self.position.take();
  792        if pop_state {
  793            self.changes.pop();
  794        }
  795        self.changes.push(new_positions.clone());
  796    }
  797
  798    pub fn last(&self) -> Option<&[Anchor]> {
  799        self.changes.last().map(|anchors| anchors.as_slice())
  800    }
  801}
  802
  803#[derive(Clone)]
  804struct InlineBlamePopoverState {
  805    scroll_handle: ScrollHandle,
  806    commit_message: Option<ParsedCommitMessage>,
  807    markdown: Entity<Markdown>,
  808}
  809
  810struct InlineBlamePopover {
  811    position: gpui::Point<Pixels>,
  812    show_task: Option<Task<()>>,
  813    hide_task: Option<Task<()>>,
  814    popover_bounds: Option<Bounds<Pixels>>,
  815    popover_state: InlineBlamePopoverState,
  816}
  817
  818/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  819///
  820/// See the [module level documentation](self) for more information.
  821pub struct Editor {
  822    focus_handle: FocusHandle,
  823    last_focused_descendant: Option<WeakFocusHandle>,
  824    /// The text buffer being edited
  825    buffer: Entity<MultiBuffer>,
  826    /// Map of how text in the buffer should be displayed.
  827    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  828    pub display_map: Entity<DisplayMap>,
  829    pub selections: SelectionsCollection,
  830    pub scroll_manager: ScrollManager,
  831    /// When inline assist editors are linked, they all render cursors because
  832    /// typing enters text into each of them, even the ones that aren't focused.
  833    pub(crate) show_cursor_when_unfocused: bool,
  834    columnar_selection_tail: Option<Anchor>,
  835    add_selections_state: Option<AddSelectionsState>,
  836    select_next_state: Option<SelectNextState>,
  837    select_prev_state: Option<SelectNextState>,
  838    selection_history: SelectionHistory,
  839    autoclose_regions: Vec<AutocloseRegion>,
  840    snippet_stack: InvalidationStack<SnippetState>,
  841    select_syntax_node_history: SelectSyntaxNodeHistory,
  842    ime_transaction: Option<TransactionId>,
  843    active_diagnostics: ActiveDiagnostic,
  844    show_inline_diagnostics: bool,
  845    inline_diagnostics_update: Task<()>,
  846    inline_diagnostics_enabled: bool,
  847    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  848    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  849    hard_wrap: Option<usize>,
  850
  851    // TODO: make this a access method
  852    pub project: Option<Entity<Project>>,
  853    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  854    completion_provider: Option<Box<dyn CompletionProvider>>,
  855    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  856    blink_manager: Entity<BlinkManager>,
  857    show_cursor_names: bool,
  858    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  859    pub show_local_selections: bool,
  860    mode: EditorMode,
  861    show_breadcrumbs: bool,
  862    show_gutter: bool,
  863    show_scrollbars: bool,
  864    disable_scrolling: bool,
  865    disable_expand_excerpt_buttons: bool,
  866    show_line_numbers: Option<bool>,
  867    use_relative_line_numbers: Option<bool>,
  868    show_git_diff_gutter: Option<bool>,
  869    show_code_actions: Option<bool>,
  870    show_runnables: Option<bool>,
  871    show_breakpoints: Option<bool>,
  872    show_wrap_guides: Option<bool>,
  873    show_indent_guides: Option<bool>,
  874    placeholder_text: Option<Arc<str>>,
  875    highlight_order: usize,
  876    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  877    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  878    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  879    scrollbar_marker_state: ScrollbarMarkerState,
  880    active_indent_guides_state: ActiveIndentGuidesState,
  881    nav_history: Option<ItemNavHistory>,
  882    context_menu: RefCell<Option<CodeContextMenu>>,
  883    context_menu_options: Option<ContextMenuOptions>,
  884    mouse_context_menu: Option<MouseContextMenu>,
  885    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  886    inline_blame_popover: Option<InlineBlamePopover>,
  887    signature_help_state: SignatureHelpState,
  888    auto_signature_help: Option<bool>,
  889    find_all_references_task_sources: Vec<Anchor>,
  890    next_completion_id: CompletionId,
  891    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  892    code_actions_task: Option<Task<Result<()>>>,
  893    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  894    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  895    document_highlights_task: Option<Task<()>>,
  896    linked_editing_range_task: Option<Task<Option<()>>>,
  897    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  898    pending_rename: Option<RenameState>,
  899    searchable: bool,
  900    cursor_shape: CursorShape,
  901    current_line_highlight: Option<CurrentLineHighlight>,
  902    collapse_matches: bool,
  903    autoindent_mode: Option<AutoindentMode>,
  904    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  905    input_enabled: bool,
  906    use_modal_editing: bool,
  907    read_only: bool,
  908    leader_peer_id: Option<PeerId>,
  909    remote_id: Option<ViewId>,
  910    pub hover_state: HoverState,
  911    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  912    gutter_hovered: bool,
  913    hovered_link_state: Option<HoveredLinkState>,
  914    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  915    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  916    active_inline_completion: Option<InlineCompletionState>,
  917    /// Used to prevent flickering as the user types while the menu is open
  918    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  919    edit_prediction_settings: EditPredictionSettings,
  920    inline_completions_hidden_for_vim_mode: bool,
  921    show_inline_completions_override: Option<bool>,
  922    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  923    edit_prediction_preview: EditPredictionPreview,
  924    edit_prediction_indent_conflict: bool,
  925    edit_prediction_requires_modifier_in_indent_conflict: bool,
  926    inlay_hint_cache: InlayHintCache,
  927    next_inlay_id: usize,
  928    _subscriptions: Vec<Subscription>,
  929    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  930    gutter_dimensions: GutterDimensions,
  931    style: Option<EditorStyle>,
  932    text_style_refinement: Option<TextStyleRefinement>,
  933    next_editor_action_id: EditorActionId,
  934    editor_actions:
  935        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  936    use_autoclose: bool,
  937    use_auto_surround: bool,
  938    auto_replace_emoji_shortcode: bool,
  939    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  940    show_git_blame_gutter: bool,
  941    show_git_blame_inline: bool,
  942    show_git_blame_inline_delay_task: Option<Task<()>>,
  943    git_blame_inline_enabled: bool,
  944    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  945    serialize_dirty_buffers: bool,
  946    show_selection_menu: Option<bool>,
  947    blame: Option<Entity<GitBlame>>,
  948    blame_subscription: Option<Subscription>,
  949    custom_context_menu: Option<
  950        Box<
  951            dyn 'static
  952                + Fn(
  953                    &mut Self,
  954                    DisplayPoint,
  955                    &mut Window,
  956                    &mut Context<Self>,
  957                ) -> Option<Entity<ui::ContextMenu>>,
  958        >,
  959    >,
  960    last_bounds: Option<Bounds<Pixels>>,
  961    last_position_map: Option<Rc<PositionMap>>,
  962    expect_bounds_change: Option<Bounds<Pixels>>,
  963    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  964    tasks_update_task: Option<Task<()>>,
  965    breakpoint_store: Option<Entity<BreakpointStore>>,
  966    /// Allow's a user to create a breakpoint by selecting this indicator
  967    /// It should be None while a user is not hovering over the gutter
  968    /// Otherwise it represents the point that the breakpoint will be shown
  969    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  970    in_project_search: bool,
  971    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  972    breadcrumb_header: Option<String>,
  973    focused_block: Option<FocusedBlock>,
  974    next_scroll_position: NextScrollCursorCenterTopBottom,
  975    addons: HashMap<TypeId, Box<dyn Addon>>,
  976    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  977    load_diff_task: Option<Shared<Task<()>>>,
  978    selection_mark_mode: bool,
  979    toggle_fold_multiple_buffers: Task<()>,
  980    _scroll_cursor_center_top_bottom_task: Task<()>,
  981    serialize_selections: Task<()>,
  982    serialize_folds: Task<()>,
  983    mouse_cursor_hidden: bool,
  984    hide_mouse_mode: HideMouseMode,
  985    pub change_list: ChangeList,
  986    inline_value_cache: InlineValueCache,
  987}
  988
  989#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  990enum NextScrollCursorCenterTopBottom {
  991    #[default]
  992    Center,
  993    Top,
  994    Bottom,
  995}
  996
  997impl NextScrollCursorCenterTopBottom {
  998    fn next(&self) -> Self {
  999        match self {
 1000            Self::Center => Self::Top,
 1001            Self::Top => Self::Bottom,
 1002            Self::Bottom => Self::Center,
 1003        }
 1004    }
 1005}
 1006
 1007#[derive(Clone)]
 1008pub struct EditorSnapshot {
 1009    pub mode: EditorMode,
 1010    show_gutter: bool,
 1011    show_line_numbers: Option<bool>,
 1012    show_git_diff_gutter: Option<bool>,
 1013    show_code_actions: Option<bool>,
 1014    show_runnables: Option<bool>,
 1015    show_breakpoints: Option<bool>,
 1016    git_blame_gutter_max_author_length: Option<usize>,
 1017    pub display_snapshot: DisplaySnapshot,
 1018    pub placeholder_text: Option<Arc<str>>,
 1019    is_focused: bool,
 1020    scroll_anchor: ScrollAnchor,
 1021    ongoing_scroll: OngoingScroll,
 1022    current_line_highlight: CurrentLineHighlight,
 1023    gutter_hovered: bool,
 1024}
 1025
 1026#[derive(Default, Debug, Clone, Copy)]
 1027pub struct GutterDimensions {
 1028    pub left_padding: Pixels,
 1029    pub right_padding: Pixels,
 1030    pub width: Pixels,
 1031    pub margin: Pixels,
 1032    pub git_blame_entries_width: Option<Pixels>,
 1033}
 1034
 1035impl GutterDimensions {
 1036    /// The full width of the space taken up by the gutter.
 1037    pub fn full_width(&self) -> Pixels {
 1038        self.margin + self.width
 1039    }
 1040
 1041    /// The width of the space reserved for the fold indicators,
 1042    /// use alongside 'justify_end' and `gutter_width` to
 1043    /// right align content with the line numbers
 1044    pub fn fold_area_width(&self) -> Pixels {
 1045        self.margin + self.right_padding
 1046    }
 1047}
 1048
 1049#[derive(Debug)]
 1050pub struct RemoteSelection {
 1051    pub replica_id: ReplicaId,
 1052    pub selection: Selection<Anchor>,
 1053    pub cursor_shape: CursorShape,
 1054    pub peer_id: PeerId,
 1055    pub line_mode: bool,
 1056    pub participant_index: Option<ParticipantIndex>,
 1057    pub user_name: Option<SharedString>,
 1058}
 1059
 1060#[derive(Clone, Debug)]
 1061struct SelectionHistoryEntry {
 1062    selections: Arc<[Selection<Anchor>]>,
 1063    select_next_state: Option<SelectNextState>,
 1064    select_prev_state: Option<SelectNextState>,
 1065    add_selections_state: Option<AddSelectionsState>,
 1066}
 1067
 1068enum SelectionHistoryMode {
 1069    Normal,
 1070    Undoing,
 1071    Redoing,
 1072}
 1073
 1074#[derive(Clone, PartialEq, Eq, Hash)]
 1075struct HoveredCursor {
 1076    replica_id: u16,
 1077    selection_id: usize,
 1078}
 1079
 1080impl Default for SelectionHistoryMode {
 1081    fn default() -> Self {
 1082        Self::Normal
 1083    }
 1084}
 1085
 1086#[derive(Default)]
 1087struct SelectionHistory {
 1088    #[allow(clippy::type_complexity)]
 1089    selections_by_transaction:
 1090        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1091    mode: SelectionHistoryMode,
 1092    undo_stack: VecDeque<SelectionHistoryEntry>,
 1093    redo_stack: VecDeque<SelectionHistoryEntry>,
 1094}
 1095
 1096impl SelectionHistory {
 1097    fn insert_transaction(
 1098        &mut self,
 1099        transaction_id: TransactionId,
 1100        selections: Arc<[Selection<Anchor>]>,
 1101    ) {
 1102        self.selections_by_transaction
 1103            .insert(transaction_id, (selections, None));
 1104    }
 1105
 1106    #[allow(clippy::type_complexity)]
 1107    fn transaction(
 1108        &self,
 1109        transaction_id: TransactionId,
 1110    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1111        self.selections_by_transaction.get(&transaction_id)
 1112    }
 1113
 1114    #[allow(clippy::type_complexity)]
 1115    fn transaction_mut(
 1116        &mut self,
 1117        transaction_id: TransactionId,
 1118    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1119        self.selections_by_transaction.get_mut(&transaction_id)
 1120    }
 1121
 1122    fn push(&mut self, entry: SelectionHistoryEntry) {
 1123        if !entry.selections.is_empty() {
 1124            match self.mode {
 1125                SelectionHistoryMode::Normal => {
 1126                    self.push_undo(entry);
 1127                    self.redo_stack.clear();
 1128                }
 1129                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1130                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1131            }
 1132        }
 1133    }
 1134
 1135    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1136        if self
 1137            .undo_stack
 1138            .back()
 1139            .map_or(true, |e| e.selections != entry.selections)
 1140        {
 1141            self.undo_stack.push_back(entry);
 1142            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1143                self.undo_stack.pop_front();
 1144            }
 1145        }
 1146    }
 1147
 1148    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1149        if self
 1150            .redo_stack
 1151            .back()
 1152            .map_or(true, |e| e.selections != entry.selections)
 1153        {
 1154            self.redo_stack.push_back(entry);
 1155            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1156                self.redo_stack.pop_front();
 1157            }
 1158        }
 1159    }
 1160}
 1161
 1162#[derive(Clone, Copy)]
 1163pub struct RowHighlightOptions {
 1164    pub autoscroll: bool,
 1165    pub include_gutter: bool,
 1166}
 1167
 1168impl Default for RowHighlightOptions {
 1169    fn default() -> Self {
 1170        Self {
 1171            autoscroll: Default::default(),
 1172            include_gutter: true,
 1173        }
 1174    }
 1175}
 1176
 1177struct RowHighlight {
 1178    index: usize,
 1179    range: Range<Anchor>,
 1180    color: Hsla,
 1181    options: RowHighlightOptions,
 1182    type_id: TypeId,
 1183}
 1184
 1185#[derive(Clone, Debug)]
 1186struct AddSelectionsState {
 1187    above: bool,
 1188    stack: Vec<usize>,
 1189}
 1190
 1191#[derive(Clone)]
 1192struct SelectNextState {
 1193    query: AhoCorasick,
 1194    wordwise: bool,
 1195    done: bool,
 1196}
 1197
 1198impl std::fmt::Debug for SelectNextState {
 1199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1200        f.debug_struct(std::any::type_name::<Self>())
 1201            .field("wordwise", &self.wordwise)
 1202            .field("done", &self.done)
 1203            .finish()
 1204    }
 1205}
 1206
 1207#[derive(Debug)]
 1208struct AutocloseRegion {
 1209    selection_id: usize,
 1210    range: Range<Anchor>,
 1211    pair: BracketPair,
 1212}
 1213
 1214#[derive(Debug)]
 1215struct SnippetState {
 1216    ranges: Vec<Vec<Range<Anchor>>>,
 1217    active_index: usize,
 1218    choices: Vec<Option<Vec<String>>>,
 1219}
 1220
 1221#[doc(hidden)]
 1222pub struct RenameState {
 1223    pub range: Range<Anchor>,
 1224    pub old_name: Arc<str>,
 1225    pub editor: Entity<Editor>,
 1226    block_id: CustomBlockId,
 1227}
 1228
 1229struct InvalidationStack<T>(Vec<T>);
 1230
 1231struct RegisteredInlineCompletionProvider {
 1232    provider: Arc<dyn InlineCompletionProviderHandle>,
 1233    _subscription: Subscription,
 1234}
 1235
 1236#[derive(Debug, PartialEq, Eq)]
 1237pub struct ActiveDiagnosticGroup {
 1238    pub active_range: Range<Anchor>,
 1239    pub active_message: String,
 1240    pub group_id: usize,
 1241    pub blocks: HashSet<CustomBlockId>,
 1242}
 1243
 1244#[derive(Debug, PartialEq, Eq)]
 1245#[allow(clippy::large_enum_variant)]
 1246pub(crate) enum ActiveDiagnostic {
 1247    None,
 1248    All,
 1249    Group(ActiveDiagnosticGroup),
 1250}
 1251
 1252#[derive(Serialize, Deserialize, Clone, Debug)]
 1253pub struct ClipboardSelection {
 1254    /// The number of bytes in this selection.
 1255    pub len: usize,
 1256    /// Whether this was a full-line selection.
 1257    pub is_entire_line: bool,
 1258    /// The indentation of the first line when this content was originally copied.
 1259    pub first_line_indent: u32,
 1260}
 1261
 1262// selections, scroll behavior, was newest selection reversed
 1263type SelectSyntaxNodeHistoryState = (
 1264    Box<[Selection<usize>]>,
 1265    SelectSyntaxNodeScrollBehavior,
 1266    bool,
 1267);
 1268
 1269#[derive(Default)]
 1270struct SelectSyntaxNodeHistory {
 1271    stack: Vec<SelectSyntaxNodeHistoryState>,
 1272    // disable temporarily to allow changing selections without losing the stack
 1273    pub disable_clearing: bool,
 1274}
 1275
 1276impl SelectSyntaxNodeHistory {
 1277    pub fn try_clear(&mut self) {
 1278        if !self.disable_clearing {
 1279            self.stack.clear();
 1280        }
 1281    }
 1282
 1283    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1284        self.stack.push(selection);
 1285    }
 1286
 1287    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1288        self.stack.pop()
 1289    }
 1290}
 1291
 1292enum SelectSyntaxNodeScrollBehavior {
 1293    CursorTop,
 1294    FitSelection,
 1295    CursorBottom,
 1296}
 1297
 1298#[derive(Debug)]
 1299pub(crate) struct NavigationData {
 1300    cursor_anchor: Anchor,
 1301    cursor_position: Point,
 1302    scroll_anchor: ScrollAnchor,
 1303    scroll_top_row: u32,
 1304}
 1305
 1306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1307pub enum GotoDefinitionKind {
 1308    Symbol,
 1309    Declaration,
 1310    Type,
 1311    Implementation,
 1312}
 1313
 1314#[derive(Debug, Clone)]
 1315enum InlayHintRefreshReason {
 1316    ModifiersChanged(bool),
 1317    Toggle(bool),
 1318    SettingsChange(InlayHintSettings),
 1319    NewLinesShown,
 1320    BufferEdited(HashSet<Arc<Language>>),
 1321    RefreshRequested,
 1322    ExcerptsRemoved(Vec<ExcerptId>),
 1323}
 1324
 1325impl InlayHintRefreshReason {
 1326    fn description(&self) -> &'static str {
 1327        match self {
 1328            Self::ModifiersChanged(_) => "modifiers changed",
 1329            Self::Toggle(_) => "toggle",
 1330            Self::SettingsChange(_) => "settings change",
 1331            Self::NewLinesShown => "new lines shown",
 1332            Self::BufferEdited(_) => "buffer edited",
 1333            Self::RefreshRequested => "refresh requested",
 1334            Self::ExcerptsRemoved(_) => "excerpts removed",
 1335        }
 1336    }
 1337}
 1338
 1339pub enum FormatTarget {
 1340    Buffers,
 1341    Ranges(Vec<Range<MultiBufferPoint>>),
 1342}
 1343
 1344pub(crate) struct FocusedBlock {
 1345    id: BlockId,
 1346    focus_handle: WeakFocusHandle,
 1347}
 1348
 1349#[derive(Clone)]
 1350enum JumpData {
 1351    MultiBufferRow {
 1352        row: MultiBufferRow,
 1353        line_offset_from_top: u32,
 1354    },
 1355    MultiBufferPoint {
 1356        excerpt_id: ExcerptId,
 1357        position: Point,
 1358        anchor: text::Anchor,
 1359        line_offset_from_top: u32,
 1360    },
 1361}
 1362
 1363pub enum MultibufferSelectionMode {
 1364    First,
 1365    All,
 1366}
 1367
 1368#[derive(Clone, Copy, Debug, Default)]
 1369pub struct RewrapOptions {
 1370    pub override_language_settings: bool,
 1371    pub preserve_existing_whitespace: bool,
 1372}
 1373
 1374impl Editor {
 1375    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1376        let buffer = cx.new(|cx| Buffer::local("", cx));
 1377        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1378        Self::new(
 1379            EditorMode::SingleLine { auto_width: false },
 1380            buffer,
 1381            None,
 1382            window,
 1383            cx,
 1384        )
 1385    }
 1386
 1387    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1388        let buffer = cx.new(|cx| Buffer::local("", cx));
 1389        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1390        Self::new(EditorMode::full(), buffer, None, window, cx)
 1391    }
 1392
 1393    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1394        let buffer = cx.new(|cx| Buffer::local("", cx));
 1395        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1396        Self::new(
 1397            EditorMode::SingleLine { auto_width: true },
 1398            buffer,
 1399            None,
 1400            window,
 1401            cx,
 1402        )
 1403    }
 1404
 1405    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1406        let buffer = cx.new(|cx| Buffer::local("", cx));
 1407        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1408        Self::new(
 1409            EditorMode::AutoHeight { max_lines },
 1410            buffer,
 1411            None,
 1412            window,
 1413            cx,
 1414        )
 1415    }
 1416
 1417    pub fn for_buffer(
 1418        buffer: Entity<Buffer>,
 1419        project: Option<Entity<Project>>,
 1420        window: &mut Window,
 1421        cx: &mut Context<Self>,
 1422    ) -> Self {
 1423        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1424        Self::new(EditorMode::full(), buffer, project, window, cx)
 1425    }
 1426
 1427    pub fn for_multibuffer(
 1428        buffer: Entity<MultiBuffer>,
 1429        project: Option<Entity<Project>>,
 1430        window: &mut Window,
 1431        cx: &mut Context<Self>,
 1432    ) -> Self {
 1433        Self::new(EditorMode::full(), buffer, project, window, cx)
 1434    }
 1435
 1436    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1437        let mut clone = Self::new(
 1438            self.mode,
 1439            self.buffer.clone(),
 1440            self.project.clone(),
 1441            window,
 1442            cx,
 1443        );
 1444        self.display_map.update(cx, |display_map, cx| {
 1445            let snapshot = display_map.snapshot(cx);
 1446            clone.display_map.update(cx, |display_map, cx| {
 1447                display_map.set_state(&snapshot, cx);
 1448            });
 1449        });
 1450        clone.folds_did_change(cx);
 1451        clone.selections.clone_state(&self.selections);
 1452        clone.scroll_manager.clone_state(&self.scroll_manager);
 1453        clone.searchable = self.searchable;
 1454        clone.read_only = self.read_only;
 1455        clone
 1456    }
 1457
 1458    pub fn new(
 1459        mode: EditorMode,
 1460        buffer: Entity<MultiBuffer>,
 1461        project: Option<Entity<Project>>,
 1462        window: &mut Window,
 1463        cx: &mut Context<Self>,
 1464    ) -> Self {
 1465        let style = window.text_style();
 1466        let font_size = style.font_size.to_pixels(window.rem_size());
 1467        let editor = cx.entity().downgrade();
 1468        let fold_placeholder = FoldPlaceholder {
 1469            constrain_width: true,
 1470            render: Arc::new(move |fold_id, fold_range, cx| {
 1471                let editor = editor.clone();
 1472                div()
 1473                    .id(fold_id)
 1474                    .bg(cx.theme().colors().ghost_element_background)
 1475                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1476                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1477                    .rounded_xs()
 1478                    .size_full()
 1479                    .cursor_pointer()
 1480                    .child("")
 1481                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1482                    .on_click(move |_, _window, cx| {
 1483                        editor
 1484                            .update(cx, |editor, cx| {
 1485                                editor.unfold_ranges(
 1486                                    &[fold_range.start..fold_range.end],
 1487                                    true,
 1488                                    false,
 1489                                    cx,
 1490                                );
 1491                                cx.stop_propagation();
 1492                            })
 1493                            .ok();
 1494                    })
 1495                    .into_any()
 1496            }),
 1497            merge_adjacent: true,
 1498            ..Default::default()
 1499        };
 1500        let display_map = cx.new(|cx| {
 1501            DisplayMap::new(
 1502                buffer.clone(),
 1503                style.font(),
 1504                font_size,
 1505                None,
 1506                FILE_HEADER_HEIGHT,
 1507                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1508                fold_placeholder,
 1509                cx,
 1510            )
 1511        });
 1512
 1513        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1514
 1515        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1516
 1517        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1518            .then(|| language_settings::SoftWrap::None);
 1519
 1520        let mut project_subscriptions = Vec::new();
 1521        if mode.is_full() {
 1522            if let Some(project) = project.as_ref() {
 1523                project_subscriptions.push(cx.subscribe_in(
 1524                    project,
 1525                    window,
 1526                    |editor, _, event, window, cx| match event {
 1527                        project::Event::RefreshCodeLens => {
 1528                            // we always query lens with actions, without storing them, always refreshing them
 1529                        }
 1530                        project::Event::RefreshInlayHints => {
 1531                            editor
 1532                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1533                        }
 1534                        project::Event::SnippetEdit(id, snippet_edits) => {
 1535                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1536                                let focus_handle = editor.focus_handle(cx);
 1537                                if focus_handle.is_focused(window) {
 1538                                    let snapshot = buffer.read(cx).snapshot();
 1539                                    for (range, snippet) in snippet_edits {
 1540                                        let editor_range =
 1541                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1542                                        editor
 1543                                            .insert_snippet(
 1544                                                &[editor_range],
 1545                                                snippet.clone(),
 1546                                                window,
 1547                                                cx,
 1548                                            )
 1549                                            .ok();
 1550                                    }
 1551                                }
 1552                            }
 1553                        }
 1554                        _ => {}
 1555                    },
 1556                ));
 1557                if let Some(task_inventory) = project
 1558                    .read(cx)
 1559                    .task_store()
 1560                    .read(cx)
 1561                    .task_inventory()
 1562                    .cloned()
 1563                {
 1564                    project_subscriptions.push(cx.observe_in(
 1565                        &task_inventory,
 1566                        window,
 1567                        |editor, _, window, cx| {
 1568                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1569                        },
 1570                    ));
 1571                };
 1572
 1573                project_subscriptions.push(cx.subscribe_in(
 1574                    &project.read(cx).breakpoint_store(),
 1575                    window,
 1576                    |editor, _, event, window, cx| match event {
 1577                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1578                            if editor.go_to_active_debug_line(window, cx) {
 1579                                cx.stop_propagation();
 1580                            }
 1581
 1582                            editor.refresh_inline_values(cx);
 1583                        }
 1584                        _ => {}
 1585                    },
 1586                ));
 1587            }
 1588        }
 1589
 1590        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1591
 1592        let inlay_hint_settings =
 1593            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1594        let focus_handle = cx.focus_handle();
 1595        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1596            .detach();
 1597        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1598            .detach();
 1599        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1600            .detach();
 1601        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1602            .detach();
 1603
 1604        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1605            Some(false)
 1606        } else {
 1607            None
 1608        };
 1609
 1610        let breakpoint_store = match (mode, project.as_ref()) {
 1611            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1612            _ => None,
 1613        };
 1614
 1615        let mut code_action_providers = Vec::new();
 1616        let mut load_uncommitted_diff = None;
 1617        if let Some(project) = project.clone() {
 1618            load_uncommitted_diff = Some(
 1619                get_uncommitted_diff_for_buffer(
 1620                    &project,
 1621                    buffer.read(cx).all_buffers(),
 1622                    buffer.clone(),
 1623                    cx,
 1624                )
 1625                .shared(),
 1626            );
 1627            code_action_providers.push(Rc::new(project) as Rc<_>);
 1628        }
 1629
 1630        let mut this = Self {
 1631            focus_handle,
 1632            show_cursor_when_unfocused: false,
 1633            last_focused_descendant: None,
 1634            buffer: buffer.clone(),
 1635            display_map: display_map.clone(),
 1636            selections,
 1637            scroll_manager: ScrollManager::new(cx),
 1638            columnar_selection_tail: None,
 1639            add_selections_state: None,
 1640            select_next_state: None,
 1641            select_prev_state: None,
 1642            selection_history: Default::default(),
 1643            autoclose_regions: Default::default(),
 1644            snippet_stack: Default::default(),
 1645            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1646            ime_transaction: Default::default(),
 1647            active_diagnostics: ActiveDiagnostic::None,
 1648            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1649            inline_diagnostics_update: Task::ready(()),
 1650            inline_diagnostics: Vec::new(),
 1651            soft_wrap_mode_override,
 1652            hard_wrap: None,
 1653            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1654            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1655            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1656            project,
 1657            blink_manager: blink_manager.clone(),
 1658            show_local_selections: true,
 1659            show_scrollbars: true,
 1660            disable_scrolling: false,
 1661            mode,
 1662            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1663            show_gutter: mode.is_full(),
 1664            show_line_numbers: None,
 1665            use_relative_line_numbers: None,
 1666            disable_expand_excerpt_buttons: false,
 1667            show_git_diff_gutter: None,
 1668            show_code_actions: None,
 1669            show_runnables: None,
 1670            show_breakpoints: None,
 1671            show_wrap_guides: None,
 1672            show_indent_guides,
 1673            placeholder_text: None,
 1674            highlight_order: 0,
 1675            highlighted_rows: HashMap::default(),
 1676            background_highlights: Default::default(),
 1677            gutter_highlights: TreeMap::default(),
 1678            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1679            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1680            nav_history: None,
 1681            context_menu: RefCell::new(None),
 1682            context_menu_options: None,
 1683            mouse_context_menu: None,
 1684            completion_tasks: Default::default(),
 1685            inline_blame_popover: Default::default(),
 1686            signature_help_state: SignatureHelpState::default(),
 1687            auto_signature_help: None,
 1688            find_all_references_task_sources: Vec::new(),
 1689            next_completion_id: 0,
 1690            next_inlay_id: 0,
 1691            code_action_providers,
 1692            available_code_actions: Default::default(),
 1693            code_actions_task: Default::default(),
 1694            quick_selection_highlight_task: Default::default(),
 1695            debounced_selection_highlight_task: Default::default(),
 1696            document_highlights_task: Default::default(),
 1697            linked_editing_range_task: Default::default(),
 1698            pending_rename: Default::default(),
 1699            searchable: true,
 1700            cursor_shape: EditorSettings::get_global(cx)
 1701                .cursor_shape
 1702                .unwrap_or_default(),
 1703            current_line_highlight: None,
 1704            autoindent_mode: Some(AutoindentMode::EachLine),
 1705            collapse_matches: false,
 1706            workspace: None,
 1707            input_enabled: true,
 1708            use_modal_editing: mode.is_full(),
 1709            read_only: false,
 1710            use_autoclose: true,
 1711            use_auto_surround: true,
 1712            auto_replace_emoji_shortcode: false,
 1713            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1714            leader_peer_id: None,
 1715            remote_id: None,
 1716            hover_state: Default::default(),
 1717            pending_mouse_down: None,
 1718            hovered_link_state: Default::default(),
 1719            edit_prediction_provider: None,
 1720            active_inline_completion: None,
 1721            stale_inline_completion_in_menu: None,
 1722            edit_prediction_preview: EditPredictionPreview::Inactive {
 1723                released_too_fast: false,
 1724            },
 1725            inline_diagnostics_enabled: mode.is_full(),
 1726            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1727            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1728
 1729            gutter_hovered: false,
 1730            pixel_position_of_newest_cursor: None,
 1731            last_bounds: None,
 1732            last_position_map: None,
 1733            expect_bounds_change: None,
 1734            gutter_dimensions: GutterDimensions::default(),
 1735            style: None,
 1736            show_cursor_names: false,
 1737            hovered_cursors: Default::default(),
 1738            next_editor_action_id: EditorActionId::default(),
 1739            editor_actions: Rc::default(),
 1740            inline_completions_hidden_for_vim_mode: false,
 1741            show_inline_completions_override: None,
 1742            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1743            edit_prediction_settings: EditPredictionSettings::Disabled,
 1744            edit_prediction_indent_conflict: false,
 1745            edit_prediction_requires_modifier_in_indent_conflict: true,
 1746            custom_context_menu: None,
 1747            show_git_blame_gutter: false,
 1748            show_git_blame_inline: false,
 1749            show_selection_menu: None,
 1750            show_git_blame_inline_delay_task: None,
 1751            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1752            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1753            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1754                .session
 1755                .restore_unsaved_buffers,
 1756            blame: None,
 1757            blame_subscription: None,
 1758            tasks: Default::default(),
 1759
 1760            breakpoint_store,
 1761            gutter_breakpoint_indicator: (None, None),
 1762            _subscriptions: vec![
 1763                cx.observe(&buffer, Self::on_buffer_changed),
 1764                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1765                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1766                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1767                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1768                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1769                cx.observe_window_activation(window, |editor, window, cx| {
 1770                    let active = window.is_window_active();
 1771                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1772                        if active {
 1773                            blink_manager.enable(cx);
 1774                        } else {
 1775                            blink_manager.disable(cx);
 1776                        }
 1777                    });
 1778                }),
 1779            ],
 1780            tasks_update_task: None,
 1781            linked_edit_ranges: Default::default(),
 1782            in_project_search: false,
 1783            previous_search_ranges: None,
 1784            breadcrumb_header: None,
 1785            focused_block: None,
 1786            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1787            addons: HashMap::default(),
 1788            registered_buffers: HashMap::default(),
 1789            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1790            selection_mark_mode: false,
 1791            toggle_fold_multiple_buffers: Task::ready(()),
 1792            serialize_selections: Task::ready(()),
 1793            serialize_folds: Task::ready(()),
 1794            text_style_refinement: None,
 1795            load_diff_task: load_uncommitted_diff,
 1796            mouse_cursor_hidden: false,
 1797            hide_mouse_mode: EditorSettings::get_global(cx)
 1798                .hide_mouse
 1799                .unwrap_or_default(),
 1800            change_list: ChangeList::new(),
 1801        };
 1802        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1803            this._subscriptions
 1804                .push(cx.observe(breakpoints, |_, _, cx| {
 1805                    cx.notify();
 1806                }));
 1807        }
 1808        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1809        this._subscriptions.extend(project_subscriptions);
 1810
 1811        this._subscriptions.push(cx.subscribe_in(
 1812            &cx.entity(),
 1813            window,
 1814            |editor, _, e: &EditorEvent, window, cx| match e {
 1815                EditorEvent::ScrollPositionChanged { local, .. } => {
 1816                    if *local {
 1817                        let new_anchor = editor.scroll_manager.anchor();
 1818                        let snapshot = editor.snapshot(window, cx);
 1819                        editor.update_restoration_data(cx, move |data| {
 1820                            data.scroll_position = (
 1821                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1822                                new_anchor.offset,
 1823                            );
 1824                        });
 1825                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1826                        editor.inline_blame_popover.take();
 1827                    }
 1828                }
 1829                EditorEvent::Edited { .. } => {
 1830                    if !vim_enabled(cx) {
 1831                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1832                        let pop_state = editor
 1833                            .change_list
 1834                            .last()
 1835                            .map(|previous| {
 1836                                previous.len() == selections.len()
 1837                                    && previous.iter().enumerate().all(|(ix, p)| {
 1838                                        p.to_display_point(&map).row()
 1839                                            == selections[ix].head().row()
 1840                                    })
 1841                            })
 1842                            .unwrap_or(false);
 1843                        let new_positions = selections
 1844                            .into_iter()
 1845                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1846                            .collect();
 1847                        editor
 1848                            .change_list
 1849                            .push_to_change_list(pop_state, new_positions);
 1850                    }
 1851                }
 1852                _ => (),
 1853            },
 1854        ));
 1855
 1856        if let Some(dap_store) = this
 1857            .project
 1858            .as_ref()
 1859            .map(|project| project.read(cx).dap_store())
 1860        {
 1861            let weak_editor = cx.weak_entity();
 1862
 1863            this._subscriptions
 1864                .push(
 1865                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1866                        let session_entity = cx.entity();
 1867                        weak_editor
 1868                            .update(cx, |editor, cx| {
 1869                                editor._subscriptions.push(
 1870                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1871                                );
 1872                            })
 1873                            .ok();
 1874                    }),
 1875                );
 1876
 1877            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1878                this._subscriptions
 1879                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1880            }
 1881        }
 1882
 1883        this.end_selection(window, cx);
 1884        this.scroll_manager.show_scrollbars(window, cx);
 1885        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1886
 1887        if mode.is_full() {
 1888            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1889            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1890
 1891            if this.git_blame_inline_enabled {
 1892                this.git_blame_inline_enabled = true;
 1893                this.start_git_blame_inline(false, window, cx);
 1894            }
 1895
 1896            this.go_to_active_debug_line(window, cx);
 1897
 1898            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1899                if let Some(project) = this.project.as_ref() {
 1900                    let handle = project.update(cx, |project, cx| {
 1901                        project.register_buffer_with_language_servers(&buffer, cx)
 1902                    });
 1903                    this.registered_buffers
 1904                        .insert(buffer.read(cx).remote_id(), handle);
 1905                }
 1906            }
 1907        }
 1908
 1909        this.report_editor_event("Editor Opened", None, cx);
 1910        this
 1911    }
 1912
 1913    pub fn deploy_mouse_context_menu(
 1914        &mut self,
 1915        position: gpui::Point<Pixels>,
 1916        context_menu: Entity<ContextMenu>,
 1917        window: &mut Window,
 1918        cx: &mut Context<Self>,
 1919    ) {
 1920        self.mouse_context_menu = Some(MouseContextMenu::new(
 1921            self,
 1922            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1923            context_menu,
 1924            window,
 1925            cx,
 1926        ));
 1927    }
 1928
 1929    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1930        self.mouse_context_menu
 1931            .as_ref()
 1932            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1933    }
 1934
 1935    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1936        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1937    }
 1938
 1939    fn key_context_internal(
 1940        &self,
 1941        has_active_edit_prediction: bool,
 1942        window: &Window,
 1943        cx: &App,
 1944    ) -> KeyContext {
 1945        let mut key_context = KeyContext::new_with_defaults();
 1946        key_context.add("Editor");
 1947        let mode = match self.mode {
 1948            EditorMode::SingleLine { .. } => "single_line",
 1949            EditorMode::AutoHeight { .. } => "auto_height",
 1950            EditorMode::Full { .. } => "full",
 1951        };
 1952
 1953        if EditorSettings::jupyter_enabled(cx) {
 1954            key_context.add("jupyter");
 1955        }
 1956
 1957        key_context.set("mode", mode);
 1958        if self.pending_rename.is_some() {
 1959            key_context.add("renaming");
 1960        }
 1961
 1962        match self.context_menu.borrow().as_ref() {
 1963            Some(CodeContextMenu::Completions(_)) => {
 1964                key_context.add("menu");
 1965                key_context.add("showing_completions");
 1966            }
 1967            Some(CodeContextMenu::CodeActions(_)) => {
 1968                key_context.add("menu");
 1969                key_context.add("showing_code_actions")
 1970            }
 1971            None => {}
 1972        }
 1973
 1974        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1975        if !self.focus_handle(cx).contains_focused(window, cx)
 1976            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1977        {
 1978            for addon in self.addons.values() {
 1979                addon.extend_key_context(&mut key_context, cx)
 1980            }
 1981        }
 1982
 1983        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1984            if let Some(extension) = singleton_buffer
 1985                .read(cx)
 1986                .file()
 1987                .and_then(|file| file.path().extension()?.to_str())
 1988            {
 1989                key_context.set("extension", extension.to_string());
 1990            }
 1991        } else {
 1992            key_context.add("multibuffer");
 1993        }
 1994
 1995        if has_active_edit_prediction {
 1996            if self.edit_prediction_in_conflict() {
 1997                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1998            } else {
 1999                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2000                key_context.add("copilot_suggestion");
 2001            }
 2002        }
 2003
 2004        if self.selection_mark_mode {
 2005            key_context.add("selection_mode");
 2006        }
 2007
 2008        key_context
 2009    }
 2010
 2011    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2012        self.mouse_cursor_hidden = match origin {
 2013            HideMouseCursorOrigin::TypingAction => {
 2014                matches!(
 2015                    self.hide_mouse_mode,
 2016                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2017                )
 2018            }
 2019            HideMouseCursorOrigin::MovementAction => {
 2020                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2021            }
 2022        };
 2023    }
 2024
 2025    pub fn edit_prediction_in_conflict(&self) -> bool {
 2026        if !self.show_edit_predictions_in_menu() {
 2027            return false;
 2028        }
 2029
 2030        let showing_completions = self
 2031            .context_menu
 2032            .borrow()
 2033            .as_ref()
 2034            .map_or(false, |context| {
 2035                matches!(context, CodeContextMenu::Completions(_))
 2036            });
 2037
 2038        showing_completions
 2039            || self.edit_prediction_requires_modifier()
 2040            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2041            // bindings to insert tab characters.
 2042            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2043    }
 2044
 2045    pub fn accept_edit_prediction_keybind(
 2046        &self,
 2047        window: &Window,
 2048        cx: &App,
 2049    ) -> AcceptEditPredictionBinding {
 2050        let key_context = self.key_context_internal(true, window, cx);
 2051        let in_conflict = self.edit_prediction_in_conflict();
 2052
 2053        AcceptEditPredictionBinding(
 2054            window
 2055                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2056                .into_iter()
 2057                .filter(|binding| {
 2058                    !in_conflict
 2059                        || binding
 2060                            .keystrokes()
 2061                            .first()
 2062                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2063                })
 2064                .rev()
 2065                .min_by_key(|binding| {
 2066                    binding
 2067                        .keystrokes()
 2068                        .first()
 2069                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2070                }),
 2071        )
 2072    }
 2073
 2074    pub fn new_file(
 2075        workspace: &mut Workspace,
 2076        _: &workspace::NewFile,
 2077        window: &mut Window,
 2078        cx: &mut Context<Workspace>,
 2079    ) {
 2080        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2081            "Failed to create buffer",
 2082            window,
 2083            cx,
 2084            |e, _, _| match e.error_code() {
 2085                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2086                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2087                e.error_tag("required").unwrap_or("the latest version")
 2088            )),
 2089                _ => None,
 2090            },
 2091        );
 2092    }
 2093
 2094    pub fn new_in_workspace(
 2095        workspace: &mut Workspace,
 2096        window: &mut Window,
 2097        cx: &mut Context<Workspace>,
 2098    ) -> Task<Result<Entity<Editor>>> {
 2099        let project = workspace.project().clone();
 2100        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2101
 2102        cx.spawn_in(window, async move |workspace, cx| {
 2103            let buffer = create.await?;
 2104            workspace.update_in(cx, |workspace, window, cx| {
 2105                let editor =
 2106                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2107                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2108                editor
 2109            })
 2110        })
 2111    }
 2112
 2113    fn new_file_vertical(
 2114        workspace: &mut Workspace,
 2115        _: &workspace::NewFileSplitVertical,
 2116        window: &mut Window,
 2117        cx: &mut Context<Workspace>,
 2118    ) {
 2119        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2120    }
 2121
 2122    fn new_file_horizontal(
 2123        workspace: &mut Workspace,
 2124        _: &workspace::NewFileSplitHorizontal,
 2125        window: &mut Window,
 2126        cx: &mut Context<Workspace>,
 2127    ) {
 2128        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2129    }
 2130
 2131    fn new_file_in_direction(
 2132        workspace: &mut Workspace,
 2133        direction: SplitDirection,
 2134        window: &mut Window,
 2135        cx: &mut Context<Workspace>,
 2136    ) {
 2137        let project = workspace.project().clone();
 2138        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2139
 2140        cx.spawn_in(window, async move |workspace, cx| {
 2141            let buffer = create.await?;
 2142            workspace.update_in(cx, move |workspace, window, cx| {
 2143                workspace.split_item(
 2144                    direction,
 2145                    Box::new(
 2146                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2147                    ),
 2148                    window,
 2149                    cx,
 2150                )
 2151            })?;
 2152            anyhow::Ok(())
 2153        })
 2154        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2155            match e.error_code() {
 2156                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2157                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2158                e.error_tag("required").unwrap_or("the latest version")
 2159            )),
 2160                _ => None,
 2161            }
 2162        });
 2163    }
 2164
 2165    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2166        self.leader_peer_id
 2167    }
 2168
 2169    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2170        &self.buffer
 2171    }
 2172
 2173    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2174        self.workspace.as_ref()?.0.upgrade()
 2175    }
 2176
 2177    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2178        self.buffer().read(cx).title(cx)
 2179    }
 2180
 2181    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2182        let git_blame_gutter_max_author_length = self
 2183            .render_git_blame_gutter(cx)
 2184            .then(|| {
 2185                if let Some(blame) = self.blame.as_ref() {
 2186                    let max_author_length =
 2187                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2188                    Some(max_author_length)
 2189                } else {
 2190                    None
 2191                }
 2192            })
 2193            .flatten();
 2194
 2195        EditorSnapshot {
 2196            mode: self.mode,
 2197            show_gutter: self.show_gutter,
 2198            show_line_numbers: self.show_line_numbers,
 2199            show_git_diff_gutter: self.show_git_diff_gutter,
 2200            show_code_actions: self.show_code_actions,
 2201            show_runnables: self.show_runnables,
 2202            show_breakpoints: self.show_breakpoints,
 2203            git_blame_gutter_max_author_length,
 2204            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2205            scroll_anchor: self.scroll_manager.anchor(),
 2206            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2207            placeholder_text: self.placeholder_text.clone(),
 2208            is_focused: self.focus_handle.is_focused(window),
 2209            current_line_highlight: self
 2210                .current_line_highlight
 2211                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2212            gutter_hovered: self.gutter_hovered,
 2213        }
 2214    }
 2215
 2216    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2217        self.buffer.read(cx).language_at(point, cx)
 2218    }
 2219
 2220    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2221        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2222    }
 2223
 2224    pub fn active_excerpt(
 2225        &self,
 2226        cx: &App,
 2227    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2228        self.buffer
 2229            .read(cx)
 2230            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2231    }
 2232
 2233    pub fn mode(&self) -> EditorMode {
 2234        self.mode
 2235    }
 2236
 2237    pub fn set_mode(&mut self, mode: EditorMode) {
 2238        self.mode = mode;
 2239    }
 2240
 2241    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2242        self.collaboration_hub.as_deref()
 2243    }
 2244
 2245    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2246        self.collaboration_hub = Some(hub);
 2247    }
 2248
 2249    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2250        self.in_project_search = in_project_search;
 2251    }
 2252
 2253    pub fn set_custom_context_menu(
 2254        &mut self,
 2255        f: impl 'static
 2256        + Fn(
 2257            &mut Self,
 2258            DisplayPoint,
 2259            &mut Window,
 2260            &mut Context<Self>,
 2261        ) -> Option<Entity<ui::ContextMenu>>,
 2262    ) {
 2263        self.custom_context_menu = Some(Box::new(f))
 2264    }
 2265
 2266    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2267        self.completion_provider = provider;
 2268    }
 2269
 2270    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2271        self.semantics_provider.clone()
 2272    }
 2273
 2274    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2275        self.semantics_provider = provider;
 2276    }
 2277
 2278    pub fn set_edit_prediction_provider<T>(
 2279        &mut self,
 2280        provider: Option<Entity<T>>,
 2281        window: &mut Window,
 2282        cx: &mut Context<Self>,
 2283    ) where
 2284        T: EditPredictionProvider,
 2285    {
 2286        self.edit_prediction_provider =
 2287            provider.map(|provider| RegisteredInlineCompletionProvider {
 2288                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2289                    if this.focus_handle.is_focused(window) {
 2290                        this.update_visible_inline_completion(window, cx);
 2291                    }
 2292                }),
 2293                provider: Arc::new(provider),
 2294            });
 2295        self.update_edit_prediction_settings(cx);
 2296        self.refresh_inline_completion(false, false, window, cx);
 2297    }
 2298
 2299    pub fn placeholder_text(&self) -> Option<&str> {
 2300        self.placeholder_text.as_deref()
 2301    }
 2302
 2303    pub fn set_placeholder_text(
 2304        &mut self,
 2305        placeholder_text: impl Into<Arc<str>>,
 2306        cx: &mut Context<Self>,
 2307    ) {
 2308        let placeholder_text = Some(placeholder_text.into());
 2309        if self.placeholder_text != placeholder_text {
 2310            self.placeholder_text = placeholder_text;
 2311            cx.notify();
 2312        }
 2313    }
 2314
 2315    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2316        self.cursor_shape = cursor_shape;
 2317
 2318        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2319        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2320
 2321        cx.notify();
 2322    }
 2323
 2324    pub fn set_current_line_highlight(
 2325        &mut self,
 2326        current_line_highlight: Option<CurrentLineHighlight>,
 2327    ) {
 2328        self.current_line_highlight = current_line_highlight;
 2329    }
 2330
 2331    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2332        self.collapse_matches = collapse_matches;
 2333    }
 2334
 2335    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2336        let buffers = self.buffer.read(cx).all_buffers();
 2337        let Some(project) = self.project.as_ref() else {
 2338            return;
 2339        };
 2340        project.update(cx, |project, cx| {
 2341            for buffer in buffers {
 2342                self.registered_buffers
 2343                    .entry(buffer.read(cx).remote_id())
 2344                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2345            }
 2346        })
 2347    }
 2348
 2349    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2350        if self.collapse_matches {
 2351            return range.start..range.start;
 2352        }
 2353        range.clone()
 2354    }
 2355
 2356    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2357        if self.display_map.read(cx).clip_at_line_ends != clip {
 2358            self.display_map
 2359                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2360        }
 2361    }
 2362
 2363    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2364        self.input_enabled = input_enabled;
 2365    }
 2366
 2367    pub fn set_inline_completions_hidden_for_vim_mode(
 2368        &mut self,
 2369        hidden: bool,
 2370        window: &mut Window,
 2371        cx: &mut Context<Self>,
 2372    ) {
 2373        if hidden != self.inline_completions_hidden_for_vim_mode {
 2374            self.inline_completions_hidden_for_vim_mode = hidden;
 2375            if hidden {
 2376                self.update_visible_inline_completion(window, cx);
 2377            } else {
 2378                self.refresh_inline_completion(true, false, window, cx);
 2379            }
 2380        }
 2381    }
 2382
 2383    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2384        self.menu_inline_completions_policy = value;
 2385    }
 2386
 2387    pub fn set_autoindent(&mut self, autoindent: bool) {
 2388        if autoindent {
 2389            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2390        } else {
 2391            self.autoindent_mode = None;
 2392        }
 2393    }
 2394
 2395    pub fn read_only(&self, cx: &App) -> bool {
 2396        self.read_only || self.buffer.read(cx).read_only()
 2397    }
 2398
 2399    pub fn set_read_only(&mut self, read_only: bool) {
 2400        self.read_only = read_only;
 2401    }
 2402
 2403    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2404        self.use_autoclose = autoclose;
 2405    }
 2406
 2407    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2408        self.use_auto_surround = auto_surround;
 2409    }
 2410
 2411    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2412        self.auto_replace_emoji_shortcode = auto_replace;
 2413    }
 2414
 2415    pub fn toggle_edit_predictions(
 2416        &mut self,
 2417        _: &ToggleEditPrediction,
 2418        window: &mut Window,
 2419        cx: &mut Context<Self>,
 2420    ) {
 2421        if self.show_inline_completions_override.is_some() {
 2422            self.set_show_edit_predictions(None, window, cx);
 2423        } else {
 2424            let show_edit_predictions = !self.edit_predictions_enabled();
 2425            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2426        }
 2427    }
 2428
 2429    pub fn set_show_edit_predictions(
 2430        &mut self,
 2431        show_edit_predictions: Option<bool>,
 2432        window: &mut Window,
 2433        cx: &mut Context<Self>,
 2434    ) {
 2435        self.show_inline_completions_override = show_edit_predictions;
 2436        self.update_edit_prediction_settings(cx);
 2437
 2438        if let Some(false) = show_edit_predictions {
 2439            self.discard_inline_completion(false, cx);
 2440        } else {
 2441            self.refresh_inline_completion(false, true, window, cx);
 2442        }
 2443    }
 2444
 2445    fn inline_completions_disabled_in_scope(
 2446        &self,
 2447        buffer: &Entity<Buffer>,
 2448        buffer_position: language::Anchor,
 2449        cx: &App,
 2450    ) -> bool {
 2451        let snapshot = buffer.read(cx).snapshot();
 2452        let settings = snapshot.settings_at(buffer_position, cx);
 2453
 2454        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2455            return false;
 2456        };
 2457
 2458        scope.override_name().map_or(false, |scope_name| {
 2459            settings
 2460                .edit_predictions_disabled_in
 2461                .iter()
 2462                .any(|s| s == scope_name)
 2463        })
 2464    }
 2465
 2466    pub fn set_use_modal_editing(&mut self, to: bool) {
 2467        self.use_modal_editing = to;
 2468    }
 2469
 2470    pub fn use_modal_editing(&self) -> bool {
 2471        self.use_modal_editing
 2472    }
 2473
 2474    fn selections_did_change(
 2475        &mut self,
 2476        local: bool,
 2477        old_cursor_position: &Anchor,
 2478        show_completions: bool,
 2479        window: &mut Window,
 2480        cx: &mut Context<Self>,
 2481    ) {
 2482        window.invalidate_character_coordinates();
 2483
 2484        // Copy selections to primary selection buffer
 2485        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2486        if local {
 2487            let selections = self.selections.all::<usize>(cx);
 2488            let buffer_handle = self.buffer.read(cx).read(cx);
 2489
 2490            let mut text = String::new();
 2491            for (index, selection) in selections.iter().enumerate() {
 2492                let text_for_selection = buffer_handle
 2493                    .text_for_range(selection.start..selection.end)
 2494                    .collect::<String>();
 2495
 2496                text.push_str(&text_for_selection);
 2497                if index != selections.len() - 1 {
 2498                    text.push('\n');
 2499                }
 2500            }
 2501
 2502            if !text.is_empty() {
 2503                cx.write_to_primary(ClipboardItem::new_string(text));
 2504            }
 2505        }
 2506
 2507        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2508            self.buffer.update(cx, |buffer, cx| {
 2509                buffer.set_active_selections(
 2510                    &self.selections.disjoint_anchors(),
 2511                    self.selections.line_mode,
 2512                    self.cursor_shape,
 2513                    cx,
 2514                )
 2515            });
 2516        }
 2517        let display_map = self
 2518            .display_map
 2519            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2520        let buffer = &display_map.buffer_snapshot;
 2521        self.add_selections_state = None;
 2522        self.select_next_state = None;
 2523        self.select_prev_state = None;
 2524        self.select_syntax_node_history.try_clear();
 2525        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2526        self.snippet_stack
 2527            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2528        self.take_rename(false, window, cx);
 2529
 2530        let new_cursor_position = self.selections.newest_anchor().head();
 2531
 2532        self.push_to_nav_history(
 2533            *old_cursor_position,
 2534            Some(new_cursor_position.to_point(buffer)),
 2535            false,
 2536            cx,
 2537        );
 2538
 2539        if local {
 2540            let new_cursor_position = self.selections.newest_anchor().head();
 2541            let mut context_menu = self.context_menu.borrow_mut();
 2542            let completion_menu = match context_menu.as_ref() {
 2543                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2544                _ => {
 2545                    *context_menu = None;
 2546                    None
 2547                }
 2548            };
 2549            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2550                if !self.registered_buffers.contains_key(&buffer_id) {
 2551                    if let Some(project) = self.project.as_ref() {
 2552                        project.update(cx, |project, cx| {
 2553                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2554                                return;
 2555                            };
 2556                            self.registered_buffers.insert(
 2557                                buffer_id,
 2558                                project.register_buffer_with_language_servers(&buffer, cx),
 2559                            );
 2560                        })
 2561                    }
 2562                }
 2563            }
 2564
 2565            if let Some(completion_menu) = completion_menu {
 2566                let cursor_position = new_cursor_position.to_offset(buffer);
 2567                let (word_range, kind) =
 2568                    buffer.surrounding_word(completion_menu.initial_position, true);
 2569                if kind == Some(CharKind::Word)
 2570                    && word_range.to_inclusive().contains(&cursor_position)
 2571                {
 2572                    let mut completion_menu = completion_menu.clone();
 2573                    drop(context_menu);
 2574
 2575                    let query = Self::completion_query(buffer, cursor_position);
 2576                    cx.spawn(async move |this, cx| {
 2577                        completion_menu
 2578                            .filter(query.as_deref(), cx.background_executor().clone())
 2579                            .await;
 2580
 2581                        this.update(cx, |this, cx| {
 2582                            let mut context_menu = this.context_menu.borrow_mut();
 2583                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2584                            else {
 2585                                return;
 2586                            };
 2587
 2588                            if menu.id > completion_menu.id {
 2589                                return;
 2590                            }
 2591
 2592                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2593                            drop(context_menu);
 2594                            cx.notify();
 2595                        })
 2596                    })
 2597                    .detach();
 2598
 2599                    if show_completions {
 2600                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2601                    }
 2602                } else {
 2603                    drop(context_menu);
 2604                    self.hide_context_menu(window, cx);
 2605                }
 2606            } else {
 2607                drop(context_menu);
 2608            }
 2609
 2610            hide_hover(self, cx);
 2611
 2612            if old_cursor_position.to_display_point(&display_map).row()
 2613                != new_cursor_position.to_display_point(&display_map).row()
 2614            {
 2615                self.available_code_actions.take();
 2616            }
 2617            self.refresh_code_actions(window, cx);
 2618            self.refresh_document_highlights(cx);
 2619            self.refresh_selected_text_highlights(window, cx);
 2620            refresh_matching_bracket_highlights(self, window, cx);
 2621            self.update_visible_inline_completion(window, cx);
 2622            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2623            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2624            self.inline_blame_popover.take();
 2625            if self.git_blame_inline_enabled {
 2626                self.start_inline_blame_timer(window, cx);
 2627            }
 2628        }
 2629
 2630        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2631        cx.emit(EditorEvent::SelectionsChanged { local });
 2632
 2633        let selections = &self.selections.disjoint;
 2634        if selections.len() == 1 {
 2635            cx.emit(SearchEvent::ActiveMatchChanged)
 2636        }
 2637        if local {
 2638            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2639                let inmemory_selections = selections
 2640                    .iter()
 2641                    .map(|s| {
 2642                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2643                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2644                    })
 2645                    .collect();
 2646                self.update_restoration_data(cx, |data| {
 2647                    data.selections = inmemory_selections;
 2648                });
 2649
 2650                if WorkspaceSettings::get(None, cx).restore_on_startup
 2651                    != RestoreOnStartupBehavior::None
 2652                {
 2653                    if let Some(workspace_id) =
 2654                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2655                    {
 2656                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2657                        let selections = selections.clone();
 2658                        let background_executor = cx.background_executor().clone();
 2659                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2660                        self.serialize_selections = cx.background_spawn(async move {
 2661                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2662                    let db_selections = selections
 2663                        .iter()
 2664                        .map(|selection| {
 2665                            (
 2666                                selection.start.to_offset(&snapshot),
 2667                                selection.end.to_offset(&snapshot),
 2668                            )
 2669                        })
 2670                        .collect();
 2671
 2672                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2673                        .await
 2674                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2675                        .log_err();
 2676                });
 2677                    }
 2678                }
 2679            }
 2680        }
 2681
 2682        cx.notify();
 2683    }
 2684
 2685    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2686        use text::ToOffset as _;
 2687        use text::ToPoint as _;
 2688
 2689        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2690            return;
 2691        }
 2692
 2693        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2694            return;
 2695        };
 2696
 2697        let snapshot = singleton.read(cx).snapshot();
 2698        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2699            let display_snapshot = display_map.snapshot(cx);
 2700
 2701            display_snapshot
 2702                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2703                .map(|fold| {
 2704                    fold.range.start.text_anchor.to_point(&snapshot)
 2705                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2706                })
 2707                .collect()
 2708        });
 2709        self.update_restoration_data(cx, |data| {
 2710            data.folds = inmemory_folds;
 2711        });
 2712
 2713        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2714            return;
 2715        };
 2716        let background_executor = cx.background_executor().clone();
 2717        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2718        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2719            display_map
 2720                .snapshot(cx)
 2721                .folds_in_range(0..snapshot.len())
 2722                .map(|fold| {
 2723                    (
 2724                        fold.range.start.text_anchor.to_offset(&snapshot),
 2725                        fold.range.end.text_anchor.to_offset(&snapshot),
 2726                    )
 2727                })
 2728                .collect()
 2729        });
 2730        self.serialize_folds = cx.background_spawn(async move {
 2731            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2732            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2733                .await
 2734                .with_context(|| {
 2735                    format!(
 2736                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2737                    )
 2738                })
 2739                .log_err();
 2740        });
 2741    }
 2742
 2743    pub fn sync_selections(
 2744        &mut self,
 2745        other: Entity<Editor>,
 2746        cx: &mut Context<Self>,
 2747    ) -> gpui::Subscription {
 2748        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2749        self.selections.change_with(cx, |selections| {
 2750            selections.select_anchors(other_selections);
 2751        });
 2752
 2753        let other_subscription =
 2754            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2755                EditorEvent::SelectionsChanged { local: true } => {
 2756                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2757                    if other_selections.is_empty() {
 2758                        return;
 2759                    }
 2760                    this.selections.change_with(cx, |selections| {
 2761                        selections.select_anchors(other_selections);
 2762                    });
 2763                }
 2764                _ => {}
 2765            });
 2766
 2767        let this_subscription =
 2768            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2769                EditorEvent::SelectionsChanged { local: true } => {
 2770                    let these_selections = this.selections.disjoint.to_vec();
 2771                    if these_selections.is_empty() {
 2772                        return;
 2773                    }
 2774                    other.update(cx, |other_editor, cx| {
 2775                        other_editor.selections.change_with(cx, |selections| {
 2776                            selections.select_anchors(these_selections);
 2777                        })
 2778                    });
 2779                }
 2780                _ => {}
 2781            });
 2782
 2783        Subscription::join(other_subscription, this_subscription)
 2784    }
 2785
 2786    pub fn change_selections<R>(
 2787        &mut self,
 2788        autoscroll: Option<Autoscroll>,
 2789        window: &mut Window,
 2790        cx: &mut Context<Self>,
 2791        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2792    ) -> R {
 2793        self.change_selections_inner(autoscroll, true, window, cx, change)
 2794    }
 2795
 2796    fn change_selections_inner<R>(
 2797        &mut self,
 2798        autoscroll: Option<Autoscroll>,
 2799        request_completions: bool,
 2800        window: &mut Window,
 2801        cx: &mut Context<Self>,
 2802        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2803    ) -> R {
 2804        let old_cursor_position = self.selections.newest_anchor().head();
 2805        self.push_to_selection_history();
 2806
 2807        let (changed, result) = self.selections.change_with(cx, change);
 2808
 2809        if changed {
 2810            if let Some(autoscroll) = autoscroll {
 2811                self.request_autoscroll(autoscroll, cx);
 2812            }
 2813            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2814
 2815            if self.should_open_signature_help_automatically(
 2816                &old_cursor_position,
 2817                self.signature_help_state.backspace_pressed(),
 2818                cx,
 2819            ) {
 2820                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2821            }
 2822            self.signature_help_state.set_backspace_pressed(false);
 2823        }
 2824
 2825        result
 2826    }
 2827
 2828    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2829    where
 2830        I: IntoIterator<Item = (Range<S>, T)>,
 2831        S: ToOffset,
 2832        T: Into<Arc<str>>,
 2833    {
 2834        if self.read_only(cx) {
 2835            return;
 2836        }
 2837
 2838        self.buffer
 2839            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2840    }
 2841
 2842    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2843    where
 2844        I: IntoIterator<Item = (Range<S>, T)>,
 2845        S: ToOffset,
 2846        T: Into<Arc<str>>,
 2847    {
 2848        if self.read_only(cx) {
 2849            return;
 2850        }
 2851
 2852        self.buffer.update(cx, |buffer, cx| {
 2853            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2854        });
 2855    }
 2856
 2857    pub fn edit_with_block_indent<I, S, T>(
 2858        &mut self,
 2859        edits: I,
 2860        original_indent_columns: Vec<Option<u32>>,
 2861        cx: &mut Context<Self>,
 2862    ) where
 2863        I: IntoIterator<Item = (Range<S>, T)>,
 2864        S: ToOffset,
 2865        T: Into<Arc<str>>,
 2866    {
 2867        if self.read_only(cx) {
 2868            return;
 2869        }
 2870
 2871        self.buffer.update(cx, |buffer, cx| {
 2872            buffer.edit(
 2873                edits,
 2874                Some(AutoindentMode::Block {
 2875                    original_indent_columns,
 2876                }),
 2877                cx,
 2878            )
 2879        });
 2880    }
 2881
 2882    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2883        self.hide_context_menu(window, cx);
 2884
 2885        match phase {
 2886            SelectPhase::Begin {
 2887                position,
 2888                add,
 2889                click_count,
 2890            } => self.begin_selection(position, add, click_count, window, cx),
 2891            SelectPhase::BeginColumnar {
 2892                position,
 2893                goal_column,
 2894                reset,
 2895            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2896            SelectPhase::Extend {
 2897                position,
 2898                click_count,
 2899            } => self.extend_selection(position, click_count, window, cx),
 2900            SelectPhase::Update {
 2901                position,
 2902                goal_column,
 2903                scroll_delta,
 2904            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2905            SelectPhase::End => self.end_selection(window, cx),
 2906        }
 2907    }
 2908
 2909    fn extend_selection(
 2910        &mut self,
 2911        position: DisplayPoint,
 2912        click_count: usize,
 2913        window: &mut Window,
 2914        cx: &mut Context<Self>,
 2915    ) {
 2916        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2917        let tail = self.selections.newest::<usize>(cx).tail();
 2918        self.begin_selection(position, false, click_count, window, cx);
 2919
 2920        let position = position.to_offset(&display_map, Bias::Left);
 2921        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2922
 2923        let mut pending_selection = self
 2924            .selections
 2925            .pending_anchor()
 2926            .expect("extend_selection not called with pending selection");
 2927        if position >= tail {
 2928            pending_selection.start = tail_anchor;
 2929        } else {
 2930            pending_selection.end = tail_anchor;
 2931            pending_selection.reversed = true;
 2932        }
 2933
 2934        let mut pending_mode = self.selections.pending_mode().unwrap();
 2935        match &mut pending_mode {
 2936            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2937            _ => {}
 2938        }
 2939
 2940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2941            s.set_pending(pending_selection, pending_mode)
 2942        });
 2943    }
 2944
 2945    fn begin_selection(
 2946        &mut self,
 2947        position: DisplayPoint,
 2948        add: bool,
 2949        click_count: usize,
 2950        window: &mut Window,
 2951        cx: &mut Context<Self>,
 2952    ) {
 2953        if !self.focus_handle.is_focused(window) {
 2954            self.last_focused_descendant = None;
 2955            window.focus(&self.focus_handle);
 2956        }
 2957
 2958        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2959        let buffer = &display_map.buffer_snapshot;
 2960        let newest_selection = self.selections.newest_anchor().clone();
 2961        let position = display_map.clip_point(position, Bias::Left);
 2962
 2963        let start;
 2964        let end;
 2965        let mode;
 2966        let mut auto_scroll;
 2967        match click_count {
 2968            1 => {
 2969                start = buffer.anchor_before(position.to_point(&display_map));
 2970                end = start;
 2971                mode = SelectMode::Character;
 2972                auto_scroll = true;
 2973            }
 2974            2 => {
 2975                let range = movement::surrounding_word(&display_map, position);
 2976                start = buffer.anchor_before(range.start.to_point(&display_map));
 2977                end = buffer.anchor_before(range.end.to_point(&display_map));
 2978                mode = SelectMode::Word(start..end);
 2979                auto_scroll = true;
 2980            }
 2981            3 => {
 2982                let position = display_map
 2983                    .clip_point(position, Bias::Left)
 2984                    .to_point(&display_map);
 2985                let line_start = display_map.prev_line_boundary(position).0;
 2986                let next_line_start = buffer.clip_point(
 2987                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2988                    Bias::Left,
 2989                );
 2990                start = buffer.anchor_before(line_start);
 2991                end = buffer.anchor_before(next_line_start);
 2992                mode = SelectMode::Line(start..end);
 2993                auto_scroll = true;
 2994            }
 2995            _ => {
 2996                start = buffer.anchor_before(0);
 2997                end = buffer.anchor_before(buffer.len());
 2998                mode = SelectMode::All;
 2999                auto_scroll = false;
 3000            }
 3001        }
 3002        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3003
 3004        let point_to_delete: Option<usize> = {
 3005            let selected_points: Vec<Selection<Point>> =
 3006                self.selections.disjoint_in_range(start..end, cx);
 3007
 3008            if !add || click_count > 1 {
 3009                None
 3010            } else if !selected_points.is_empty() {
 3011                Some(selected_points[0].id)
 3012            } else {
 3013                let clicked_point_already_selected =
 3014                    self.selections.disjoint.iter().find(|selection| {
 3015                        selection.start.to_point(buffer) == start.to_point(buffer)
 3016                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3017                    });
 3018
 3019                clicked_point_already_selected.map(|selection| selection.id)
 3020            }
 3021        };
 3022
 3023        let selections_count = self.selections.count();
 3024
 3025        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3026            if let Some(point_to_delete) = point_to_delete {
 3027                s.delete(point_to_delete);
 3028
 3029                if selections_count == 1 {
 3030                    s.set_pending_anchor_range(start..end, mode);
 3031                }
 3032            } else {
 3033                if !add {
 3034                    s.clear_disjoint();
 3035                } else if click_count > 1 {
 3036                    s.delete(newest_selection.id)
 3037                }
 3038
 3039                s.set_pending_anchor_range(start..end, mode);
 3040            }
 3041        });
 3042    }
 3043
 3044    fn begin_columnar_selection(
 3045        &mut self,
 3046        position: DisplayPoint,
 3047        goal_column: u32,
 3048        reset: bool,
 3049        window: &mut Window,
 3050        cx: &mut Context<Self>,
 3051    ) {
 3052        if !self.focus_handle.is_focused(window) {
 3053            self.last_focused_descendant = None;
 3054            window.focus(&self.focus_handle);
 3055        }
 3056
 3057        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3058
 3059        if reset {
 3060            let pointer_position = display_map
 3061                .buffer_snapshot
 3062                .anchor_before(position.to_point(&display_map));
 3063
 3064            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3065                s.clear_disjoint();
 3066                s.set_pending_anchor_range(
 3067                    pointer_position..pointer_position,
 3068                    SelectMode::Character,
 3069                );
 3070            });
 3071        }
 3072
 3073        let tail = self.selections.newest::<Point>(cx).tail();
 3074        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3075
 3076        if !reset {
 3077            self.select_columns(
 3078                tail.to_display_point(&display_map),
 3079                position,
 3080                goal_column,
 3081                &display_map,
 3082                window,
 3083                cx,
 3084            );
 3085        }
 3086    }
 3087
 3088    fn update_selection(
 3089        &mut self,
 3090        position: DisplayPoint,
 3091        goal_column: u32,
 3092        scroll_delta: gpui::Point<f32>,
 3093        window: &mut Window,
 3094        cx: &mut Context<Self>,
 3095    ) {
 3096        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3097
 3098        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3099            let tail = tail.to_display_point(&display_map);
 3100            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3101        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3102            let buffer = self.buffer.read(cx).snapshot(cx);
 3103            let head;
 3104            let tail;
 3105            let mode = self.selections.pending_mode().unwrap();
 3106            match &mode {
 3107                SelectMode::Character => {
 3108                    head = position.to_point(&display_map);
 3109                    tail = pending.tail().to_point(&buffer);
 3110                }
 3111                SelectMode::Word(original_range) => {
 3112                    let original_display_range = original_range.start.to_display_point(&display_map)
 3113                        ..original_range.end.to_display_point(&display_map);
 3114                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3115                        ..original_display_range.end.to_point(&display_map);
 3116                    if movement::is_inside_word(&display_map, position)
 3117                        || original_display_range.contains(&position)
 3118                    {
 3119                        let word_range = movement::surrounding_word(&display_map, position);
 3120                        if word_range.start < original_display_range.start {
 3121                            head = word_range.start.to_point(&display_map);
 3122                        } else {
 3123                            head = word_range.end.to_point(&display_map);
 3124                        }
 3125                    } else {
 3126                        head = position.to_point(&display_map);
 3127                    }
 3128
 3129                    if head <= original_buffer_range.start {
 3130                        tail = original_buffer_range.end;
 3131                    } else {
 3132                        tail = original_buffer_range.start;
 3133                    }
 3134                }
 3135                SelectMode::Line(original_range) => {
 3136                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3137
 3138                    let position = display_map
 3139                        .clip_point(position, Bias::Left)
 3140                        .to_point(&display_map);
 3141                    let line_start = display_map.prev_line_boundary(position).0;
 3142                    let next_line_start = buffer.clip_point(
 3143                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3144                        Bias::Left,
 3145                    );
 3146
 3147                    if line_start < original_range.start {
 3148                        head = line_start
 3149                    } else {
 3150                        head = next_line_start
 3151                    }
 3152
 3153                    if head <= original_range.start {
 3154                        tail = original_range.end;
 3155                    } else {
 3156                        tail = original_range.start;
 3157                    }
 3158                }
 3159                SelectMode::All => {
 3160                    return;
 3161                }
 3162            };
 3163
 3164            if head < tail {
 3165                pending.start = buffer.anchor_before(head);
 3166                pending.end = buffer.anchor_before(tail);
 3167                pending.reversed = true;
 3168            } else {
 3169                pending.start = buffer.anchor_before(tail);
 3170                pending.end = buffer.anchor_before(head);
 3171                pending.reversed = false;
 3172            }
 3173
 3174            self.change_selections(None, window, cx, |s| {
 3175                s.set_pending(pending, mode);
 3176            });
 3177        } else {
 3178            log::error!("update_selection dispatched with no pending selection");
 3179            return;
 3180        }
 3181
 3182        self.apply_scroll_delta(scroll_delta, window, cx);
 3183        cx.notify();
 3184    }
 3185
 3186    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3187        self.columnar_selection_tail.take();
 3188        if self.selections.pending_anchor().is_some() {
 3189            let selections = self.selections.all::<usize>(cx);
 3190            self.change_selections(None, window, cx, |s| {
 3191                s.select(selections);
 3192                s.clear_pending();
 3193            });
 3194        }
 3195    }
 3196
 3197    fn select_columns(
 3198        &mut self,
 3199        tail: DisplayPoint,
 3200        head: DisplayPoint,
 3201        goal_column: u32,
 3202        display_map: &DisplaySnapshot,
 3203        window: &mut Window,
 3204        cx: &mut Context<Self>,
 3205    ) {
 3206        let start_row = cmp::min(tail.row(), head.row());
 3207        let end_row = cmp::max(tail.row(), head.row());
 3208        let start_column = cmp::min(tail.column(), goal_column);
 3209        let end_column = cmp::max(tail.column(), goal_column);
 3210        let reversed = start_column < tail.column();
 3211
 3212        let selection_ranges = (start_row.0..=end_row.0)
 3213            .map(DisplayRow)
 3214            .filter_map(|row| {
 3215                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3216                    let start = display_map
 3217                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3218                        .to_point(display_map);
 3219                    let end = display_map
 3220                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3221                        .to_point(display_map);
 3222                    if reversed {
 3223                        Some(end..start)
 3224                    } else {
 3225                        Some(start..end)
 3226                    }
 3227                } else {
 3228                    None
 3229                }
 3230            })
 3231            .collect::<Vec<_>>();
 3232
 3233        self.change_selections(None, window, cx, |s| {
 3234            s.select_ranges(selection_ranges);
 3235        });
 3236        cx.notify();
 3237    }
 3238
 3239    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3240        self.selections
 3241            .all_adjusted(cx)
 3242            .iter()
 3243            .any(|selection| !selection.is_empty())
 3244    }
 3245
 3246    pub fn has_pending_nonempty_selection(&self) -> bool {
 3247        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3248            Some(Selection { start, end, .. }) => start != end,
 3249            None => false,
 3250        };
 3251
 3252        pending_nonempty_selection
 3253            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3254    }
 3255
 3256    pub fn has_pending_selection(&self) -> bool {
 3257        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3258    }
 3259
 3260    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3261        self.selection_mark_mode = false;
 3262
 3263        if self.clear_expanded_diff_hunks(cx) {
 3264            cx.notify();
 3265            return;
 3266        }
 3267        if self.dismiss_menus_and_popups(true, window, cx) {
 3268            return;
 3269        }
 3270
 3271        if self.mode.is_full()
 3272            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3273        {
 3274            return;
 3275        }
 3276
 3277        cx.propagate();
 3278    }
 3279
 3280    pub fn dismiss_menus_and_popups(
 3281        &mut self,
 3282        is_user_requested: bool,
 3283        window: &mut Window,
 3284        cx: &mut Context<Self>,
 3285    ) -> bool {
 3286        if self.take_rename(false, window, cx).is_some() {
 3287            return true;
 3288        }
 3289
 3290        if hide_hover(self, cx) {
 3291            return true;
 3292        }
 3293
 3294        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3295            return true;
 3296        }
 3297
 3298        if self.hide_context_menu(window, cx).is_some() {
 3299            return true;
 3300        }
 3301
 3302        if self.mouse_context_menu.take().is_some() {
 3303            return true;
 3304        }
 3305
 3306        if is_user_requested && self.discard_inline_completion(true, cx) {
 3307            return true;
 3308        }
 3309
 3310        if self.snippet_stack.pop().is_some() {
 3311            return true;
 3312        }
 3313
 3314        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3315            self.dismiss_diagnostics(cx);
 3316            return true;
 3317        }
 3318
 3319        false
 3320    }
 3321
 3322    fn linked_editing_ranges_for(
 3323        &self,
 3324        selection: Range<text::Anchor>,
 3325        cx: &App,
 3326    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3327        if self.linked_edit_ranges.is_empty() {
 3328            return None;
 3329        }
 3330        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3331            selection.end.buffer_id.and_then(|end_buffer_id| {
 3332                if selection.start.buffer_id != Some(end_buffer_id) {
 3333                    return None;
 3334                }
 3335                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3336                let snapshot = buffer.read(cx).snapshot();
 3337                self.linked_edit_ranges
 3338                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3339                    .map(|ranges| (ranges, snapshot, buffer))
 3340            })?;
 3341        use text::ToOffset as TO;
 3342        // find offset from the start of current range to current cursor position
 3343        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3344
 3345        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3346        let start_difference = start_offset - start_byte_offset;
 3347        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3348        let end_difference = end_offset - start_byte_offset;
 3349        // Current range has associated linked ranges.
 3350        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3351        for range in linked_ranges.iter() {
 3352            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3353            let end_offset = start_offset + end_difference;
 3354            let start_offset = start_offset + start_difference;
 3355            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3356                continue;
 3357            }
 3358            if self.selections.disjoint_anchor_ranges().any(|s| {
 3359                if s.start.buffer_id != selection.start.buffer_id
 3360                    || s.end.buffer_id != selection.end.buffer_id
 3361                {
 3362                    return false;
 3363                }
 3364                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3365                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3366            }) {
 3367                continue;
 3368            }
 3369            let start = buffer_snapshot.anchor_after(start_offset);
 3370            let end = buffer_snapshot.anchor_after(end_offset);
 3371            linked_edits
 3372                .entry(buffer.clone())
 3373                .or_default()
 3374                .push(start..end);
 3375        }
 3376        Some(linked_edits)
 3377    }
 3378
 3379    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3380        let text: Arc<str> = text.into();
 3381
 3382        if self.read_only(cx) {
 3383            return;
 3384        }
 3385
 3386        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3387
 3388        let selections = self.selections.all_adjusted(cx);
 3389        let mut bracket_inserted = false;
 3390        let mut edits = Vec::new();
 3391        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3392        let mut new_selections = Vec::with_capacity(selections.len());
 3393        let mut new_autoclose_regions = Vec::new();
 3394        let snapshot = self.buffer.read(cx).read(cx);
 3395        let mut clear_linked_edit_ranges = false;
 3396
 3397        for (selection, autoclose_region) in
 3398            self.selections_with_autoclose_regions(selections, &snapshot)
 3399        {
 3400            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3401                // Determine if the inserted text matches the opening or closing
 3402                // bracket of any of this language's bracket pairs.
 3403                let mut bracket_pair = None;
 3404                let mut is_bracket_pair_start = false;
 3405                let mut is_bracket_pair_end = false;
 3406                if !text.is_empty() {
 3407                    let mut bracket_pair_matching_end = None;
 3408                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3409                    //  and they are removing the character that triggered IME popup.
 3410                    for (pair, enabled) in scope.brackets() {
 3411                        if !pair.close && !pair.surround {
 3412                            continue;
 3413                        }
 3414
 3415                        if enabled && pair.start.ends_with(text.as_ref()) {
 3416                            let prefix_len = pair.start.len() - text.len();
 3417                            let preceding_text_matches_prefix = prefix_len == 0
 3418                                || (selection.start.column >= (prefix_len as u32)
 3419                                    && snapshot.contains_str_at(
 3420                                        Point::new(
 3421                                            selection.start.row,
 3422                                            selection.start.column - (prefix_len as u32),
 3423                                        ),
 3424                                        &pair.start[..prefix_len],
 3425                                    ));
 3426                            if preceding_text_matches_prefix {
 3427                                bracket_pair = Some(pair.clone());
 3428                                is_bracket_pair_start = true;
 3429                                break;
 3430                            }
 3431                        }
 3432                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3433                        {
 3434                            // take first bracket pair matching end, but don't break in case a later bracket
 3435                            // pair matches start
 3436                            bracket_pair_matching_end = Some(pair.clone());
 3437                        }
 3438                    }
 3439                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3440                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3441                        is_bracket_pair_end = true;
 3442                    }
 3443                }
 3444
 3445                if let Some(bracket_pair) = bracket_pair {
 3446                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3447                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3448                    let auto_surround =
 3449                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3450                    if selection.is_empty() {
 3451                        if is_bracket_pair_start {
 3452                            // If the inserted text is a suffix of an opening bracket and the
 3453                            // selection is preceded by the rest of the opening bracket, then
 3454                            // insert the closing bracket.
 3455                            let following_text_allows_autoclose = snapshot
 3456                                .chars_at(selection.start)
 3457                                .next()
 3458                                .map_or(true, |c| scope.should_autoclose_before(c));
 3459
 3460                            let preceding_text_allows_autoclose = selection.start.column == 0
 3461                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3462                                    true,
 3463                                    |c| {
 3464                                        bracket_pair.start != bracket_pair.end
 3465                                            || !snapshot
 3466                                                .char_classifier_at(selection.start)
 3467                                                .is_word(c)
 3468                                    },
 3469                                );
 3470
 3471                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3472                                && bracket_pair.start.len() == 1
 3473                            {
 3474                                let target = bracket_pair.start.chars().next().unwrap();
 3475                                let current_line_count = snapshot
 3476                                    .reversed_chars_at(selection.start)
 3477                                    .take_while(|&c| c != '\n')
 3478                                    .filter(|&c| c == target)
 3479                                    .count();
 3480                                current_line_count % 2 == 1
 3481                            } else {
 3482                                false
 3483                            };
 3484
 3485                            if autoclose
 3486                                && bracket_pair.close
 3487                                && following_text_allows_autoclose
 3488                                && preceding_text_allows_autoclose
 3489                                && !is_closing_quote
 3490                            {
 3491                                let anchor = snapshot.anchor_before(selection.end);
 3492                                new_selections.push((selection.map(|_| anchor), text.len()));
 3493                                new_autoclose_regions.push((
 3494                                    anchor,
 3495                                    text.len(),
 3496                                    selection.id,
 3497                                    bracket_pair.clone(),
 3498                                ));
 3499                                edits.push((
 3500                                    selection.range(),
 3501                                    format!("{}{}", text, bracket_pair.end).into(),
 3502                                ));
 3503                                bracket_inserted = true;
 3504                                continue;
 3505                            }
 3506                        }
 3507
 3508                        if let Some(region) = autoclose_region {
 3509                            // If the selection is followed by an auto-inserted closing bracket,
 3510                            // then don't insert that closing bracket again; just move the selection
 3511                            // past the closing bracket.
 3512                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3513                                && text.as_ref() == region.pair.end.as_str();
 3514                            if should_skip {
 3515                                let anchor = snapshot.anchor_after(selection.end);
 3516                                new_selections
 3517                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3518                                continue;
 3519                            }
 3520                        }
 3521
 3522                        let always_treat_brackets_as_autoclosed = snapshot
 3523                            .language_settings_at(selection.start, cx)
 3524                            .always_treat_brackets_as_autoclosed;
 3525                        if always_treat_brackets_as_autoclosed
 3526                            && is_bracket_pair_end
 3527                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3528                        {
 3529                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3530                            // and the inserted text is a closing bracket and the selection is followed
 3531                            // by the closing bracket then move the selection past the closing bracket.
 3532                            let anchor = snapshot.anchor_after(selection.end);
 3533                            new_selections.push((selection.map(|_| anchor), text.len()));
 3534                            continue;
 3535                        }
 3536                    }
 3537                    // If an opening bracket is 1 character long and is typed while
 3538                    // text is selected, then surround that text with the bracket pair.
 3539                    else if auto_surround
 3540                        && bracket_pair.surround
 3541                        && is_bracket_pair_start
 3542                        && bracket_pair.start.chars().count() == 1
 3543                    {
 3544                        edits.push((selection.start..selection.start, text.clone()));
 3545                        edits.push((
 3546                            selection.end..selection.end,
 3547                            bracket_pair.end.as_str().into(),
 3548                        ));
 3549                        bracket_inserted = true;
 3550                        new_selections.push((
 3551                            Selection {
 3552                                id: selection.id,
 3553                                start: snapshot.anchor_after(selection.start),
 3554                                end: snapshot.anchor_before(selection.end),
 3555                                reversed: selection.reversed,
 3556                                goal: selection.goal,
 3557                            },
 3558                            0,
 3559                        ));
 3560                        continue;
 3561                    }
 3562                }
 3563            }
 3564
 3565            if self.auto_replace_emoji_shortcode
 3566                && selection.is_empty()
 3567                && text.as_ref().ends_with(':')
 3568            {
 3569                if let Some(possible_emoji_short_code) =
 3570                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3571                {
 3572                    if !possible_emoji_short_code.is_empty() {
 3573                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3574                            let emoji_shortcode_start = Point::new(
 3575                                selection.start.row,
 3576                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3577                            );
 3578
 3579                            // Remove shortcode from buffer
 3580                            edits.push((
 3581                                emoji_shortcode_start..selection.start,
 3582                                "".to_string().into(),
 3583                            ));
 3584                            new_selections.push((
 3585                                Selection {
 3586                                    id: selection.id,
 3587                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3588                                    end: snapshot.anchor_before(selection.start),
 3589                                    reversed: selection.reversed,
 3590                                    goal: selection.goal,
 3591                                },
 3592                                0,
 3593                            ));
 3594
 3595                            // Insert emoji
 3596                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3597                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3598                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3599
 3600                            continue;
 3601                        }
 3602                    }
 3603                }
 3604            }
 3605
 3606            // If not handling any auto-close operation, then just replace the selected
 3607            // text with the given input and move the selection to the end of the
 3608            // newly inserted text.
 3609            let anchor = snapshot.anchor_after(selection.end);
 3610            if !self.linked_edit_ranges.is_empty() {
 3611                let start_anchor = snapshot.anchor_before(selection.start);
 3612
 3613                let is_word_char = text.chars().next().map_or(true, |char| {
 3614                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3615                    classifier.is_word(char)
 3616                });
 3617
 3618                if is_word_char {
 3619                    if let Some(ranges) = self
 3620                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3621                    {
 3622                        for (buffer, edits) in ranges {
 3623                            linked_edits
 3624                                .entry(buffer.clone())
 3625                                .or_default()
 3626                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3627                        }
 3628                    }
 3629                } else {
 3630                    clear_linked_edit_ranges = true;
 3631                }
 3632            }
 3633
 3634            new_selections.push((selection.map(|_| anchor), 0));
 3635            edits.push((selection.start..selection.end, text.clone()));
 3636        }
 3637
 3638        drop(snapshot);
 3639
 3640        self.transact(window, cx, |this, window, cx| {
 3641            if clear_linked_edit_ranges {
 3642                this.linked_edit_ranges.clear();
 3643            }
 3644            let initial_buffer_versions =
 3645                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3646
 3647            this.buffer.update(cx, |buffer, cx| {
 3648                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3649            });
 3650            for (buffer, edits) in linked_edits {
 3651                buffer.update(cx, |buffer, cx| {
 3652                    let snapshot = buffer.snapshot();
 3653                    let edits = edits
 3654                        .into_iter()
 3655                        .map(|(range, text)| {
 3656                            use text::ToPoint as TP;
 3657                            let end_point = TP::to_point(&range.end, &snapshot);
 3658                            let start_point = TP::to_point(&range.start, &snapshot);
 3659                            (start_point..end_point, text)
 3660                        })
 3661                        .sorted_by_key(|(range, _)| range.start);
 3662                    buffer.edit(edits, None, cx);
 3663                })
 3664            }
 3665            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3666            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3667            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3668            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3669                .zip(new_selection_deltas)
 3670                .map(|(selection, delta)| Selection {
 3671                    id: selection.id,
 3672                    start: selection.start + delta,
 3673                    end: selection.end + delta,
 3674                    reversed: selection.reversed,
 3675                    goal: SelectionGoal::None,
 3676                })
 3677                .collect::<Vec<_>>();
 3678
 3679            let mut i = 0;
 3680            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3681                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3682                let start = map.buffer_snapshot.anchor_before(position);
 3683                let end = map.buffer_snapshot.anchor_after(position);
 3684                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3685                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3686                        Ordering::Less => i += 1,
 3687                        Ordering::Greater => break,
 3688                        Ordering::Equal => {
 3689                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3690                                Ordering::Less => i += 1,
 3691                                Ordering::Equal => break,
 3692                                Ordering::Greater => break,
 3693                            }
 3694                        }
 3695                    }
 3696                }
 3697                this.autoclose_regions.insert(
 3698                    i,
 3699                    AutocloseRegion {
 3700                        selection_id,
 3701                        range: start..end,
 3702                        pair,
 3703                    },
 3704                );
 3705            }
 3706
 3707            let had_active_inline_completion = this.has_active_inline_completion();
 3708            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3709                s.select(new_selections)
 3710            });
 3711
 3712            if !bracket_inserted {
 3713                if let Some(on_type_format_task) =
 3714                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3715                {
 3716                    on_type_format_task.detach_and_log_err(cx);
 3717                }
 3718            }
 3719
 3720            let editor_settings = EditorSettings::get_global(cx);
 3721            if bracket_inserted
 3722                && (editor_settings.auto_signature_help
 3723                    || editor_settings.show_signature_help_after_edits)
 3724            {
 3725                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3726            }
 3727
 3728            let trigger_in_words =
 3729                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3730            if this.hard_wrap.is_some() {
 3731                let latest: Range<Point> = this.selections.newest(cx).range();
 3732                if latest.is_empty()
 3733                    && this
 3734                        .buffer()
 3735                        .read(cx)
 3736                        .snapshot(cx)
 3737                        .line_len(MultiBufferRow(latest.start.row))
 3738                        == latest.start.column
 3739                {
 3740                    this.rewrap_impl(
 3741                        RewrapOptions {
 3742                            override_language_settings: true,
 3743                            preserve_existing_whitespace: true,
 3744                        },
 3745                        cx,
 3746                    )
 3747                }
 3748            }
 3749            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3750            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3751            this.refresh_inline_completion(true, false, window, cx);
 3752            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3753        });
 3754    }
 3755
 3756    fn find_possible_emoji_shortcode_at_position(
 3757        snapshot: &MultiBufferSnapshot,
 3758        position: Point,
 3759    ) -> Option<String> {
 3760        let mut chars = Vec::new();
 3761        let mut found_colon = false;
 3762        for char in snapshot.reversed_chars_at(position).take(100) {
 3763            // Found a possible emoji shortcode in the middle of the buffer
 3764            if found_colon {
 3765                if char.is_whitespace() {
 3766                    chars.reverse();
 3767                    return Some(chars.iter().collect());
 3768                }
 3769                // If the previous character is not a whitespace, we are in the middle of a word
 3770                // and we only want to complete the shortcode if the word is made up of other emojis
 3771                let mut containing_word = String::new();
 3772                for ch in snapshot
 3773                    .reversed_chars_at(position)
 3774                    .skip(chars.len() + 1)
 3775                    .take(100)
 3776                {
 3777                    if ch.is_whitespace() {
 3778                        break;
 3779                    }
 3780                    containing_word.push(ch);
 3781                }
 3782                let containing_word = containing_word.chars().rev().collect::<String>();
 3783                if util::word_consists_of_emojis(containing_word.as_str()) {
 3784                    chars.reverse();
 3785                    return Some(chars.iter().collect());
 3786                }
 3787            }
 3788
 3789            if char.is_whitespace() || !char.is_ascii() {
 3790                return None;
 3791            }
 3792            if char == ':' {
 3793                found_colon = true;
 3794            } else {
 3795                chars.push(char);
 3796            }
 3797        }
 3798        // Found a possible emoji shortcode at the beginning of the buffer
 3799        chars.reverse();
 3800        Some(chars.iter().collect())
 3801    }
 3802
 3803    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3804        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3805        self.transact(window, cx, |this, window, cx| {
 3806            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3807                let selections = this.selections.all::<usize>(cx);
 3808                let multi_buffer = this.buffer.read(cx);
 3809                let buffer = multi_buffer.snapshot(cx);
 3810                selections
 3811                    .iter()
 3812                    .map(|selection| {
 3813                        let start_point = selection.start.to_point(&buffer);
 3814                        let mut indent =
 3815                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3816                        indent.len = cmp::min(indent.len, start_point.column);
 3817                        let start = selection.start;
 3818                        let end = selection.end;
 3819                        let selection_is_empty = start == end;
 3820                        let language_scope = buffer.language_scope_at(start);
 3821                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3822                            &language_scope
 3823                        {
 3824                            let insert_extra_newline =
 3825                                insert_extra_newline_brackets(&buffer, start..end, language)
 3826                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3827
 3828                            // Comment extension on newline is allowed only for cursor selections
 3829                            let comment_delimiter = maybe!({
 3830                                if !selection_is_empty {
 3831                                    return None;
 3832                                }
 3833
 3834                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3835                                    return None;
 3836                                }
 3837
 3838                                let delimiters = language.line_comment_prefixes();
 3839                                let max_len_of_delimiter =
 3840                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3841                                let (snapshot, range) =
 3842                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3843
 3844                                let mut index_of_first_non_whitespace = 0;
 3845                                let comment_candidate = snapshot
 3846                                    .chars_for_range(range)
 3847                                    .skip_while(|c| {
 3848                                        let should_skip = c.is_whitespace();
 3849                                        if should_skip {
 3850                                            index_of_first_non_whitespace += 1;
 3851                                        }
 3852                                        should_skip
 3853                                    })
 3854                                    .take(max_len_of_delimiter)
 3855                                    .collect::<String>();
 3856                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3857                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3858                                })?;
 3859                                let cursor_is_placed_after_comment_marker =
 3860                                    index_of_first_non_whitespace + comment_prefix.len()
 3861                                        <= start_point.column as usize;
 3862                                if cursor_is_placed_after_comment_marker {
 3863                                    Some(comment_prefix.clone())
 3864                                } else {
 3865                                    None
 3866                                }
 3867                            });
 3868                            (comment_delimiter, insert_extra_newline)
 3869                        } else {
 3870                            (None, false)
 3871                        };
 3872
 3873                        let capacity_for_delimiter = comment_delimiter
 3874                            .as_deref()
 3875                            .map(str::len)
 3876                            .unwrap_or_default();
 3877                        let mut new_text =
 3878                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3879                        new_text.push('\n');
 3880                        new_text.extend(indent.chars());
 3881                        if let Some(delimiter) = &comment_delimiter {
 3882                            new_text.push_str(delimiter);
 3883                        }
 3884                        if insert_extra_newline {
 3885                            new_text = new_text.repeat(2);
 3886                        }
 3887
 3888                        let anchor = buffer.anchor_after(end);
 3889                        let new_selection = selection.map(|_| anchor);
 3890                        (
 3891                            (start..end, new_text),
 3892                            (insert_extra_newline, new_selection),
 3893                        )
 3894                    })
 3895                    .unzip()
 3896            };
 3897
 3898            this.edit_with_autoindent(edits, cx);
 3899            let buffer = this.buffer.read(cx).snapshot(cx);
 3900            let new_selections = selection_fixup_info
 3901                .into_iter()
 3902                .map(|(extra_newline_inserted, new_selection)| {
 3903                    let mut cursor = new_selection.end.to_point(&buffer);
 3904                    if extra_newline_inserted {
 3905                        cursor.row -= 1;
 3906                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3907                    }
 3908                    new_selection.map(|_| cursor)
 3909                })
 3910                .collect();
 3911
 3912            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3913                s.select(new_selections)
 3914            });
 3915            this.refresh_inline_completion(true, false, window, cx);
 3916        });
 3917    }
 3918
 3919    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3920        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3921
 3922        let buffer = self.buffer.read(cx);
 3923        let snapshot = buffer.snapshot(cx);
 3924
 3925        let mut edits = Vec::new();
 3926        let mut rows = Vec::new();
 3927
 3928        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3929            let cursor = selection.head();
 3930            let row = cursor.row;
 3931
 3932            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3933
 3934            let newline = "\n".to_string();
 3935            edits.push((start_of_line..start_of_line, newline));
 3936
 3937            rows.push(row + rows_inserted as u32);
 3938        }
 3939
 3940        self.transact(window, cx, |editor, window, cx| {
 3941            editor.edit(edits, cx);
 3942
 3943            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3944                let mut index = 0;
 3945                s.move_cursors_with(|map, _, _| {
 3946                    let row = rows[index];
 3947                    index += 1;
 3948
 3949                    let point = Point::new(row, 0);
 3950                    let boundary = map.next_line_boundary(point).1;
 3951                    let clipped = map.clip_point(boundary, Bias::Left);
 3952
 3953                    (clipped, SelectionGoal::None)
 3954                });
 3955            });
 3956
 3957            let mut indent_edits = Vec::new();
 3958            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3959            for row in rows {
 3960                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3961                for (row, indent) in indents {
 3962                    if indent.len == 0 {
 3963                        continue;
 3964                    }
 3965
 3966                    let text = match indent.kind {
 3967                        IndentKind::Space => " ".repeat(indent.len as usize),
 3968                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3969                    };
 3970                    let point = Point::new(row.0, 0);
 3971                    indent_edits.push((point..point, text));
 3972                }
 3973            }
 3974            editor.edit(indent_edits, cx);
 3975        });
 3976    }
 3977
 3978    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3979        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3980
 3981        let buffer = self.buffer.read(cx);
 3982        let snapshot = buffer.snapshot(cx);
 3983
 3984        let mut edits = Vec::new();
 3985        let mut rows = Vec::new();
 3986        let mut rows_inserted = 0;
 3987
 3988        for selection in self.selections.all_adjusted(cx) {
 3989            let cursor = selection.head();
 3990            let row = cursor.row;
 3991
 3992            let point = Point::new(row + 1, 0);
 3993            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3994
 3995            let newline = "\n".to_string();
 3996            edits.push((start_of_line..start_of_line, newline));
 3997
 3998            rows_inserted += 1;
 3999            rows.push(row + rows_inserted);
 4000        }
 4001
 4002        self.transact(window, cx, |editor, window, cx| {
 4003            editor.edit(edits, cx);
 4004
 4005            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4006                let mut index = 0;
 4007                s.move_cursors_with(|map, _, _| {
 4008                    let row = rows[index];
 4009                    index += 1;
 4010
 4011                    let point = Point::new(row, 0);
 4012                    let boundary = map.next_line_boundary(point).1;
 4013                    let clipped = map.clip_point(boundary, Bias::Left);
 4014
 4015                    (clipped, SelectionGoal::None)
 4016                });
 4017            });
 4018
 4019            let mut indent_edits = Vec::new();
 4020            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4021            for row in rows {
 4022                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4023                for (row, indent) in indents {
 4024                    if indent.len == 0 {
 4025                        continue;
 4026                    }
 4027
 4028                    let text = match indent.kind {
 4029                        IndentKind::Space => " ".repeat(indent.len as usize),
 4030                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4031                    };
 4032                    let point = Point::new(row.0, 0);
 4033                    indent_edits.push((point..point, text));
 4034                }
 4035            }
 4036            editor.edit(indent_edits, cx);
 4037        });
 4038    }
 4039
 4040    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4041        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4042            original_indent_columns: Vec::new(),
 4043        });
 4044        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4045    }
 4046
 4047    fn insert_with_autoindent_mode(
 4048        &mut self,
 4049        text: &str,
 4050        autoindent_mode: Option<AutoindentMode>,
 4051        window: &mut Window,
 4052        cx: &mut Context<Self>,
 4053    ) {
 4054        if self.read_only(cx) {
 4055            return;
 4056        }
 4057
 4058        let text: Arc<str> = text.into();
 4059        self.transact(window, cx, |this, window, cx| {
 4060            let old_selections = this.selections.all_adjusted(cx);
 4061            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4062                let anchors = {
 4063                    let snapshot = buffer.read(cx);
 4064                    old_selections
 4065                        .iter()
 4066                        .map(|s| {
 4067                            let anchor = snapshot.anchor_after(s.head());
 4068                            s.map(|_| anchor)
 4069                        })
 4070                        .collect::<Vec<_>>()
 4071                };
 4072                buffer.edit(
 4073                    old_selections
 4074                        .iter()
 4075                        .map(|s| (s.start..s.end, text.clone())),
 4076                    autoindent_mode,
 4077                    cx,
 4078                );
 4079                anchors
 4080            });
 4081
 4082            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4083                s.select_anchors(selection_anchors);
 4084            });
 4085
 4086            cx.notify();
 4087        });
 4088    }
 4089
 4090    fn trigger_completion_on_input(
 4091        &mut self,
 4092        text: &str,
 4093        trigger_in_words: bool,
 4094        window: &mut Window,
 4095        cx: &mut Context<Self>,
 4096    ) {
 4097        let ignore_completion_provider = self
 4098            .context_menu
 4099            .borrow()
 4100            .as_ref()
 4101            .map(|menu| match menu {
 4102                CodeContextMenu::Completions(completions_menu) => {
 4103                    completions_menu.ignore_completion_provider
 4104                }
 4105                CodeContextMenu::CodeActions(_) => false,
 4106            })
 4107            .unwrap_or(false);
 4108
 4109        if ignore_completion_provider {
 4110            self.show_word_completions(&ShowWordCompletions, window, cx);
 4111        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4112            self.show_completions(
 4113                &ShowCompletions {
 4114                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4115                },
 4116                window,
 4117                cx,
 4118            );
 4119        } else {
 4120            self.hide_context_menu(window, cx);
 4121        }
 4122    }
 4123
 4124    fn is_completion_trigger(
 4125        &self,
 4126        text: &str,
 4127        trigger_in_words: bool,
 4128        cx: &mut Context<Self>,
 4129    ) -> bool {
 4130        let position = self.selections.newest_anchor().head();
 4131        let multibuffer = self.buffer.read(cx);
 4132        let Some(buffer) = position
 4133            .buffer_id
 4134            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4135        else {
 4136            return false;
 4137        };
 4138
 4139        if let Some(completion_provider) = &self.completion_provider {
 4140            completion_provider.is_completion_trigger(
 4141                &buffer,
 4142                position.text_anchor,
 4143                text,
 4144                trigger_in_words,
 4145                cx,
 4146            )
 4147        } else {
 4148            false
 4149        }
 4150    }
 4151
 4152    /// If any empty selections is touching the start of its innermost containing autoclose
 4153    /// region, expand it to select the brackets.
 4154    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4155        let selections = self.selections.all::<usize>(cx);
 4156        let buffer = self.buffer.read(cx).read(cx);
 4157        let new_selections = self
 4158            .selections_with_autoclose_regions(selections, &buffer)
 4159            .map(|(mut selection, region)| {
 4160                if !selection.is_empty() {
 4161                    return selection;
 4162                }
 4163
 4164                if let Some(region) = region {
 4165                    let mut range = region.range.to_offset(&buffer);
 4166                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4167                        range.start -= region.pair.start.len();
 4168                        if buffer.contains_str_at(range.start, &region.pair.start)
 4169                            && buffer.contains_str_at(range.end, &region.pair.end)
 4170                        {
 4171                            range.end += region.pair.end.len();
 4172                            selection.start = range.start;
 4173                            selection.end = range.end;
 4174
 4175                            return selection;
 4176                        }
 4177                    }
 4178                }
 4179
 4180                let always_treat_brackets_as_autoclosed = buffer
 4181                    .language_settings_at(selection.start, cx)
 4182                    .always_treat_brackets_as_autoclosed;
 4183
 4184                if !always_treat_brackets_as_autoclosed {
 4185                    return selection;
 4186                }
 4187
 4188                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4189                    for (pair, enabled) in scope.brackets() {
 4190                        if !enabled || !pair.close {
 4191                            continue;
 4192                        }
 4193
 4194                        if buffer.contains_str_at(selection.start, &pair.end) {
 4195                            let pair_start_len = pair.start.len();
 4196                            if buffer.contains_str_at(
 4197                                selection.start.saturating_sub(pair_start_len),
 4198                                &pair.start,
 4199                            ) {
 4200                                selection.start -= pair_start_len;
 4201                                selection.end += pair.end.len();
 4202
 4203                                return selection;
 4204                            }
 4205                        }
 4206                    }
 4207                }
 4208
 4209                selection
 4210            })
 4211            .collect();
 4212
 4213        drop(buffer);
 4214        self.change_selections(None, window, cx, |selections| {
 4215            selections.select(new_selections)
 4216        });
 4217    }
 4218
 4219    /// Iterate the given selections, and for each one, find the smallest surrounding
 4220    /// autoclose region. This uses the ordering of the selections and the autoclose
 4221    /// regions to avoid repeated comparisons.
 4222    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4223        &'a self,
 4224        selections: impl IntoIterator<Item = Selection<D>>,
 4225        buffer: &'a MultiBufferSnapshot,
 4226    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4227        let mut i = 0;
 4228        let mut regions = self.autoclose_regions.as_slice();
 4229        selections.into_iter().map(move |selection| {
 4230            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4231
 4232            let mut enclosing = None;
 4233            while let Some(pair_state) = regions.get(i) {
 4234                if pair_state.range.end.to_offset(buffer) < range.start {
 4235                    regions = &regions[i + 1..];
 4236                    i = 0;
 4237                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4238                    break;
 4239                } else {
 4240                    if pair_state.selection_id == selection.id {
 4241                        enclosing = Some(pair_state);
 4242                    }
 4243                    i += 1;
 4244                }
 4245            }
 4246
 4247            (selection, enclosing)
 4248        })
 4249    }
 4250
 4251    /// Remove any autoclose regions that no longer contain their selection.
 4252    fn invalidate_autoclose_regions(
 4253        &mut self,
 4254        mut selections: &[Selection<Anchor>],
 4255        buffer: &MultiBufferSnapshot,
 4256    ) {
 4257        self.autoclose_regions.retain(|state| {
 4258            let mut i = 0;
 4259            while let Some(selection) = selections.get(i) {
 4260                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4261                    selections = &selections[1..];
 4262                    continue;
 4263                }
 4264                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4265                    break;
 4266                }
 4267                if selection.id == state.selection_id {
 4268                    return true;
 4269                } else {
 4270                    i += 1;
 4271                }
 4272            }
 4273            false
 4274        });
 4275    }
 4276
 4277    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4278        let offset = position.to_offset(buffer);
 4279        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4280        if offset > word_range.start && kind == Some(CharKind::Word) {
 4281            Some(
 4282                buffer
 4283                    .text_for_range(word_range.start..offset)
 4284                    .collect::<String>(),
 4285            )
 4286        } else {
 4287            None
 4288        }
 4289    }
 4290
 4291    pub fn toggle_inline_values(
 4292        &mut self,
 4293        _: &ToggleInlineValues,
 4294        _: &mut Window,
 4295        cx: &mut Context<Self>,
 4296    ) {
 4297        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4298
 4299        self.refresh_inline_values(cx);
 4300    }
 4301
 4302    pub fn toggle_inlay_hints(
 4303        &mut self,
 4304        _: &ToggleInlayHints,
 4305        _: &mut Window,
 4306        cx: &mut Context<Self>,
 4307    ) {
 4308        self.refresh_inlay_hints(
 4309            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4310            cx,
 4311        );
 4312    }
 4313
 4314    pub fn inlay_hints_enabled(&self) -> bool {
 4315        self.inlay_hint_cache.enabled
 4316    }
 4317
 4318    pub fn inline_values_enabled(&self) -> bool {
 4319        self.inline_value_cache.enabled
 4320    }
 4321
 4322    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4323        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4324            return;
 4325        }
 4326
 4327        let reason_description = reason.description();
 4328        let ignore_debounce = matches!(
 4329            reason,
 4330            InlayHintRefreshReason::SettingsChange(_)
 4331                | InlayHintRefreshReason::Toggle(_)
 4332                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4333                | InlayHintRefreshReason::ModifiersChanged(_)
 4334        );
 4335        let (invalidate_cache, required_languages) = match reason {
 4336            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4337                match self.inlay_hint_cache.modifiers_override(enabled) {
 4338                    Some(enabled) => {
 4339                        if enabled {
 4340                            (InvalidationStrategy::RefreshRequested, None)
 4341                        } else {
 4342                            self.splice_inlays(
 4343                                &self
 4344                                    .visible_inlay_hints(cx)
 4345                                    .iter()
 4346                                    .map(|inlay| inlay.id)
 4347                                    .collect::<Vec<InlayId>>(),
 4348                                Vec::new(),
 4349                                cx,
 4350                            );
 4351                            return;
 4352                        }
 4353                    }
 4354                    None => return,
 4355                }
 4356            }
 4357            InlayHintRefreshReason::Toggle(enabled) => {
 4358                if self.inlay_hint_cache.toggle(enabled) {
 4359                    if enabled {
 4360                        (InvalidationStrategy::RefreshRequested, None)
 4361                    } else {
 4362                        self.splice_inlays(
 4363                            &self
 4364                                .visible_inlay_hints(cx)
 4365                                .iter()
 4366                                .map(|inlay| inlay.id)
 4367                                .collect::<Vec<InlayId>>(),
 4368                            Vec::new(),
 4369                            cx,
 4370                        );
 4371                        return;
 4372                    }
 4373                } else {
 4374                    return;
 4375                }
 4376            }
 4377            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4378                match self.inlay_hint_cache.update_settings(
 4379                    &self.buffer,
 4380                    new_settings,
 4381                    self.visible_inlay_hints(cx),
 4382                    cx,
 4383                ) {
 4384                    ControlFlow::Break(Some(InlaySplice {
 4385                        to_remove,
 4386                        to_insert,
 4387                    })) => {
 4388                        self.splice_inlays(&to_remove, to_insert, cx);
 4389                        return;
 4390                    }
 4391                    ControlFlow::Break(None) => return,
 4392                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4393                }
 4394            }
 4395            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4396                if let Some(InlaySplice {
 4397                    to_remove,
 4398                    to_insert,
 4399                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4400                {
 4401                    self.splice_inlays(&to_remove, to_insert, cx);
 4402                }
 4403                self.display_map.update(cx, |display_map, _| {
 4404                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4405                });
 4406                return;
 4407            }
 4408            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4409            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4410                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4411            }
 4412            InlayHintRefreshReason::RefreshRequested => {
 4413                (InvalidationStrategy::RefreshRequested, None)
 4414            }
 4415        };
 4416
 4417        if let Some(InlaySplice {
 4418            to_remove,
 4419            to_insert,
 4420        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4421            reason_description,
 4422            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4423            invalidate_cache,
 4424            ignore_debounce,
 4425            cx,
 4426        ) {
 4427            self.splice_inlays(&to_remove, to_insert, cx);
 4428        }
 4429    }
 4430
 4431    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4432        self.display_map
 4433            .read(cx)
 4434            .current_inlays()
 4435            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4436            .cloned()
 4437            .collect()
 4438    }
 4439
 4440    pub fn excerpts_for_inlay_hints_query(
 4441        &self,
 4442        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4443        cx: &mut Context<Editor>,
 4444    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4445        let Some(project) = self.project.as_ref() else {
 4446            return HashMap::default();
 4447        };
 4448        let project = project.read(cx);
 4449        let multi_buffer = self.buffer().read(cx);
 4450        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4451        let multi_buffer_visible_start = self
 4452            .scroll_manager
 4453            .anchor()
 4454            .anchor
 4455            .to_point(&multi_buffer_snapshot);
 4456        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4457            multi_buffer_visible_start
 4458                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4459            Bias::Left,
 4460        );
 4461        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4462        multi_buffer_snapshot
 4463            .range_to_buffer_ranges(multi_buffer_visible_range)
 4464            .into_iter()
 4465            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4466            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4467                let buffer_file = project::File::from_dyn(buffer.file())?;
 4468                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4469                let worktree_entry = buffer_worktree
 4470                    .read(cx)
 4471                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4472                if worktree_entry.is_ignored {
 4473                    return None;
 4474                }
 4475
 4476                let language = buffer.language()?;
 4477                if let Some(restrict_to_languages) = restrict_to_languages {
 4478                    if !restrict_to_languages.contains(language) {
 4479                        return None;
 4480                    }
 4481                }
 4482                Some((
 4483                    excerpt_id,
 4484                    (
 4485                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4486                        buffer.version().clone(),
 4487                        excerpt_visible_range,
 4488                    ),
 4489                ))
 4490            })
 4491            .collect()
 4492    }
 4493
 4494    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4495        TextLayoutDetails {
 4496            text_system: window.text_system().clone(),
 4497            editor_style: self.style.clone().unwrap(),
 4498            rem_size: window.rem_size(),
 4499            scroll_anchor: self.scroll_manager.anchor(),
 4500            visible_rows: self.visible_line_count(),
 4501            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4502        }
 4503    }
 4504
 4505    pub fn splice_inlays(
 4506        &self,
 4507        to_remove: &[InlayId],
 4508        to_insert: Vec<Inlay>,
 4509        cx: &mut Context<Self>,
 4510    ) {
 4511        self.display_map.update(cx, |display_map, cx| {
 4512            display_map.splice_inlays(to_remove, to_insert, cx)
 4513        });
 4514        cx.notify();
 4515    }
 4516
 4517    fn trigger_on_type_formatting(
 4518        &self,
 4519        input: String,
 4520        window: &mut Window,
 4521        cx: &mut Context<Self>,
 4522    ) -> Option<Task<Result<()>>> {
 4523        if input.len() != 1 {
 4524            return None;
 4525        }
 4526
 4527        let project = self.project.as_ref()?;
 4528        let position = self.selections.newest_anchor().head();
 4529        let (buffer, buffer_position) = self
 4530            .buffer
 4531            .read(cx)
 4532            .text_anchor_for_position(position, cx)?;
 4533
 4534        let settings = language_settings::language_settings(
 4535            buffer
 4536                .read(cx)
 4537                .language_at(buffer_position)
 4538                .map(|l| l.name()),
 4539            buffer.read(cx).file(),
 4540            cx,
 4541        );
 4542        if !settings.use_on_type_format {
 4543            return None;
 4544        }
 4545
 4546        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4547        // hence we do LSP request & edit on host side only — add formats to host's history.
 4548        let push_to_lsp_host_history = true;
 4549        // If this is not the host, append its history with new edits.
 4550        let push_to_client_history = project.read(cx).is_via_collab();
 4551
 4552        let on_type_formatting = project.update(cx, |project, cx| {
 4553            project.on_type_format(
 4554                buffer.clone(),
 4555                buffer_position,
 4556                input,
 4557                push_to_lsp_host_history,
 4558                cx,
 4559            )
 4560        });
 4561        Some(cx.spawn_in(window, async move |editor, cx| {
 4562            if let Some(transaction) = on_type_formatting.await? {
 4563                if push_to_client_history {
 4564                    buffer
 4565                        .update(cx, |buffer, _| {
 4566                            buffer.push_transaction(transaction, Instant::now());
 4567                            buffer.finalize_last_transaction();
 4568                        })
 4569                        .ok();
 4570                }
 4571                editor.update(cx, |editor, cx| {
 4572                    editor.refresh_document_highlights(cx);
 4573                })?;
 4574            }
 4575            Ok(())
 4576        }))
 4577    }
 4578
 4579    pub fn show_word_completions(
 4580        &mut self,
 4581        _: &ShowWordCompletions,
 4582        window: &mut Window,
 4583        cx: &mut Context<Self>,
 4584    ) {
 4585        self.open_completions_menu(true, None, window, cx);
 4586    }
 4587
 4588    pub fn show_completions(
 4589        &mut self,
 4590        options: &ShowCompletions,
 4591        window: &mut Window,
 4592        cx: &mut Context<Self>,
 4593    ) {
 4594        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4595    }
 4596
 4597    fn open_completions_menu(
 4598        &mut self,
 4599        ignore_completion_provider: bool,
 4600        trigger: Option<&str>,
 4601        window: &mut Window,
 4602        cx: &mut Context<Self>,
 4603    ) {
 4604        if self.pending_rename.is_some() {
 4605            return;
 4606        }
 4607        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4608            return;
 4609        }
 4610
 4611        let position = self.selections.newest_anchor().head();
 4612        if position.diff_base_anchor.is_some() {
 4613            return;
 4614        }
 4615        let (buffer, buffer_position) =
 4616            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4617                output
 4618            } else {
 4619                return;
 4620            };
 4621        let buffer_snapshot = buffer.read(cx).snapshot();
 4622        let show_completion_documentation = buffer_snapshot
 4623            .settings_at(buffer_position, cx)
 4624            .show_completion_documentation;
 4625
 4626        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4627
 4628        let trigger_kind = match trigger {
 4629            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4630                CompletionTriggerKind::TRIGGER_CHARACTER
 4631            }
 4632            _ => CompletionTriggerKind::INVOKED,
 4633        };
 4634        let completion_context = CompletionContext {
 4635            trigger_character: trigger.and_then(|trigger| {
 4636                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4637                    Some(String::from(trigger))
 4638                } else {
 4639                    None
 4640                }
 4641            }),
 4642            trigger_kind,
 4643        };
 4644
 4645        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4646        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4647            let word_to_exclude = buffer_snapshot
 4648                .text_for_range(old_range.clone())
 4649                .collect::<String>();
 4650            (
 4651                buffer_snapshot.anchor_before(old_range.start)
 4652                    ..buffer_snapshot.anchor_after(old_range.end),
 4653                Some(word_to_exclude),
 4654            )
 4655        } else {
 4656            (buffer_position..buffer_position, None)
 4657        };
 4658
 4659        let completion_settings = language_settings(
 4660            buffer_snapshot
 4661                .language_at(buffer_position)
 4662                .map(|language| language.name()),
 4663            buffer_snapshot.file(),
 4664            cx,
 4665        )
 4666        .completions;
 4667
 4668        // The document can be large, so stay in reasonable bounds when searching for words,
 4669        // otherwise completion pop-up might be slow to appear.
 4670        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4671        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4672        let min_word_search = buffer_snapshot.clip_point(
 4673            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4674            Bias::Left,
 4675        );
 4676        let max_word_search = buffer_snapshot.clip_point(
 4677            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4678            Bias::Right,
 4679        );
 4680        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4681            ..buffer_snapshot.point_to_offset(max_word_search);
 4682
 4683        let provider = self
 4684            .completion_provider
 4685            .as_ref()
 4686            .filter(|_| !ignore_completion_provider);
 4687        let skip_digits = query
 4688            .as_ref()
 4689            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4690
 4691        let (mut words, provided_completions) = match provider {
 4692            Some(provider) => {
 4693                let completions = provider.completions(
 4694                    position.excerpt_id,
 4695                    &buffer,
 4696                    buffer_position,
 4697                    completion_context,
 4698                    window,
 4699                    cx,
 4700                );
 4701
 4702                let words = match completion_settings.words {
 4703                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4704                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4705                        .background_spawn(async move {
 4706                            buffer_snapshot.words_in_range(WordsQuery {
 4707                                fuzzy_contents: None,
 4708                                range: word_search_range,
 4709                                skip_digits,
 4710                            })
 4711                        }),
 4712                };
 4713
 4714                (words, completions)
 4715            }
 4716            None => (
 4717                cx.background_spawn(async move {
 4718                    buffer_snapshot.words_in_range(WordsQuery {
 4719                        fuzzy_contents: None,
 4720                        range: word_search_range,
 4721                        skip_digits,
 4722                    })
 4723                }),
 4724                Task::ready(Ok(None)),
 4725            ),
 4726        };
 4727
 4728        let sort_completions = provider
 4729            .as_ref()
 4730            .map_or(false, |provider| provider.sort_completions());
 4731
 4732        let filter_completions = provider
 4733            .as_ref()
 4734            .map_or(true, |provider| provider.filter_completions());
 4735
 4736        let id = post_inc(&mut self.next_completion_id);
 4737        let task = cx.spawn_in(window, async move |editor, cx| {
 4738            async move {
 4739                editor.update(cx, |this, _| {
 4740                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4741                })?;
 4742
 4743                let mut completions = Vec::new();
 4744                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4745                    completions.extend(provided_completions);
 4746                    if completion_settings.words == WordsCompletionMode::Fallback {
 4747                        words = Task::ready(BTreeMap::default());
 4748                    }
 4749                }
 4750
 4751                let mut words = words.await;
 4752                if let Some(word_to_exclude) = &word_to_exclude {
 4753                    words.remove(word_to_exclude);
 4754                }
 4755                for lsp_completion in &completions {
 4756                    words.remove(&lsp_completion.new_text);
 4757                }
 4758                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4759                    replace_range: old_range.clone(),
 4760                    new_text: word.clone(),
 4761                    label: CodeLabel::plain(word, None),
 4762                    icon_path: None,
 4763                    documentation: None,
 4764                    source: CompletionSource::BufferWord {
 4765                        word_range,
 4766                        resolved: false,
 4767                    },
 4768                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4769                    confirm: None,
 4770                }));
 4771
 4772                let menu = if completions.is_empty() {
 4773                    None
 4774                } else {
 4775                    let mut menu = CompletionsMenu::new(
 4776                        id,
 4777                        sort_completions,
 4778                        show_completion_documentation,
 4779                        ignore_completion_provider,
 4780                        position,
 4781                        buffer.clone(),
 4782                        completions.into(),
 4783                    );
 4784
 4785                    menu.filter(
 4786                        if filter_completions {
 4787                            query.as_deref()
 4788                        } else {
 4789                            None
 4790                        },
 4791                        cx.background_executor().clone(),
 4792                    )
 4793                    .await;
 4794
 4795                    menu.visible().then_some(menu)
 4796                };
 4797
 4798                editor.update_in(cx, |editor, window, cx| {
 4799                    match editor.context_menu.borrow().as_ref() {
 4800                        None => {}
 4801                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4802                            if prev_menu.id > id {
 4803                                return;
 4804                            }
 4805                        }
 4806                        _ => return,
 4807                    }
 4808
 4809                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4810                        let mut menu = menu.unwrap();
 4811                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4812
 4813                        *editor.context_menu.borrow_mut() =
 4814                            Some(CodeContextMenu::Completions(menu));
 4815
 4816                        if editor.show_edit_predictions_in_menu() {
 4817                            editor.update_visible_inline_completion(window, cx);
 4818                        } else {
 4819                            editor.discard_inline_completion(false, cx);
 4820                        }
 4821
 4822                        cx.notify();
 4823                    } else if editor.completion_tasks.len() <= 1 {
 4824                        // If there are no more completion tasks and the last menu was
 4825                        // empty, we should hide it.
 4826                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4827                        // If it was already hidden and we don't show inline
 4828                        // completions in the menu, we should also show the
 4829                        // inline-completion when available.
 4830                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4831                            editor.update_visible_inline_completion(window, cx);
 4832                        }
 4833                    }
 4834                })?;
 4835
 4836                anyhow::Ok(())
 4837            }
 4838            .log_err()
 4839            .await
 4840        });
 4841
 4842        self.completion_tasks.push((id, task));
 4843    }
 4844
 4845    #[cfg(feature = "test-support")]
 4846    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4847        let menu = self.context_menu.borrow();
 4848        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4849            let completions = menu.completions.borrow();
 4850            Some(completions.to_vec())
 4851        } else {
 4852            None
 4853        }
 4854    }
 4855
 4856    pub fn confirm_completion(
 4857        &mut self,
 4858        action: &ConfirmCompletion,
 4859        window: &mut Window,
 4860        cx: &mut Context<Self>,
 4861    ) -> Option<Task<Result<()>>> {
 4862        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4863        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4864    }
 4865
 4866    pub fn confirm_completion_insert(
 4867        &mut self,
 4868        _: &ConfirmCompletionInsert,
 4869        window: &mut Window,
 4870        cx: &mut Context<Self>,
 4871    ) -> Option<Task<Result<()>>> {
 4872        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4873        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4874    }
 4875
 4876    pub fn confirm_completion_replace(
 4877        &mut self,
 4878        _: &ConfirmCompletionReplace,
 4879        window: &mut Window,
 4880        cx: &mut Context<Self>,
 4881    ) -> Option<Task<Result<()>>> {
 4882        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4883        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4884    }
 4885
 4886    pub fn compose_completion(
 4887        &mut self,
 4888        action: &ComposeCompletion,
 4889        window: &mut Window,
 4890        cx: &mut Context<Self>,
 4891    ) -> Option<Task<Result<()>>> {
 4892        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4893        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4894    }
 4895
 4896    fn do_completion(
 4897        &mut self,
 4898        item_ix: Option<usize>,
 4899        intent: CompletionIntent,
 4900        window: &mut Window,
 4901        cx: &mut Context<Editor>,
 4902    ) -> Option<Task<Result<()>>> {
 4903        use language::ToOffset as _;
 4904
 4905        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4906        else {
 4907            return None;
 4908        };
 4909
 4910        let candidate_id = {
 4911            let entries = completions_menu.entries.borrow();
 4912            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4913            if self.show_edit_predictions_in_menu() {
 4914                self.discard_inline_completion(true, cx);
 4915            }
 4916            mat.candidate_id
 4917        };
 4918
 4919        let buffer_handle = completions_menu.buffer;
 4920        let completion = completions_menu
 4921            .completions
 4922            .borrow()
 4923            .get(candidate_id)?
 4924            .clone();
 4925        cx.stop_propagation();
 4926
 4927        let snippet;
 4928        let new_text;
 4929        if completion.is_snippet() {
 4930            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4931            new_text = snippet.as_ref().unwrap().text.clone();
 4932        } else {
 4933            snippet = None;
 4934            new_text = completion.new_text.clone();
 4935        };
 4936
 4937        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4938        let buffer = buffer_handle.read(cx);
 4939        let snapshot = self.buffer.read(cx).snapshot(cx);
 4940        let replace_range_multibuffer = {
 4941            let excerpt = snapshot
 4942                .excerpt_containing(self.selections.newest_anchor().range())
 4943                .unwrap();
 4944            let multibuffer_anchor = snapshot
 4945                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4946                .unwrap()
 4947                ..snapshot
 4948                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4949                    .unwrap();
 4950            multibuffer_anchor.start.to_offset(&snapshot)
 4951                ..multibuffer_anchor.end.to_offset(&snapshot)
 4952        };
 4953        let newest_anchor = self.selections.newest_anchor();
 4954        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4955            return None;
 4956        }
 4957
 4958        let old_text = buffer
 4959            .text_for_range(replace_range.clone())
 4960            .collect::<String>();
 4961        let lookbehind = newest_anchor
 4962            .start
 4963            .text_anchor
 4964            .to_offset(buffer)
 4965            .saturating_sub(replace_range.start);
 4966        let lookahead = replace_range
 4967            .end
 4968            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4969        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4970        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4971
 4972        let selections = self.selections.all::<usize>(cx);
 4973        let mut ranges = Vec::new();
 4974        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4975
 4976        for selection in &selections {
 4977            let range = if selection.id == newest_anchor.id {
 4978                replace_range_multibuffer.clone()
 4979            } else {
 4980                let mut range = selection.range();
 4981
 4982                // if prefix is present, don't duplicate it
 4983                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4984                    range.start = range.start.saturating_sub(lookbehind);
 4985
 4986                    // if suffix is also present, mimic the newest cursor and replace it
 4987                    if selection.id != newest_anchor.id
 4988                        && snapshot.contains_str_at(range.end, suffix)
 4989                    {
 4990                        range.end += lookahead;
 4991                    }
 4992                }
 4993                range
 4994            };
 4995
 4996            ranges.push(range);
 4997
 4998            if !self.linked_edit_ranges.is_empty() {
 4999                let start_anchor = snapshot.anchor_before(selection.head());
 5000                let end_anchor = snapshot.anchor_after(selection.tail());
 5001                if let Some(ranges) = self
 5002                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5003                {
 5004                    for (buffer, edits) in ranges {
 5005                        linked_edits
 5006                            .entry(buffer.clone())
 5007                            .or_default()
 5008                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5009                    }
 5010                }
 5011            }
 5012        }
 5013
 5014        cx.emit(EditorEvent::InputHandled {
 5015            utf16_range_to_replace: None,
 5016            text: new_text.clone().into(),
 5017        });
 5018
 5019        self.transact(window, cx, |this, window, cx| {
 5020            if let Some(mut snippet) = snippet {
 5021                snippet.text = new_text.to_string();
 5022                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5023            } else {
 5024                this.buffer.update(cx, |buffer, cx| {
 5025                    let auto_indent = match completion.insert_text_mode {
 5026                        Some(InsertTextMode::AS_IS) => None,
 5027                        _ => this.autoindent_mode.clone(),
 5028                    };
 5029                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5030                    buffer.edit(edits, auto_indent, cx);
 5031                });
 5032            }
 5033            for (buffer, edits) in linked_edits {
 5034                buffer.update(cx, |buffer, cx| {
 5035                    let snapshot = buffer.snapshot();
 5036                    let edits = edits
 5037                        .into_iter()
 5038                        .map(|(range, text)| {
 5039                            use text::ToPoint as TP;
 5040                            let end_point = TP::to_point(&range.end, &snapshot);
 5041                            let start_point = TP::to_point(&range.start, &snapshot);
 5042                            (start_point..end_point, text)
 5043                        })
 5044                        .sorted_by_key(|(range, _)| range.start);
 5045                    buffer.edit(edits, None, cx);
 5046                })
 5047            }
 5048
 5049            this.refresh_inline_completion(true, false, window, cx);
 5050        });
 5051
 5052        let show_new_completions_on_confirm = completion
 5053            .confirm
 5054            .as_ref()
 5055            .map_or(false, |confirm| confirm(intent, window, cx));
 5056        if show_new_completions_on_confirm {
 5057            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5058        }
 5059
 5060        let provider = self.completion_provider.as_ref()?;
 5061        drop(completion);
 5062        let apply_edits = provider.apply_additional_edits_for_completion(
 5063            buffer_handle,
 5064            completions_menu.completions.clone(),
 5065            candidate_id,
 5066            true,
 5067            cx,
 5068        );
 5069
 5070        let editor_settings = EditorSettings::get_global(cx);
 5071        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5072            // After the code completion is finished, users often want to know what signatures are needed.
 5073            // so we should automatically call signature_help
 5074            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5075        }
 5076
 5077        Some(cx.foreground_executor().spawn(async move {
 5078            apply_edits.await?;
 5079            Ok(())
 5080        }))
 5081    }
 5082
 5083    pub fn toggle_code_actions(
 5084        &mut self,
 5085        action: &ToggleCodeActions,
 5086        window: &mut Window,
 5087        cx: &mut Context<Self>,
 5088    ) {
 5089        let mut context_menu = self.context_menu.borrow_mut();
 5090        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5091            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5092                // Toggle if we're selecting the same one
 5093                *context_menu = None;
 5094                cx.notify();
 5095                return;
 5096            } else {
 5097                // Otherwise, clear it and start a new one
 5098                *context_menu = None;
 5099                cx.notify();
 5100            }
 5101        }
 5102        drop(context_menu);
 5103        let snapshot = self.snapshot(window, cx);
 5104        let deployed_from_indicator = action.deployed_from_indicator;
 5105        let mut task = self.code_actions_task.take();
 5106        let action = action.clone();
 5107        cx.spawn_in(window, async move |editor, cx| {
 5108            while let Some(prev_task) = task {
 5109                prev_task.await.log_err();
 5110                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5111            }
 5112
 5113            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5114                if editor.focus_handle.is_focused(window) {
 5115                    let multibuffer_point = action
 5116                        .deployed_from_indicator
 5117                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5118                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5119                    let (buffer, buffer_row) = snapshot
 5120                        .buffer_snapshot
 5121                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5122                        .and_then(|(buffer_snapshot, range)| {
 5123                            editor
 5124                                .buffer
 5125                                .read(cx)
 5126                                .buffer(buffer_snapshot.remote_id())
 5127                                .map(|buffer| (buffer, range.start.row))
 5128                        })?;
 5129                    let (_, code_actions) = editor
 5130                        .available_code_actions
 5131                        .clone()
 5132                        .and_then(|(location, code_actions)| {
 5133                            let snapshot = location.buffer.read(cx).snapshot();
 5134                            let point_range = location.range.to_point(&snapshot);
 5135                            let point_range = point_range.start.row..=point_range.end.row;
 5136                            if point_range.contains(&buffer_row) {
 5137                                Some((location, code_actions))
 5138                            } else {
 5139                                None
 5140                            }
 5141                        })
 5142                        .unzip();
 5143                    let buffer_id = buffer.read(cx).remote_id();
 5144                    let tasks = editor
 5145                        .tasks
 5146                        .get(&(buffer_id, buffer_row))
 5147                        .map(|t| Arc::new(t.to_owned()));
 5148                    if tasks.is_none() && code_actions.is_none() {
 5149                        return None;
 5150                    }
 5151
 5152                    editor.completion_tasks.clear();
 5153                    editor.discard_inline_completion(false, cx);
 5154                    let task_context =
 5155                        tasks
 5156                            .as_ref()
 5157                            .zip(editor.project.clone())
 5158                            .map(|(tasks, project)| {
 5159                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5160                            });
 5161
 5162                    let debugger_flag = cx.has_flag::<Debugger>();
 5163
 5164                    Some(cx.spawn_in(window, async move |editor, cx| {
 5165                        let task_context = match task_context {
 5166                            Some(task_context) => task_context.await,
 5167                            None => None,
 5168                        };
 5169                        let resolved_tasks =
 5170                            tasks
 5171                                .zip(task_context)
 5172                                .map(|(tasks, task_context)| ResolvedTasks {
 5173                                    templates: tasks.resolve(&task_context).collect(),
 5174                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5175                                        multibuffer_point.row,
 5176                                        tasks.column,
 5177                                    )),
 5178                                });
 5179                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 5180                            tasks
 5181                                .templates
 5182                                .iter()
 5183                                .filter(|task| {
 5184                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 5185                                        debugger_flag
 5186                                    } else {
 5187                                        true
 5188                                    }
 5189                                })
 5190                                .count()
 5191                                == 1
 5192                        }) && code_actions
 5193                            .as_ref()
 5194                            .map_or(true, |actions| actions.is_empty());
 5195                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5196                            *editor.context_menu.borrow_mut() =
 5197                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5198                                    buffer,
 5199                                    actions: CodeActionContents::new(
 5200                                        resolved_tasks,
 5201                                        code_actions,
 5202                                        cx,
 5203                                    ),
 5204                                    selected_item: Default::default(),
 5205                                    scroll_handle: UniformListScrollHandle::default(),
 5206                                    deployed_from_indicator,
 5207                                }));
 5208                            if spawn_straight_away {
 5209                                if let Some(task) = editor.confirm_code_action(
 5210                                    &ConfirmCodeAction { item_ix: Some(0) },
 5211                                    window,
 5212                                    cx,
 5213                                ) {
 5214                                    cx.notify();
 5215                                    return task;
 5216                                }
 5217                            }
 5218                            cx.notify();
 5219                            Task::ready(Ok(()))
 5220                        }) {
 5221                            task.await
 5222                        } else {
 5223                            Ok(())
 5224                        }
 5225                    }))
 5226                } else {
 5227                    Some(Task::ready(Ok(())))
 5228                }
 5229            })?;
 5230            if let Some(task) = spawned_test_task {
 5231                task.await?;
 5232            }
 5233
 5234            Ok::<_, anyhow::Error>(())
 5235        })
 5236        .detach_and_log_err(cx);
 5237    }
 5238
 5239    pub fn confirm_code_action(
 5240        &mut self,
 5241        action: &ConfirmCodeAction,
 5242        window: &mut Window,
 5243        cx: &mut Context<Self>,
 5244    ) -> Option<Task<Result<()>>> {
 5245        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5246
 5247        let actions_menu =
 5248            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5249                menu
 5250            } else {
 5251                return None;
 5252            };
 5253
 5254        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5255        let action = actions_menu.actions.get(action_ix)?;
 5256        let title = action.label();
 5257        let buffer = actions_menu.buffer;
 5258        let workspace = self.workspace()?;
 5259
 5260        match action {
 5261            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5262                match resolved_task.task_type() {
 5263                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5264                        workspace.schedule_resolved_task(
 5265                            task_source_kind,
 5266                            resolved_task,
 5267                            false,
 5268                            window,
 5269                            cx,
 5270                        );
 5271
 5272                        Some(Task::ready(Ok(())))
 5273                    }),
 5274                    task::TaskType::Debug(_) => {
 5275                        workspace.update(cx, |workspace, cx| {
 5276                            workspace.schedule_debug_task(resolved_task, window, cx);
 5277                        });
 5278                        Some(Task::ready(Ok(())))
 5279                    }
 5280                }
 5281            }
 5282            CodeActionsItem::CodeAction {
 5283                excerpt_id,
 5284                action,
 5285                provider,
 5286            } => {
 5287                let apply_code_action =
 5288                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5289                let workspace = workspace.downgrade();
 5290                Some(cx.spawn_in(window, async move |editor, cx| {
 5291                    let project_transaction = apply_code_action.await?;
 5292                    Self::open_project_transaction(
 5293                        &editor,
 5294                        workspace,
 5295                        project_transaction,
 5296                        title,
 5297                        cx,
 5298                    )
 5299                    .await
 5300                }))
 5301            }
 5302        }
 5303    }
 5304
 5305    pub async fn open_project_transaction(
 5306        this: &WeakEntity<Editor>,
 5307        workspace: WeakEntity<Workspace>,
 5308        transaction: ProjectTransaction,
 5309        title: String,
 5310        cx: &mut AsyncWindowContext,
 5311    ) -> Result<()> {
 5312        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5313        cx.update(|_, cx| {
 5314            entries.sort_unstable_by_key(|(buffer, _)| {
 5315                buffer.read(cx).file().map(|f| f.path().clone())
 5316            });
 5317        })?;
 5318
 5319        // If the project transaction's edits are all contained within this editor, then
 5320        // avoid opening a new editor to display them.
 5321
 5322        if let Some((buffer, transaction)) = entries.first() {
 5323            if entries.len() == 1 {
 5324                let excerpt = this.update(cx, |editor, cx| {
 5325                    editor
 5326                        .buffer()
 5327                        .read(cx)
 5328                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5329                })?;
 5330                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5331                    if excerpted_buffer == *buffer {
 5332                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5333                            let excerpt_range = excerpt_range.to_offset(buffer);
 5334                            buffer
 5335                                .edited_ranges_for_transaction::<usize>(transaction)
 5336                                .all(|range| {
 5337                                    excerpt_range.start <= range.start
 5338                                        && excerpt_range.end >= range.end
 5339                                })
 5340                        })?;
 5341
 5342                        if all_edits_within_excerpt {
 5343                            return Ok(());
 5344                        }
 5345                    }
 5346                }
 5347            }
 5348        } else {
 5349            return Ok(());
 5350        }
 5351
 5352        let mut ranges_to_highlight = Vec::new();
 5353        let excerpt_buffer = cx.new(|cx| {
 5354            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5355            for (buffer_handle, transaction) in &entries {
 5356                let edited_ranges = buffer_handle
 5357                    .read(cx)
 5358                    .edited_ranges_for_transaction::<Point>(transaction)
 5359                    .collect::<Vec<_>>();
 5360                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5361                    PathKey::for_buffer(buffer_handle, cx),
 5362                    buffer_handle.clone(),
 5363                    edited_ranges,
 5364                    DEFAULT_MULTIBUFFER_CONTEXT,
 5365                    cx,
 5366                );
 5367
 5368                ranges_to_highlight.extend(ranges);
 5369            }
 5370            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5371            multibuffer
 5372        })?;
 5373
 5374        workspace.update_in(cx, |workspace, window, cx| {
 5375            let project = workspace.project().clone();
 5376            let editor =
 5377                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5378            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5379            editor.update(cx, |editor, cx| {
 5380                editor.highlight_background::<Self>(
 5381                    &ranges_to_highlight,
 5382                    |theme| theme.editor_highlighted_line_background,
 5383                    cx,
 5384                );
 5385            });
 5386        })?;
 5387
 5388        Ok(())
 5389    }
 5390
 5391    pub fn clear_code_action_providers(&mut self) {
 5392        self.code_action_providers.clear();
 5393        self.available_code_actions.take();
 5394    }
 5395
 5396    pub fn add_code_action_provider(
 5397        &mut self,
 5398        provider: Rc<dyn CodeActionProvider>,
 5399        window: &mut Window,
 5400        cx: &mut Context<Self>,
 5401    ) {
 5402        if self
 5403            .code_action_providers
 5404            .iter()
 5405            .any(|existing_provider| existing_provider.id() == provider.id())
 5406        {
 5407            return;
 5408        }
 5409
 5410        self.code_action_providers.push(provider);
 5411        self.refresh_code_actions(window, cx);
 5412    }
 5413
 5414    pub fn remove_code_action_provider(
 5415        &mut self,
 5416        id: Arc<str>,
 5417        window: &mut Window,
 5418        cx: &mut Context<Self>,
 5419    ) {
 5420        self.code_action_providers
 5421            .retain(|provider| provider.id() != id);
 5422        self.refresh_code_actions(window, cx);
 5423    }
 5424
 5425    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5426        let newest_selection = self.selections.newest_anchor().clone();
 5427        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5428        let buffer = self.buffer.read(cx);
 5429        if newest_selection.head().diff_base_anchor.is_some() {
 5430            return None;
 5431        }
 5432        let (start_buffer, start) =
 5433            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5434        let (end_buffer, end) =
 5435            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5436        if start_buffer != end_buffer {
 5437            return None;
 5438        }
 5439
 5440        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5441            cx.background_executor()
 5442                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5443                .await;
 5444
 5445            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5446                let providers = this.code_action_providers.clone();
 5447                let tasks = this
 5448                    .code_action_providers
 5449                    .iter()
 5450                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5451                    .collect::<Vec<_>>();
 5452                (providers, tasks)
 5453            })?;
 5454
 5455            let mut actions = Vec::new();
 5456            for (provider, provider_actions) in
 5457                providers.into_iter().zip(future::join_all(tasks).await)
 5458            {
 5459                if let Some(provider_actions) = provider_actions.log_err() {
 5460                    actions.extend(provider_actions.into_iter().map(|action| {
 5461                        AvailableCodeAction {
 5462                            excerpt_id: newest_selection.start.excerpt_id,
 5463                            action,
 5464                            provider: provider.clone(),
 5465                        }
 5466                    }));
 5467                }
 5468            }
 5469
 5470            this.update(cx, |this, cx| {
 5471                this.available_code_actions = if actions.is_empty() {
 5472                    None
 5473                } else {
 5474                    Some((
 5475                        Location {
 5476                            buffer: start_buffer,
 5477                            range: start..end,
 5478                        },
 5479                        actions.into(),
 5480                    ))
 5481                };
 5482                cx.notify();
 5483            })
 5484        }));
 5485        None
 5486    }
 5487
 5488    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5489        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5490            self.show_git_blame_inline = false;
 5491
 5492            self.show_git_blame_inline_delay_task =
 5493                Some(cx.spawn_in(window, async move |this, cx| {
 5494                    cx.background_executor().timer(delay).await;
 5495
 5496                    this.update(cx, |this, cx| {
 5497                        this.show_git_blame_inline = true;
 5498                        cx.notify();
 5499                    })
 5500                    .log_err();
 5501                }));
 5502        }
 5503    }
 5504
 5505    fn show_blame_popover(
 5506        &mut self,
 5507        blame_entry: &BlameEntry,
 5508        position: gpui::Point<Pixels>,
 5509        cx: &mut Context<Self>,
 5510    ) {
 5511        if let Some(state) = &mut self.inline_blame_popover {
 5512            state.hide_task.take();
 5513            cx.notify();
 5514        } else {
 5515            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5516            let show_task = cx.spawn(async move |editor, cx| {
 5517                cx.background_executor()
 5518                    .timer(std::time::Duration::from_millis(delay))
 5519                    .await;
 5520                editor
 5521                    .update(cx, |editor, cx| {
 5522                        if let Some(state) = &mut editor.inline_blame_popover {
 5523                            state.show_task = None;
 5524                            cx.notify();
 5525                        }
 5526                    })
 5527                    .ok();
 5528            });
 5529            let Some(blame) = self.blame.as_ref() else {
 5530                return;
 5531            };
 5532            let blame = blame.read(cx);
 5533            let details = blame.details_for_entry(&blame_entry);
 5534            let markdown = cx.new(|cx| {
 5535                Markdown::new(
 5536                    details
 5537                        .as_ref()
 5538                        .map(|message| message.message.clone())
 5539                        .unwrap_or_default(),
 5540                    None,
 5541                    None,
 5542                    cx,
 5543                )
 5544            });
 5545            self.inline_blame_popover = Some(InlineBlamePopover {
 5546                position,
 5547                show_task: Some(show_task),
 5548                hide_task: None,
 5549                popover_bounds: None,
 5550                popover_state: InlineBlamePopoverState {
 5551                    scroll_handle: ScrollHandle::new(),
 5552                    commit_message: details,
 5553                    markdown,
 5554                },
 5555            });
 5556        }
 5557    }
 5558
 5559    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5560        if let Some(state) = &mut self.inline_blame_popover {
 5561            if state.show_task.is_some() {
 5562                self.inline_blame_popover.take();
 5563                cx.notify();
 5564            } else {
 5565                let hide_task = cx.spawn(async move |editor, cx| {
 5566                    cx.background_executor()
 5567                        .timer(std::time::Duration::from_millis(100))
 5568                        .await;
 5569                    editor
 5570                        .update(cx, |editor, cx| {
 5571                            editor.inline_blame_popover.take();
 5572                            cx.notify();
 5573                        })
 5574                        .ok();
 5575                });
 5576                state.hide_task = Some(hide_task);
 5577            }
 5578        }
 5579    }
 5580
 5581    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5582        if self.pending_rename.is_some() {
 5583            return None;
 5584        }
 5585
 5586        let provider = self.semantics_provider.clone()?;
 5587        let buffer = self.buffer.read(cx);
 5588        let newest_selection = self.selections.newest_anchor().clone();
 5589        let cursor_position = newest_selection.head();
 5590        let (cursor_buffer, cursor_buffer_position) =
 5591            buffer.text_anchor_for_position(cursor_position, cx)?;
 5592        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5593        if cursor_buffer != tail_buffer {
 5594            return None;
 5595        }
 5596        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5597        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5598            cx.background_executor()
 5599                .timer(Duration::from_millis(debounce))
 5600                .await;
 5601
 5602            let highlights = if let Some(highlights) = cx
 5603                .update(|cx| {
 5604                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5605                })
 5606                .ok()
 5607                .flatten()
 5608            {
 5609                highlights.await.log_err()
 5610            } else {
 5611                None
 5612            };
 5613
 5614            if let Some(highlights) = highlights {
 5615                this.update(cx, |this, cx| {
 5616                    if this.pending_rename.is_some() {
 5617                        return;
 5618                    }
 5619
 5620                    let buffer_id = cursor_position.buffer_id;
 5621                    let buffer = this.buffer.read(cx);
 5622                    if !buffer
 5623                        .text_anchor_for_position(cursor_position, cx)
 5624                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5625                    {
 5626                        return;
 5627                    }
 5628
 5629                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5630                    let mut write_ranges = Vec::new();
 5631                    let mut read_ranges = Vec::new();
 5632                    for highlight in highlights {
 5633                        for (excerpt_id, excerpt_range) in
 5634                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5635                        {
 5636                            let start = highlight
 5637                                .range
 5638                                .start
 5639                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5640                            let end = highlight
 5641                                .range
 5642                                .end
 5643                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5644                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5645                                continue;
 5646                            }
 5647
 5648                            let range = Anchor {
 5649                                buffer_id,
 5650                                excerpt_id,
 5651                                text_anchor: start,
 5652                                diff_base_anchor: None,
 5653                            }..Anchor {
 5654                                buffer_id,
 5655                                excerpt_id,
 5656                                text_anchor: end,
 5657                                diff_base_anchor: None,
 5658                            };
 5659                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5660                                write_ranges.push(range);
 5661                            } else {
 5662                                read_ranges.push(range);
 5663                            }
 5664                        }
 5665                    }
 5666
 5667                    this.highlight_background::<DocumentHighlightRead>(
 5668                        &read_ranges,
 5669                        |theme| theme.editor_document_highlight_read_background,
 5670                        cx,
 5671                    );
 5672                    this.highlight_background::<DocumentHighlightWrite>(
 5673                        &write_ranges,
 5674                        |theme| theme.editor_document_highlight_write_background,
 5675                        cx,
 5676                    );
 5677                    cx.notify();
 5678                })
 5679                .log_err();
 5680            }
 5681        }));
 5682        None
 5683    }
 5684
 5685    fn prepare_highlight_query_from_selection(
 5686        &mut self,
 5687        cx: &mut Context<Editor>,
 5688    ) -> Option<(String, Range<Anchor>)> {
 5689        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5690            return None;
 5691        }
 5692        if !EditorSettings::get_global(cx).selection_highlight {
 5693            return None;
 5694        }
 5695        if self.selections.count() != 1 || self.selections.line_mode {
 5696            return None;
 5697        }
 5698        let selection = self.selections.newest::<Point>(cx);
 5699        if selection.is_empty() || selection.start.row != selection.end.row {
 5700            return None;
 5701        }
 5702        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5703        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5704        let query = multi_buffer_snapshot
 5705            .text_for_range(selection_anchor_range.clone())
 5706            .collect::<String>();
 5707        if query.trim().is_empty() {
 5708            return None;
 5709        }
 5710        Some((query, selection_anchor_range))
 5711    }
 5712
 5713    fn update_selection_occurrence_highlights(
 5714        &mut self,
 5715        query_text: String,
 5716        query_range: Range<Anchor>,
 5717        multi_buffer_range_to_query: Range<Point>,
 5718        use_debounce: bool,
 5719        window: &mut Window,
 5720        cx: &mut Context<Editor>,
 5721    ) -> Task<()> {
 5722        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5723        cx.spawn_in(window, async move |editor, cx| {
 5724            if use_debounce {
 5725                cx.background_executor()
 5726                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5727                    .await;
 5728            }
 5729            let match_task = cx.background_spawn(async move {
 5730                let buffer_ranges = multi_buffer_snapshot
 5731                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5732                    .into_iter()
 5733                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5734                let mut match_ranges = Vec::new();
 5735                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5736                    match_ranges.extend(
 5737                        project::search::SearchQuery::text(
 5738                            query_text.clone(),
 5739                            false,
 5740                            false,
 5741                            false,
 5742                            Default::default(),
 5743                            Default::default(),
 5744                            false,
 5745                            None,
 5746                        )
 5747                        .unwrap()
 5748                        .search(&buffer_snapshot, Some(search_range.clone()))
 5749                        .await
 5750                        .into_iter()
 5751                        .filter_map(|match_range| {
 5752                            let match_start = buffer_snapshot
 5753                                .anchor_after(search_range.start + match_range.start);
 5754                            let match_end =
 5755                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5756                            let match_anchor_range = Anchor::range_in_buffer(
 5757                                excerpt_id,
 5758                                buffer_snapshot.remote_id(),
 5759                                match_start..match_end,
 5760                            );
 5761                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5762                        }),
 5763                    );
 5764                }
 5765                match_ranges
 5766            });
 5767            let match_ranges = match_task.await;
 5768            editor
 5769                .update_in(cx, |editor, _, cx| {
 5770                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5771                    if !match_ranges.is_empty() {
 5772                        editor.highlight_background::<SelectedTextHighlight>(
 5773                            &match_ranges,
 5774                            |theme| theme.editor_document_highlight_bracket_background,
 5775                            cx,
 5776                        )
 5777                    }
 5778                })
 5779                .log_err();
 5780        })
 5781    }
 5782
 5783    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5784        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5785        else {
 5786            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5787            self.quick_selection_highlight_task.take();
 5788            self.debounced_selection_highlight_task.take();
 5789            return;
 5790        };
 5791        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5792        if self
 5793            .quick_selection_highlight_task
 5794            .as_ref()
 5795            .map_or(true, |(prev_anchor_range, _)| {
 5796                prev_anchor_range != &query_range
 5797            })
 5798        {
 5799            let multi_buffer_visible_start = self
 5800                .scroll_manager
 5801                .anchor()
 5802                .anchor
 5803                .to_point(&multi_buffer_snapshot);
 5804            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5805                multi_buffer_visible_start
 5806                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5807                Bias::Left,
 5808            );
 5809            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5810            self.quick_selection_highlight_task = Some((
 5811                query_range.clone(),
 5812                self.update_selection_occurrence_highlights(
 5813                    query_text.clone(),
 5814                    query_range.clone(),
 5815                    multi_buffer_visible_range,
 5816                    false,
 5817                    window,
 5818                    cx,
 5819                ),
 5820            ));
 5821        }
 5822        if self
 5823            .debounced_selection_highlight_task
 5824            .as_ref()
 5825            .map_or(true, |(prev_anchor_range, _)| {
 5826                prev_anchor_range != &query_range
 5827            })
 5828        {
 5829            let multi_buffer_start = multi_buffer_snapshot
 5830                .anchor_before(0)
 5831                .to_point(&multi_buffer_snapshot);
 5832            let multi_buffer_end = multi_buffer_snapshot
 5833                .anchor_after(multi_buffer_snapshot.len())
 5834                .to_point(&multi_buffer_snapshot);
 5835            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5836            self.debounced_selection_highlight_task = Some((
 5837                query_range.clone(),
 5838                self.update_selection_occurrence_highlights(
 5839                    query_text,
 5840                    query_range,
 5841                    multi_buffer_full_range,
 5842                    true,
 5843                    window,
 5844                    cx,
 5845                ),
 5846            ));
 5847        }
 5848    }
 5849
 5850    pub fn refresh_inline_completion(
 5851        &mut self,
 5852        debounce: bool,
 5853        user_requested: bool,
 5854        window: &mut Window,
 5855        cx: &mut Context<Self>,
 5856    ) -> Option<()> {
 5857        let provider = self.edit_prediction_provider()?;
 5858        let cursor = self.selections.newest_anchor().head();
 5859        let (buffer, cursor_buffer_position) =
 5860            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5861
 5862        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5863            self.discard_inline_completion(false, cx);
 5864            return None;
 5865        }
 5866
 5867        if !user_requested
 5868            && (!self.should_show_edit_predictions()
 5869                || !self.is_focused(window)
 5870                || buffer.read(cx).is_empty())
 5871        {
 5872            self.discard_inline_completion(false, cx);
 5873            return None;
 5874        }
 5875
 5876        self.update_visible_inline_completion(window, cx);
 5877        provider.refresh(
 5878            self.project.clone(),
 5879            buffer,
 5880            cursor_buffer_position,
 5881            debounce,
 5882            cx,
 5883        );
 5884        Some(())
 5885    }
 5886
 5887    fn show_edit_predictions_in_menu(&self) -> bool {
 5888        match self.edit_prediction_settings {
 5889            EditPredictionSettings::Disabled => false,
 5890            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5891        }
 5892    }
 5893
 5894    pub fn edit_predictions_enabled(&self) -> bool {
 5895        match self.edit_prediction_settings {
 5896            EditPredictionSettings::Disabled => false,
 5897            EditPredictionSettings::Enabled { .. } => true,
 5898        }
 5899    }
 5900
 5901    fn edit_prediction_requires_modifier(&self) -> bool {
 5902        match self.edit_prediction_settings {
 5903            EditPredictionSettings::Disabled => false,
 5904            EditPredictionSettings::Enabled {
 5905                preview_requires_modifier,
 5906                ..
 5907            } => preview_requires_modifier,
 5908        }
 5909    }
 5910
 5911    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5912        if self.edit_prediction_provider.is_none() {
 5913            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5914        } else {
 5915            let selection = self.selections.newest_anchor();
 5916            let cursor = selection.head();
 5917
 5918            if let Some((buffer, cursor_buffer_position)) =
 5919                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5920            {
 5921                self.edit_prediction_settings =
 5922                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5923            }
 5924        }
 5925    }
 5926
 5927    fn edit_prediction_settings_at_position(
 5928        &self,
 5929        buffer: &Entity<Buffer>,
 5930        buffer_position: language::Anchor,
 5931        cx: &App,
 5932    ) -> EditPredictionSettings {
 5933        if !self.mode.is_full()
 5934            || !self.show_inline_completions_override.unwrap_or(true)
 5935            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5936        {
 5937            return EditPredictionSettings::Disabled;
 5938        }
 5939
 5940        let buffer = buffer.read(cx);
 5941
 5942        let file = buffer.file();
 5943
 5944        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5945            return EditPredictionSettings::Disabled;
 5946        };
 5947
 5948        let by_provider = matches!(
 5949            self.menu_inline_completions_policy,
 5950            MenuInlineCompletionsPolicy::ByProvider
 5951        );
 5952
 5953        let show_in_menu = by_provider
 5954            && self
 5955                .edit_prediction_provider
 5956                .as_ref()
 5957                .map_or(false, |provider| {
 5958                    provider.provider.show_completions_in_menu()
 5959                });
 5960
 5961        let preview_requires_modifier =
 5962            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5963
 5964        EditPredictionSettings::Enabled {
 5965            show_in_menu,
 5966            preview_requires_modifier,
 5967        }
 5968    }
 5969
 5970    fn should_show_edit_predictions(&self) -> bool {
 5971        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5972    }
 5973
 5974    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5975        matches!(
 5976            self.edit_prediction_preview,
 5977            EditPredictionPreview::Active { .. }
 5978        )
 5979    }
 5980
 5981    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5982        let cursor = self.selections.newest_anchor().head();
 5983        if let Some((buffer, cursor_position)) =
 5984            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5985        {
 5986            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5987        } else {
 5988            false
 5989        }
 5990    }
 5991
 5992    fn edit_predictions_enabled_in_buffer(
 5993        &self,
 5994        buffer: &Entity<Buffer>,
 5995        buffer_position: language::Anchor,
 5996        cx: &App,
 5997    ) -> bool {
 5998        maybe!({
 5999            if self.read_only(cx) {
 6000                return Some(false);
 6001            }
 6002            let provider = self.edit_prediction_provider()?;
 6003            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6004                return Some(false);
 6005            }
 6006            let buffer = buffer.read(cx);
 6007            let Some(file) = buffer.file() else {
 6008                return Some(true);
 6009            };
 6010            let settings = all_language_settings(Some(file), cx);
 6011            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6012        })
 6013        .unwrap_or(false)
 6014    }
 6015
 6016    fn cycle_inline_completion(
 6017        &mut self,
 6018        direction: Direction,
 6019        window: &mut Window,
 6020        cx: &mut Context<Self>,
 6021    ) -> Option<()> {
 6022        let provider = self.edit_prediction_provider()?;
 6023        let cursor = self.selections.newest_anchor().head();
 6024        let (buffer, cursor_buffer_position) =
 6025            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6026        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6027            return None;
 6028        }
 6029
 6030        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6031        self.update_visible_inline_completion(window, cx);
 6032
 6033        Some(())
 6034    }
 6035
 6036    pub fn show_inline_completion(
 6037        &mut self,
 6038        _: &ShowEditPrediction,
 6039        window: &mut Window,
 6040        cx: &mut Context<Self>,
 6041    ) {
 6042        if !self.has_active_inline_completion() {
 6043            self.refresh_inline_completion(false, true, window, cx);
 6044            return;
 6045        }
 6046
 6047        self.update_visible_inline_completion(window, cx);
 6048    }
 6049
 6050    pub fn display_cursor_names(
 6051        &mut self,
 6052        _: &DisplayCursorNames,
 6053        window: &mut Window,
 6054        cx: &mut Context<Self>,
 6055    ) {
 6056        self.show_cursor_names(window, cx);
 6057    }
 6058
 6059    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6060        self.show_cursor_names = true;
 6061        cx.notify();
 6062        cx.spawn_in(window, async move |this, cx| {
 6063            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6064            this.update(cx, |this, cx| {
 6065                this.show_cursor_names = false;
 6066                cx.notify()
 6067            })
 6068            .ok()
 6069        })
 6070        .detach();
 6071    }
 6072
 6073    pub fn next_edit_prediction(
 6074        &mut self,
 6075        _: &NextEditPrediction,
 6076        window: &mut Window,
 6077        cx: &mut Context<Self>,
 6078    ) {
 6079        if self.has_active_inline_completion() {
 6080            self.cycle_inline_completion(Direction::Next, window, cx);
 6081        } else {
 6082            let is_copilot_disabled = self
 6083                .refresh_inline_completion(false, true, window, cx)
 6084                .is_none();
 6085            if is_copilot_disabled {
 6086                cx.propagate();
 6087            }
 6088        }
 6089    }
 6090
 6091    pub fn previous_edit_prediction(
 6092        &mut self,
 6093        _: &PreviousEditPrediction,
 6094        window: &mut Window,
 6095        cx: &mut Context<Self>,
 6096    ) {
 6097        if self.has_active_inline_completion() {
 6098            self.cycle_inline_completion(Direction::Prev, window, cx);
 6099        } else {
 6100            let is_copilot_disabled = self
 6101                .refresh_inline_completion(false, true, window, cx)
 6102                .is_none();
 6103            if is_copilot_disabled {
 6104                cx.propagate();
 6105            }
 6106        }
 6107    }
 6108
 6109    pub fn accept_edit_prediction(
 6110        &mut self,
 6111        _: &AcceptEditPrediction,
 6112        window: &mut Window,
 6113        cx: &mut Context<Self>,
 6114    ) {
 6115        if self.show_edit_predictions_in_menu() {
 6116            self.hide_context_menu(window, cx);
 6117        }
 6118
 6119        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6120            return;
 6121        };
 6122
 6123        self.report_inline_completion_event(
 6124            active_inline_completion.completion_id.clone(),
 6125            true,
 6126            cx,
 6127        );
 6128
 6129        match &active_inline_completion.completion {
 6130            InlineCompletion::Move { target, .. } => {
 6131                let target = *target;
 6132
 6133                if let Some(position_map) = &self.last_position_map {
 6134                    if position_map
 6135                        .visible_row_range
 6136                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6137                        || !self.edit_prediction_requires_modifier()
 6138                    {
 6139                        self.unfold_ranges(&[target..target], true, false, cx);
 6140                        // Note that this is also done in vim's handler of the Tab action.
 6141                        self.change_selections(
 6142                            Some(Autoscroll::newest()),
 6143                            window,
 6144                            cx,
 6145                            |selections| {
 6146                                selections.select_anchor_ranges([target..target]);
 6147                            },
 6148                        );
 6149                        self.clear_row_highlights::<EditPredictionPreview>();
 6150
 6151                        self.edit_prediction_preview
 6152                            .set_previous_scroll_position(None);
 6153                    } else {
 6154                        self.edit_prediction_preview
 6155                            .set_previous_scroll_position(Some(
 6156                                position_map.snapshot.scroll_anchor,
 6157                            ));
 6158
 6159                        self.highlight_rows::<EditPredictionPreview>(
 6160                            target..target,
 6161                            cx.theme().colors().editor_highlighted_line_background,
 6162                            RowHighlightOptions {
 6163                                autoscroll: true,
 6164                                ..Default::default()
 6165                            },
 6166                            cx,
 6167                        );
 6168                        self.request_autoscroll(Autoscroll::fit(), cx);
 6169                    }
 6170                }
 6171            }
 6172            InlineCompletion::Edit { edits, .. } => {
 6173                if let Some(provider) = self.edit_prediction_provider() {
 6174                    provider.accept(cx);
 6175                }
 6176
 6177                let snapshot = self.buffer.read(cx).snapshot(cx);
 6178                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6179
 6180                self.buffer.update(cx, |buffer, cx| {
 6181                    buffer.edit(edits.iter().cloned(), None, cx)
 6182                });
 6183
 6184                self.change_selections(None, window, cx, |s| {
 6185                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6186                });
 6187
 6188                self.update_visible_inline_completion(window, cx);
 6189                if self.active_inline_completion.is_none() {
 6190                    self.refresh_inline_completion(true, true, window, cx);
 6191                }
 6192
 6193                cx.notify();
 6194            }
 6195        }
 6196
 6197        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6198    }
 6199
 6200    pub fn accept_partial_inline_completion(
 6201        &mut self,
 6202        _: &AcceptPartialEditPrediction,
 6203        window: &mut Window,
 6204        cx: &mut Context<Self>,
 6205    ) {
 6206        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6207            return;
 6208        };
 6209        if self.selections.count() != 1 {
 6210            return;
 6211        }
 6212
 6213        self.report_inline_completion_event(
 6214            active_inline_completion.completion_id.clone(),
 6215            true,
 6216            cx,
 6217        );
 6218
 6219        match &active_inline_completion.completion {
 6220            InlineCompletion::Move { target, .. } => {
 6221                let target = *target;
 6222                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6223                    selections.select_anchor_ranges([target..target]);
 6224                });
 6225            }
 6226            InlineCompletion::Edit { edits, .. } => {
 6227                // Find an insertion that starts at the cursor position.
 6228                let snapshot = self.buffer.read(cx).snapshot(cx);
 6229                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6230                let insertion = edits.iter().find_map(|(range, text)| {
 6231                    let range = range.to_offset(&snapshot);
 6232                    if range.is_empty() && range.start == cursor_offset {
 6233                        Some(text)
 6234                    } else {
 6235                        None
 6236                    }
 6237                });
 6238
 6239                if let Some(text) = insertion {
 6240                    let mut partial_completion = text
 6241                        .chars()
 6242                        .by_ref()
 6243                        .take_while(|c| c.is_alphabetic())
 6244                        .collect::<String>();
 6245                    if partial_completion.is_empty() {
 6246                        partial_completion = text
 6247                            .chars()
 6248                            .by_ref()
 6249                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6250                            .collect::<String>();
 6251                    }
 6252
 6253                    cx.emit(EditorEvent::InputHandled {
 6254                        utf16_range_to_replace: None,
 6255                        text: partial_completion.clone().into(),
 6256                    });
 6257
 6258                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6259
 6260                    self.refresh_inline_completion(true, true, window, cx);
 6261                    cx.notify();
 6262                } else {
 6263                    self.accept_edit_prediction(&Default::default(), window, cx);
 6264                }
 6265            }
 6266        }
 6267    }
 6268
 6269    fn discard_inline_completion(
 6270        &mut self,
 6271        should_report_inline_completion_event: bool,
 6272        cx: &mut Context<Self>,
 6273    ) -> bool {
 6274        if should_report_inline_completion_event {
 6275            let completion_id = self
 6276                .active_inline_completion
 6277                .as_ref()
 6278                .and_then(|active_completion| active_completion.completion_id.clone());
 6279
 6280            self.report_inline_completion_event(completion_id, false, cx);
 6281        }
 6282
 6283        if let Some(provider) = self.edit_prediction_provider() {
 6284            provider.discard(cx);
 6285        }
 6286
 6287        self.take_active_inline_completion(cx)
 6288    }
 6289
 6290    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6291        let Some(provider) = self.edit_prediction_provider() else {
 6292            return;
 6293        };
 6294
 6295        let Some((_, buffer, _)) = self
 6296            .buffer
 6297            .read(cx)
 6298            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6299        else {
 6300            return;
 6301        };
 6302
 6303        let extension = buffer
 6304            .read(cx)
 6305            .file()
 6306            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6307
 6308        let event_type = match accepted {
 6309            true => "Edit Prediction Accepted",
 6310            false => "Edit Prediction Discarded",
 6311        };
 6312        telemetry::event!(
 6313            event_type,
 6314            provider = provider.name(),
 6315            prediction_id = id,
 6316            suggestion_accepted = accepted,
 6317            file_extension = extension,
 6318        );
 6319    }
 6320
 6321    pub fn has_active_inline_completion(&self) -> bool {
 6322        self.active_inline_completion.is_some()
 6323    }
 6324
 6325    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6326        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6327            return false;
 6328        };
 6329
 6330        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6331        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6332        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6333        true
 6334    }
 6335
 6336    /// Returns true when we're displaying the edit prediction popover below the cursor
 6337    /// like we are not previewing and the LSP autocomplete menu is visible
 6338    /// or we are in `when_holding_modifier` mode.
 6339    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6340        if self.edit_prediction_preview_is_active()
 6341            || !self.show_edit_predictions_in_menu()
 6342            || !self.edit_predictions_enabled()
 6343        {
 6344            return false;
 6345        }
 6346
 6347        if self.has_visible_completions_menu() {
 6348            return true;
 6349        }
 6350
 6351        has_completion && self.edit_prediction_requires_modifier()
 6352    }
 6353
 6354    fn handle_modifiers_changed(
 6355        &mut self,
 6356        modifiers: Modifiers,
 6357        position_map: &PositionMap,
 6358        window: &mut Window,
 6359        cx: &mut Context<Self>,
 6360    ) {
 6361        if self.show_edit_predictions_in_menu() {
 6362            self.update_edit_prediction_preview(&modifiers, window, cx);
 6363        }
 6364
 6365        self.update_selection_mode(&modifiers, position_map, window, cx);
 6366
 6367        let mouse_position = window.mouse_position();
 6368        if !position_map.text_hitbox.is_hovered(window) {
 6369            return;
 6370        }
 6371
 6372        self.update_hovered_link(
 6373            position_map.point_for_position(mouse_position),
 6374            &position_map.snapshot,
 6375            modifiers,
 6376            window,
 6377            cx,
 6378        )
 6379    }
 6380
 6381    fn update_selection_mode(
 6382        &mut self,
 6383        modifiers: &Modifiers,
 6384        position_map: &PositionMap,
 6385        window: &mut Window,
 6386        cx: &mut Context<Self>,
 6387    ) {
 6388        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6389            return;
 6390        }
 6391
 6392        let mouse_position = window.mouse_position();
 6393        let point_for_position = position_map.point_for_position(mouse_position);
 6394        let position = point_for_position.previous_valid;
 6395
 6396        self.select(
 6397            SelectPhase::BeginColumnar {
 6398                position,
 6399                reset: false,
 6400                goal_column: point_for_position.exact_unclipped.column(),
 6401            },
 6402            window,
 6403            cx,
 6404        );
 6405    }
 6406
 6407    fn update_edit_prediction_preview(
 6408        &mut self,
 6409        modifiers: &Modifiers,
 6410        window: &mut Window,
 6411        cx: &mut Context<Self>,
 6412    ) {
 6413        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6414        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6415            return;
 6416        };
 6417
 6418        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6419            if matches!(
 6420                self.edit_prediction_preview,
 6421                EditPredictionPreview::Inactive { .. }
 6422            ) {
 6423                self.edit_prediction_preview = EditPredictionPreview::Active {
 6424                    previous_scroll_position: None,
 6425                    since: Instant::now(),
 6426                };
 6427
 6428                self.update_visible_inline_completion(window, cx);
 6429                cx.notify();
 6430            }
 6431        } else if let EditPredictionPreview::Active {
 6432            previous_scroll_position,
 6433            since,
 6434        } = self.edit_prediction_preview
 6435        {
 6436            if let (Some(previous_scroll_position), Some(position_map)) =
 6437                (previous_scroll_position, self.last_position_map.as_ref())
 6438            {
 6439                self.set_scroll_position(
 6440                    previous_scroll_position
 6441                        .scroll_position(&position_map.snapshot.display_snapshot),
 6442                    window,
 6443                    cx,
 6444                );
 6445            }
 6446
 6447            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6448                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6449            };
 6450            self.clear_row_highlights::<EditPredictionPreview>();
 6451            self.update_visible_inline_completion(window, cx);
 6452            cx.notify();
 6453        }
 6454    }
 6455
 6456    fn update_visible_inline_completion(
 6457        &mut self,
 6458        _window: &mut Window,
 6459        cx: &mut Context<Self>,
 6460    ) -> Option<()> {
 6461        let selection = self.selections.newest_anchor();
 6462        let cursor = selection.head();
 6463        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6464        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6465        let excerpt_id = cursor.excerpt_id;
 6466
 6467        let show_in_menu = self.show_edit_predictions_in_menu();
 6468        let completions_menu_has_precedence = !show_in_menu
 6469            && (self.context_menu.borrow().is_some()
 6470                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6471
 6472        if completions_menu_has_precedence
 6473            || !offset_selection.is_empty()
 6474            || self
 6475                .active_inline_completion
 6476                .as_ref()
 6477                .map_or(false, |completion| {
 6478                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6479                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6480                    !invalidation_range.contains(&offset_selection.head())
 6481                })
 6482        {
 6483            self.discard_inline_completion(false, cx);
 6484            return None;
 6485        }
 6486
 6487        self.take_active_inline_completion(cx);
 6488        let Some(provider) = self.edit_prediction_provider() else {
 6489            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6490            return None;
 6491        };
 6492
 6493        let (buffer, cursor_buffer_position) =
 6494            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6495
 6496        self.edit_prediction_settings =
 6497            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6498
 6499        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6500
 6501        if self.edit_prediction_indent_conflict {
 6502            let cursor_point = cursor.to_point(&multibuffer);
 6503
 6504            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6505
 6506            if let Some((_, indent)) = indents.iter().next() {
 6507                if indent.len == cursor_point.column {
 6508                    self.edit_prediction_indent_conflict = false;
 6509                }
 6510            }
 6511        }
 6512
 6513        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6514        let edits = inline_completion
 6515            .edits
 6516            .into_iter()
 6517            .flat_map(|(range, new_text)| {
 6518                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6519                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6520                Some((start..end, new_text))
 6521            })
 6522            .collect::<Vec<_>>();
 6523        if edits.is_empty() {
 6524            return None;
 6525        }
 6526
 6527        let first_edit_start = edits.first().unwrap().0.start;
 6528        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6529        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6530
 6531        let last_edit_end = edits.last().unwrap().0.end;
 6532        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6533        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6534
 6535        let cursor_row = cursor.to_point(&multibuffer).row;
 6536
 6537        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6538
 6539        let mut inlay_ids = Vec::new();
 6540        let invalidation_row_range;
 6541        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6542            Some(cursor_row..edit_end_row)
 6543        } else if cursor_row > edit_end_row {
 6544            Some(edit_start_row..cursor_row)
 6545        } else {
 6546            None
 6547        };
 6548        let is_move =
 6549            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6550        let completion = if is_move {
 6551            invalidation_row_range =
 6552                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6553            let target = first_edit_start;
 6554            InlineCompletion::Move { target, snapshot }
 6555        } else {
 6556            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6557                && !self.inline_completions_hidden_for_vim_mode;
 6558
 6559            if show_completions_in_buffer {
 6560                if edits
 6561                    .iter()
 6562                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6563                {
 6564                    let mut inlays = Vec::new();
 6565                    for (range, new_text) in &edits {
 6566                        let inlay = Inlay::inline_completion(
 6567                            post_inc(&mut self.next_inlay_id),
 6568                            range.start,
 6569                            new_text.as_str(),
 6570                        );
 6571                        inlay_ids.push(inlay.id);
 6572                        inlays.push(inlay);
 6573                    }
 6574
 6575                    self.splice_inlays(&[], inlays, cx);
 6576                } else {
 6577                    let background_color = cx.theme().status().deleted_background;
 6578                    self.highlight_text::<InlineCompletionHighlight>(
 6579                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6580                        HighlightStyle {
 6581                            background_color: Some(background_color),
 6582                            ..Default::default()
 6583                        },
 6584                        cx,
 6585                    );
 6586                }
 6587            }
 6588
 6589            invalidation_row_range = edit_start_row..edit_end_row;
 6590
 6591            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6592                if provider.show_tab_accept_marker() {
 6593                    EditDisplayMode::TabAccept
 6594                } else {
 6595                    EditDisplayMode::Inline
 6596                }
 6597            } else {
 6598                EditDisplayMode::DiffPopover
 6599            };
 6600
 6601            InlineCompletion::Edit {
 6602                edits,
 6603                edit_preview: inline_completion.edit_preview,
 6604                display_mode,
 6605                snapshot,
 6606            }
 6607        };
 6608
 6609        let invalidation_range = multibuffer
 6610            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6611            ..multibuffer.anchor_after(Point::new(
 6612                invalidation_row_range.end,
 6613                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6614            ));
 6615
 6616        self.stale_inline_completion_in_menu = None;
 6617        self.active_inline_completion = Some(InlineCompletionState {
 6618            inlay_ids,
 6619            completion,
 6620            completion_id: inline_completion.id,
 6621            invalidation_range,
 6622        });
 6623
 6624        cx.notify();
 6625
 6626        Some(())
 6627    }
 6628
 6629    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6630        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6631    }
 6632
 6633    fn render_code_actions_indicator(
 6634        &self,
 6635        _style: &EditorStyle,
 6636        row: DisplayRow,
 6637        is_active: bool,
 6638        breakpoint: Option<&(Anchor, Breakpoint)>,
 6639        cx: &mut Context<Self>,
 6640    ) -> Option<IconButton> {
 6641        let color = Color::Muted;
 6642        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6643        let show_tooltip = !self.context_menu_visible();
 6644
 6645        if self.available_code_actions.is_some() {
 6646            Some(
 6647                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6648                    .shape(ui::IconButtonShape::Square)
 6649                    .icon_size(IconSize::XSmall)
 6650                    .icon_color(color)
 6651                    .toggle_state(is_active)
 6652                    .when(show_tooltip, |this| {
 6653                        this.tooltip({
 6654                            let focus_handle = self.focus_handle.clone();
 6655                            move |window, cx| {
 6656                                Tooltip::for_action_in(
 6657                                    "Toggle Code Actions",
 6658                                    &ToggleCodeActions {
 6659                                        deployed_from_indicator: None,
 6660                                    },
 6661                                    &focus_handle,
 6662                                    window,
 6663                                    cx,
 6664                                )
 6665                            }
 6666                        })
 6667                    })
 6668                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6669                        window.focus(&editor.focus_handle(cx));
 6670                        editor.toggle_code_actions(
 6671                            &ToggleCodeActions {
 6672                                deployed_from_indicator: Some(row),
 6673                            },
 6674                            window,
 6675                            cx,
 6676                        );
 6677                    }))
 6678                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6679                        editor.set_breakpoint_context_menu(
 6680                            row,
 6681                            position,
 6682                            event.down.position,
 6683                            window,
 6684                            cx,
 6685                        );
 6686                    })),
 6687            )
 6688        } else {
 6689            None
 6690        }
 6691    }
 6692
 6693    fn clear_tasks(&mut self) {
 6694        self.tasks.clear()
 6695    }
 6696
 6697    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6698        if self.tasks.insert(key, value).is_some() {
 6699            // This case should hopefully be rare, but just in case...
 6700            log::error!(
 6701                "multiple different run targets found on a single line, only the last target will be rendered"
 6702            )
 6703        }
 6704    }
 6705
 6706    /// Get all display points of breakpoints that will be rendered within editor
 6707    ///
 6708    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6709    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6710    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6711    fn active_breakpoints(
 6712        &self,
 6713        range: Range<DisplayRow>,
 6714        window: &mut Window,
 6715        cx: &mut Context<Self>,
 6716    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6717        let mut breakpoint_display_points = HashMap::default();
 6718
 6719        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6720            return breakpoint_display_points;
 6721        };
 6722
 6723        let snapshot = self.snapshot(window, cx);
 6724
 6725        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6726        let Some(project) = self.project.as_ref() else {
 6727            return breakpoint_display_points;
 6728        };
 6729
 6730        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6731            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6732
 6733        for (buffer_snapshot, range, excerpt_id) in
 6734            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6735        {
 6736            let Some(buffer) = project.read_with(cx, |this, cx| {
 6737                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6738            }) else {
 6739                continue;
 6740            };
 6741            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6742                &buffer,
 6743                Some(
 6744                    buffer_snapshot.anchor_before(range.start)
 6745                        ..buffer_snapshot.anchor_after(range.end),
 6746                ),
 6747                buffer_snapshot,
 6748                cx,
 6749            );
 6750            for (anchor, breakpoint) in breakpoints {
 6751                let multi_buffer_anchor =
 6752                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6753                let position = multi_buffer_anchor
 6754                    .to_point(&multi_buffer_snapshot)
 6755                    .to_display_point(&snapshot);
 6756
 6757                breakpoint_display_points
 6758                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6759            }
 6760        }
 6761
 6762        breakpoint_display_points
 6763    }
 6764
 6765    fn breakpoint_context_menu(
 6766        &self,
 6767        anchor: Anchor,
 6768        window: &mut Window,
 6769        cx: &mut Context<Self>,
 6770    ) -> Entity<ui::ContextMenu> {
 6771        let weak_editor = cx.weak_entity();
 6772        let focus_handle = self.focus_handle(cx);
 6773
 6774        let row = self
 6775            .buffer
 6776            .read(cx)
 6777            .snapshot(cx)
 6778            .summary_for_anchor::<Point>(&anchor)
 6779            .row;
 6780
 6781        let breakpoint = self
 6782            .breakpoint_at_row(row, window, cx)
 6783            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6784
 6785        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6786            "Edit Log Breakpoint"
 6787        } else {
 6788            "Set Log Breakpoint"
 6789        };
 6790
 6791        let condition_breakpoint_msg = if breakpoint
 6792            .as_ref()
 6793            .is_some_and(|bp| bp.1.condition.is_some())
 6794        {
 6795            "Edit Condition Breakpoint"
 6796        } else {
 6797            "Set Condition Breakpoint"
 6798        };
 6799
 6800        let hit_condition_breakpoint_msg = if breakpoint
 6801            .as_ref()
 6802            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6803        {
 6804            "Edit Hit Condition Breakpoint"
 6805        } else {
 6806            "Set Hit Condition Breakpoint"
 6807        };
 6808
 6809        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6810            "Unset Breakpoint"
 6811        } else {
 6812            "Set Breakpoint"
 6813        };
 6814
 6815        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6816            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6817
 6818        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6819            BreakpointState::Enabled => Some("Disable"),
 6820            BreakpointState::Disabled => Some("Enable"),
 6821        });
 6822
 6823        let (anchor, breakpoint) =
 6824            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6825
 6826        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6827            menu.on_blur_subscription(Subscription::new(|| {}))
 6828                .context(focus_handle)
 6829                .when(run_to_cursor, |this| {
 6830                    let weak_editor = weak_editor.clone();
 6831                    this.entry("Run to cursor", None, move |window, cx| {
 6832                        weak_editor
 6833                            .update(cx, |editor, cx| {
 6834                                editor.change_selections(None, window, cx, |s| {
 6835                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6836                                });
 6837                            })
 6838                            .ok();
 6839
 6840                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6841                    })
 6842                    .separator()
 6843                })
 6844                .when_some(toggle_state_msg, |this, msg| {
 6845                    this.entry(msg, None, {
 6846                        let weak_editor = weak_editor.clone();
 6847                        let breakpoint = breakpoint.clone();
 6848                        move |_window, cx| {
 6849                            weak_editor
 6850                                .update(cx, |this, cx| {
 6851                                    this.edit_breakpoint_at_anchor(
 6852                                        anchor,
 6853                                        breakpoint.as_ref().clone(),
 6854                                        BreakpointEditAction::InvertState,
 6855                                        cx,
 6856                                    );
 6857                                })
 6858                                .log_err();
 6859                        }
 6860                    })
 6861                })
 6862                .entry(set_breakpoint_msg, None, {
 6863                    let weak_editor = weak_editor.clone();
 6864                    let breakpoint = breakpoint.clone();
 6865                    move |_window, cx| {
 6866                        weak_editor
 6867                            .update(cx, |this, cx| {
 6868                                this.edit_breakpoint_at_anchor(
 6869                                    anchor,
 6870                                    breakpoint.as_ref().clone(),
 6871                                    BreakpointEditAction::Toggle,
 6872                                    cx,
 6873                                );
 6874                            })
 6875                            .log_err();
 6876                    }
 6877                })
 6878                .entry(log_breakpoint_msg, None, {
 6879                    let breakpoint = breakpoint.clone();
 6880                    let weak_editor = weak_editor.clone();
 6881                    move |window, cx| {
 6882                        weak_editor
 6883                            .update(cx, |this, cx| {
 6884                                this.add_edit_breakpoint_block(
 6885                                    anchor,
 6886                                    breakpoint.as_ref(),
 6887                                    BreakpointPromptEditAction::Log,
 6888                                    window,
 6889                                    cx,
 6890                                );
 6891                            })
 6892                            .log_err();
 6893                    }
 6894                })
 6895                .entry(condition_breakpoint_msg, None, {
 6896                    let breakpoint = breakpoint.clone();
 6897                    let weak_editor = weak_editor.clone();
 6898                    move |window, cx| {
 6899                        weak_editor
 6900                            .update(cx, |this, cx| {
 6901                                this.add_edit_breakpoint_block(
 6902                                    anchor,
 6903                                    breakpoint.as_ref(),
 6904                                    BreakpointPromptEditAction::Condition,
 6905                                    window,
 6906                                    cx,
 6907                                );
 6908                            })
 6909                            .log_err();
 6910                    }
 6911                })
 6912                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6913                    weak_editor
 6914                        .update(cx, |this, cx| {
 6915                            this.add_edit_breakpoint_block(
 6916                                anchor,
 6917                                breakpoint.as_ref(),
 6918                                BreakpointPromptEditAction::HitCondition,
 6919                                window,
 6920                                cx,
 6921                            );
 6922                        })
 6923                        .log_err();
 6924                })
 6925        })
 6926    }
 6927
 6928    fn render_breakpoint(
 6929        &self,
 6930        position: Anchor,
 6931        row: DisplayRow,
 6932        breakpoint: &Breakpoint,
 6933        cx: &mut Context<Self>,
 6934    ) -> IconButton {
 6935        let (color, icon) = {
 6936            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6937                (false, false) => ui::IconName::DebugBreakpoint,
 6938                (true, false) => ui::IconName::DebugLogBreakpoint,
 6939                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6940                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6941            };
 6942
 6943            let color = if self
 6944                .gutter_breakpoint_indicator
 6945                .0
 6946                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6947            {
 6948                Color::Hint
 6949            } else {
 6950                Color::Debugger
 6951            };
 6952
 6953            (color, icon)
 6954        };
 6955
 6956        let breakpoint = Arc::from(breakpoint.clone());
 6957
 6958        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6959            .icon_size(IconSize::XSmall)
 6960            .size(ui::ButtonSize::None)
 6961            .icon_color(color)
 6962            .style(ButtonStyle::Transparent)
 6963            .on_click(cx.listener({
 6964                let breakpoint = breakpoint.clone();
 6965
 6966                move |editor, event: &ClickEvent, window, cx| {
 6967                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6968                        BreakpointEditAction::InvertState
 6969                    } else {
 6970                        BreakpointEditAction::Toggle
 6971                    };
 6972
 6973                    window.focus(&editor.focus_handle(cx));
 6974                    editor.edit_breakpoint_at_anchor(
 6975                        position,
 6976                        breakpoint.as_ref().clone(),
 6977                        edit_action,
 6978                        cx,
 6979                    );
 6980                }
 6981            }))
 6982            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6983                editor.set_breakpoint_context_menu(
 6984                    row,
 6985                    Some(position),
 6986                    event.down.position,
 6987                    window,
 6988                    cx,
 6989                );
 6990            }))
 6991    }
 6992
 6993    fn build_tasks_context(
 6994        project: &Entity<Project>,
 6995        buffer: &Entity<Buffer>,
 6996        buffer_row: u32,
 6997        tasks: &Arc<RunnableTasks>,
 6998        cx: &mut Context<Self>,
 6999    ) -> Task<Option<task::TaskContext>> {
 7000        let position = Point::new(buffer_row, tasks.column);
 7001        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7002        let location = Location {
 7003            buffer: buffer.clone(),
 7004            range: range_start..range_start,
 7005        };
 7006        // Fill in the environmental variables from the tree-sitter captures
 7007        let mut captured_task_variables = TaskVariables::default();
 7008        for (capture_name, value) in tasks.extra_variables.clone() {
 7009            captured_task_variables.insert(
 7010                task::VariableName::Custom(capture_name.into()),
 7011                value.clone(),
 7012            );
 7013        }
 7014        project.update(cx, |project, cx| {
 7015            project.task_store().update(cx, |task_store, cx| {
 7016                task_store.task_context_for_location(captured_task_variables, location, cx)
 7017            })
 7018        })
 7019    }
 7020
 7021    pub fn spawn_nearest_task(
 7022        &mut self,
 7023        action: &SpawnNearestTask,
 7024        window: &mut Window,
 7025        cx: &mut Context<Self>,
 7026    ) {
 7027        let Some((workspace, _)) = self.workspace.clone() else {
 7028            return;
 7029        };
 7030        let Some(project) = self.project.clone() else {
 7031            return;
 7032        };
 7033
 7034        // Try to find a closest, enclosing node using tree-sitter that has a
 7035        // task
 7036        let Some((buffer, buffer_row, tasks)) = self
 7037            .find_enclosing_node_task(cx)
 7038            // Or find the task that's closest in row-distance.
 7039            .or_else(|| self.find_closest_task(cx))
 7040        else {
 7041            return;
 7042        };
 7043
 7044        let reveal_strategy = action.reveal;
 7045        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7046        cx.spawn_in(window, async move |_, cx| {
 7047            let context = task_context.await?;
 7048            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7049
 7050            let resolved = resolved_task.resolved.as_mut()?;
 7051            resolved.reveal = reveal_strategy;
 7052
 7053            workspace
 7054                .update_in(cx, |workspace, window, cx| {
 7055                    workspace.schedule_resolved_task(
 7056                        task_source_kind,
 7057                        resolved_task,
 7058                        false,
 7059                        window,
 7060                        cx,
 7061                    );
 7062                })
 7063                .ok()
 7064        })
 7065        .detach();
 7066    }
 7067
 7068    fn find_closest_task(
 7069        &mut self,
 7070        cx: &mut Context<Self>,
 7071    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7072        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7073
 7074        let ((buffer_id, row), tasks) = self
 7075            .tasks
 7076            .iter()
 7077            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7078
 7079        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7080        let tasks = Arc::new(tasks.to_owned());
 7081        Some((buffer, *row, tasks))
 7082    }
 7083
 7084    fn find_enclosing_node_task(
 7085        &mut self,
 7086        cx: &mut Context<Self>,
 7087    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7088        let snapshot = self.buffer.read(cx).snapshot(cx);
 7089        let offset = self.selections.newest::<usize>(cx).head();
 7090        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7091        let buffer_id = excerpt.buffer().remote_id();
 7092
 7093        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7094        let mut cursor = layer.node().walk();
 7095
 7096        while cursor.goto_first_child_for_byte(offset).is_some() {
 7097            if cursor.node().end_byte() == offset {
 7098                cursor.goto_next_sibling();
 7099            }
 7100        }
 7101
 7102        // Ascend to the smallest ancestor that contains the range and has a task.
 7103        loop {
 7104            let node = cursor.node();
 7105            let node_range = node.byte_range();
 7106            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7107
 7108            // Check if this node contains our offset
 7109            if node_range.start <= offset && node_range.end >= offset {
 7110                // If it contains offset, check for task
 7111                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7112                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7113                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7114                }
 7115            }
 7116
 7117            if !cursor.goto_parent() {
 7118                break;
 7119            }
 7120        }
 7121        None
 7122    }
 7123
 7124    fn render_run_indicator(
 7125        &self,
 7126        _style: &EditorStyle,
 7127        is_active: bool,
 7128        row: DisplayRow,
 7129        breakpoint: Option<(Anchor, Breakpoint)>,
 7130        cx: &mut Context<Self>,
 7131    ) -> IconButton {
 7132        let color = Color::Muted;
 7133        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7134
 7135        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7136            .shape(ui::IconButtonShape::Square)
 7137            .icon_size(IconSize::XSmall)
 7138            .icon_color(color)
 7139            .toggle_state(is_active)
 7140            .on_click(cx.listener(move |editor, _e, window, cx| {
 7141                window.focus(&editor.focus_handle(cx));
 7142                editor.toggle_code_actions(
 7143                    &ToggleCodeActions {
 7144                        deployed_from_indicator: Some(row),
 7145                    },
 7146                    window,
 7147                    cx,
 7148                );
 7149            }))
 7150            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7151                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7152            }))
 7153    }
 7154
 7155    pub fn context_menu_visible(&self) -> bool {
 7156        !self.edit_prediction_preview_is_active()
 7157            && self
 7158                .context_menu
 7159                .borrow()
 7160                .as_ref()
 7161                .map_or(false, |menu| menu.visible())
 7162    }
 7163
 7164    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7165        self.context_menu
 7166            .borrow()
 7167            .as_ref()
 7168            .map(|menu| menu.origin())
 7169    }
 7170
 7171    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7172        self.context_menu_options = Some(options);
 7173    }
 7174
 7175    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7176    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7177
 7178    fn render_edit_prediction_popover(
 7179        &mut self,
 7180        text_bounds: &Bounds<Pixels>,
 7181        content_origin: gpui::Point<Pixels>,
 7182        editor_snapshot: &EditorSnapshot,
 7183        visible_row_range: Range<DisplayRow>,
 7184        scroll_top: f32,
 7185        scroll_bottom: f32,
 7186        line_layouts: &[LineWithInvisibles],
 7187        line_height: Pixels,
 7188        scroll_pixel_position: gpui::Point<Pixels>,
 7189        newest_selection_head: Option<DisplayPoint>,
 7190        editor_width: Pixels,
 7191        style: &EditorStyle,
 7192        window: &mut Window,
 7193        cx: &mut App,
 7194    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7195        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7196
 7197        if self.edit_prediction_visible_in_cursor_popover(true) {
 7198            return None;
 7199        }
 7200
 7201        match &active_inline_completion.completion {
 7202            InlineCompletion::Move { target, .. } => {
 7203                let target_display_point = target.to_display_point(editor_snapshot);
 7204
 7205                if self.edit_prediction_requires_modifier() {
 7206                    if !self.edit_prediction_preview_is_active() {
 7207                        return None;
 7208                    }
 7209
 7210                    self.render_edit_prediction_modifier_jump_popover(
 7211                        text_bounds,
 7212                        content_origin,
 7213                        visible_row_range,
 7214                        line_layouts,
 7215                        line_height,
 7216                        scroll_pixel_position,
 7217                        newest_selection_head,
 7218                        target_display_point,
 7219                        window,
 7220                        cx,
 7221                    )
 7222                } else {
 7223                    self.render_edit_prediction_eager_jump_popover(
 7224                        text_bounds,
 7225                        content_origin,
 7226                        editor_snapshot,
 7227                        visible_row_range,
 7228                        scroll_top,
 7229                        scroll_bottom,
 7230                        line_height,
 7231                        scroll_pixel_position,
 7232                        target_display_point,
 7233                        editor_width,
 7234                        window,
 7235                        cx,
 7236                    )
 7237                }
 7238            }
 7239            InlineCompletion::Edit {
 7240                display_mode: EditDisplayMode::Inline,
 7241                ..
 7242            } => None,
 7243            InlineCompletion::Edit {
 7244                display_mode: EditDisplayMode::TabAccept,
 7245                edits,
 7246                ..
 7247            } => {
 7248                let range = &edits.first()?.0;
 7249                let target_display_point = range.end.to_display_point(editor_snapshot);
 7250
 7251                self.render_edit_prediction_end_of_line_popover(
 7252                    "Accept",
 7253                    editor_snapshot,
 7254                    visible_row_range,
 7255                    target_display_point,
 7256                    line_height,
 7257                    scroll_pixel_position,
 7258                    content_origin,
 7259                    editor_width,
 7260                    window,
 7261                    cx,
 7262                )
 7263            }
 7264            InlineCompletion::Edit {
 7265                edits,
 7266                edit_preview,
 7267                display_mode: EditDisplayMode::DiffPopover,
 7268                snapshot,
 7269            } => self.render_edit_prediction_diff_popover(
 7270                text_bounds,
 7271                content_origin,
 7272                editor_snapshot,
 7273                visible_row_range,
 7274                line_layouts,
 7275                line_height,
 7276                scroll_pixel_position,
 7277                newest_selection_head,
 7278                editor_width,
 7279                style,
 7280                edits,
 7281                edit_preview,
 7282                snapshot,
 7283                window,
 7284                cx,
 7285            ),
 7286        }
 7287    }
 7288
 7289    fn render_edit_prediction_modifier_jump_popover(
 7290        &mut self,
 7291        text_bounds: &Bounds<Pixels>,
 7292        content_origin: gpui::Point<Pixels>,
 7293        visible_row_range: Range<DisplayRow>,
 7294        line_layouts: &[LineWithInvisibles],
 7295        line_height: Pixels,
 7296        scroll_pixel_position: gpui::Point<Pixels>,
 7297        newest_selection_head: Option<DisplayPoint>,
 7298        target_display_point: DisplayPoint,
 7299        window: &mut Window,
 7300        cx: &mut App,
 7301    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7302        let scrolled_content_origin =
 7303            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7304
 7305        const SCROLL_PADDING_Y: Pixels = px(12.);
 7306
 7307        if target_display_point.row() < visible_row_range.start {
 7308            return self.render_edit_prediction_scroll_popover(
 7309                |_| SCROLL_PADDING_Y,
 7310                IconName::ArrowUp,
 7311                visible_row_range,
 7312                line_layouts,
 7313                newest_selection_head,
 7314                scrolled_content_origin,
 7315                window,
 7316                cx,
 7317            );
 7318        } else if target_display_point.row() >= visible_row_range.end {
 7319            return self.render_edit_prediction_scroll_popover(
 7320                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7321                IconName::ArrowDown,
 7322                visible_row_range,
 7323                line_layouts,
 7324                newest_selection_head,
 7325                scrolled_content_origin,
 7326                window,
 7327                cx,
 7328            );
 7329        }
 7330
 7331        const POLE_WIDTH: Pixels = px(2.);
 7332
 7333        let line_layout =
 7334            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7335        let target_column = target_display_point.column() as usize;
 7336
 7337        let target_x = line_layout.x_for_index(target_column);
 7338        let target_y =
 7339            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7340
 7341        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7342
 7343        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7344        border_color.l += 0.001;
 7345
 7346        let mut element = v_flex()
 7347            .items_end()
 7348            .when(flag_on_right, |el| el.items_start())
 7349            .child(if flag_on_right {
 7350                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7351                    .rounded_bl(px(0.))
 7352                    .rounded_tl(px(0.))
 7353                    .border_l_2()
 7354                    .border_color(border_color)
 7355            } else {
 7356                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7357                    .rounded_br(px(0.))
 7358                    .rounded_tr(px(0.))
 7359                    .border_r_2()
 7360                    .border_color(border_color)
 7361            })
 7362            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7363            .into_any();
 7364
 7365        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7366
 7367        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7368            - point(
 7369                if flag_on_right {
 7370                    POLE_WIDTH
 7371                } else {
 7372                    size.width - POLE_WIDTH
 7373                },
 7374                size.height - line_height,
 7375            );
 7376
 7377        origin.x = origin.x.max(content_origin.x);
 7378
 7379        element.prepaint_at(origin, window, cx);
 7380
 7381        Some((element, origin))
 7382    }
 7383
 7384    fn render_edit_prediction_scroll_popover(
 7385        &mut self,
 7386        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7387        scroll_icon: IconName,
 7388        visible_row_range: Range<DisplayRow>,
 7389        line_layouts: &[LineWithInvisibles],
 7390        newest_selection_head: Option<DisplayPoint>,
 7391        scrolled_content_origin: gpui::Point<Pixels>,
 7392        window: &mut Window,
 7393        cx: &mut App,
 7394    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7395        let mut element = self
 7396            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7397            .into_any();
 7398
 7399        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7400
 7401        let cursor = newest_selection_head?;
 7402        let cursor_row_layout =
 7403            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7404        let cursor_column = cursor.column() as usize;
 7405
 7406        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7407
 7408        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7409
 7410        element.prepaint_at(origin, window, cx);
 7411        Some((element, origin))
 7412    }
 7413
 7414    fn render_edit_prediction_eager_jump_popover(
 7415        &mut self,
 7416        text_bounds: &Bounds<Pixels>,
 7417        content_origin: gpui::Point<Pixels>,
 7418        editor_snapshot: &EditorSnapshot,
 7419        visible_row_range: Range<DisplayRow>,
 7420        scroll_top: f32,
 7421        scroll_bottom: f32,
 7422        line_height: Pixels,
 7423        scroll_pixel_position: gpui::Point<Pixels>,
 7424        target_display_point: DisplayPoint,
 7425        editor_width: Pixels,
 7426        window: &mut Window,
 7427        cx: &mut App,
 7428    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7429        if target_display_point.row().as_f32() < scroll_top {
 7430            let mut element = self
 7431                .render_edit_prediction_line_popover(
 7432                    "Jump to Edit",
 7433                    Some(IconName::ArrowUp),
 7434                    window,
 7435                    cx,
 7436                )?
 7437                .into_any();
 7438
 7439            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7440            let offset = point(
 7441                (text_bounds.size.width - size.width) / 2.,
 7442                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7443            );
 7444
 7445            let origin = text_bounds.origin + offset;
 7446            element.prepaint_at(origin, window, cx);
 7447            Some((element, origin))
 7448        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7449            let mut element = self
 7450                .render_edit_prediction_line_popover(
 7451                    "Jump to Edit",
 7452                    Some(IconName::ArrowDown),
 7453                    window,
 7454                    cx,
 7455                )?
 7456                .into_any();
 7457
 7458            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7459            let offset = point(
 7460                (text_bounds.size.width - size.width) / 2.,
 7461                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7462            );
 7463
 7464            let origin = text_bounds.origin + offset;
 7465            element.prepaint_at(origin, window, cx);
 7466            Some((element, origin))
 7467        } else {
 7468            self.render_edit_prediction_end_of_line_popover(
 7469                "Jump to Edit",
 7470                editor_snapshot,
 7471                visible_row_range,
 7472                target_display_point,
 7473                line_height,
 7474                scroll_pixel_position,
 7475                content_origin,
 7476                editor_width,
 7477                window,
 7478                cx,
 7479            )
 7480        }
 7481    }
 7482
 7483    fn render_edit_prediction_end_of_line_popover(
 7484        self: &mut Editor,
 7485        label: &'static str,
 7486        editor_snapshot: &EditorSnapshot,
 7487        visible_row_range: Range<DisplayRow>,
 7488        target_display_point: DisplayPoint,
 7489        line_height: Pixels,
 7490        scroll_pixel_position: gpui::Point<Pixels>,
 7491        content_origin: gpui::Point<Pixels>,
 7492        editor_width: Pixels,
 7493        window: &mut Window,
 7494        cx: &mut App,
 7495    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7496        let target_line_end = DisplayPoint::new(
 7497            target_display_point.row(),
 7498            editor_snapshot.line_len(target_display_point.row()),
 7499        );
 7500
 7501        let mut element = self
 7502            .render_edit_prediction_line_popover(label, None, window, cx)?
 7503            .into_any();
 7504
 7505        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7506
 7507        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7508
 7509        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7510        let mut origin = start_point
 7511            + line_origin
 7512            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7513        origin.x = origin.x.max(content_origin.x);
 7514
 7515        let max_x = content_origin.x + editor_width - size.width;
 7516
 7517        if origin.x > max_x {
 7518            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7519
 7520            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7521                origin.y += offset;
 7522                IconName::ArrowUp
 7523            } else {
 7524                origin.y -= offset;
 7525                IconName::ArrowDown
 7526            };
 7527
 7528            element = self
 7529                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7530                .into_any();
 7531
 7532            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7533
 7534            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7535        }
 7536
 7537        element.prepaint_at(origin, window, cx);
 7538        Some((element, origin))
 7539    }
 7540
 7541    fn render_edit_prediction_diff_popover(
 7542        self: &Editor,
 7543        text_bounds: &Bounds<Pixels>,
 7544        content_origin: gpui::Point<Pixels>,
 7545        editor_snapshot: &EditorSnapshot,
 7546        visible_row_range: Range<DisplayRow>,
 7547        line_layouts: &[LineWithInvisibles],
 7548        line_height: Pixels,
 7549        scroll_pixel_position: gpui::Point<Pixels>,
 7550        newest_selection_head: Option<DisplayPoint>,
 7551        editor_width: Pixels,
 7552        style: &EditorStyle,
 7553        edits: &Vec<(Range<Anchor>, String)>,
 7554        edit_preview: &Option<language::EditPreview>,
 7555        snapshot: &language::BufferSnapshot,
 7556        window: &mut Window,
 7557        cx: &mut App,
 7558    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7559        let edit_start = edits
 7560            .first()
 7561            .unwrap()
 7562            .0
 7563            .start
 7564            .to_display_point(editor_snapshot);
 7565        let edit_end = edits
 7566            .last()
 7567            .unwrap()
 7568            .0
 7569            .end
 7570            .to_display_point(editor_snapshot);
 7571
 7572        let is_visible = visible_row_range.contains(&edit_start.row())
 7573            || visible_row_range.contains(&edit_end.row());
 7574        if !is_visible {
 7575            return None;
 7576        }
 7577
 7578        let highlighted_edits =
 7579            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7580
 7581        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7582        let line_count = highlighted_edits.text.lines().count();
 7583
 7584        const BORDER_WIDTH: Pixels = px(1.);
 7585
 7586        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7587        let has_keybind = keybind.is_some();
 7588
 7589        let mut element = h_flex()
 7590            .items_start()
 7591            .child(
 7592                h_flex()
 7593                    .bg(cx.theme().colors().editor_background)
 7594                    .border(BORDER_WIDTH)
 7595                    .shadow_sm()
 7596                    .border_color(cx.theme().colors().border)
 7597                    .rounded_l_lg()
 7598                    .when(line_count > 1, |el| el.rounded_br_lg())
 7599                    .pr_1()
 7600                    .child(styled_text),
 7601            )
 7602            .child(
 7603                h_flex()
 7604                    .h(line_height + BORDER_WIDTH * 2.)
 7605                    .px_1p5()
 7606                    .gap_1()
 7607                    // Workaround: For some reason, there's a gap if we don't do this
 7608                    .ml(-BORDER_WIDTH)
 7609                    .shadow(smallvec![gpui::BoxShadow {
 7610                        color: gpui::black().opacity(0.05),
 7611                        offset: point(px(1.), px(1.)),
 7612                        blur_radius: px(2.),
 7613                        spread_radius: px(0.),
 7614                    }])
 7615                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7616                    .border(BORDER_WIDTH)
 7617                    .border_color(cx.theme().colors().border)
 7618                    .rounded_r_lg()
 7619                    .id("edit_prediction_diff_popover_keybind")
 7620                    .when(!has_keybind, |el| {
 7621                        let status_colors = cx.theme().status();
 7622
 7623                        el.bg(status_colors.error_background)
 7624                            .border_color(status_colors.error.opacity(0.6))
 7625                            .child(Icon::new(IconName::Info).color(Color::Error))
 7626                            .cursor_default()
 7627                            .hoverable_tooltip(move |_window, cx| {
 7628                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7629                            })
 7630                    })
 7631                    .children(keybind),
 7632            )
 7633            .into_any();
 7634
 7635        let longest_row =
 7636            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7637        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7638            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7639        } else {
 7640            layout_line(
 7641                longest_row,
 7642                editor_snapshot,
 7643                style,
 7644                editor_width,
 7645                |_| false,
 7646                window,
 7647                cx,
 7648            )
 7649            .width
 7650        };
 7651
 7652        let viewport_bounds =
 7653            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7654                right: -EditorElement::SCROLLBAR_WIDTH,
 7655                ..Default::default()
 7656            });
 7657
 7658        let x_after_longest =
 7659            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7660                - scroll_pixel_position.x;
 7661
 7662        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7663
 7664        // Fully visible if it can be displayed within the window (allow overlapping other
 7665        // panes). However, this is only allowed if the popover starts within text_bounds.
 7666        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7667            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7668
 7669        let mut origin = if can_position_to_the_right {
 7670            point(
 7671                x_after_longest,
 7672                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7673                    - scroll_pixel_position.y,
 7674            )
 7675        } else {
 7676            let cursor_row = newest_selection_head.map(|head| head.row());
 7677            let above_edit = edit_start
 7678                .row()
 7679                .0
 7680                .checked_sub(line_count as u32)
 7681                .map(DisplayRow);
 7682            let below_edit = Some(edit_end.row() + 1);
 7683            let above_cursor =
 7684                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7685            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7686
 7687            // Place the edit popover adjacent to the edit if there is a location
 7688            // available that is onscreen and does not obscure the cursor. Otherwise,
 7689            // place it adjacent to the cursor.
 7690            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7691                .into_iter()
 7692                .flatten()
 7693                .find(|&start_row| {
 7694                    let end_row = start_row + line_count as u32;
 7695                    visible_row_range.contains(&start_row)
 7696                        && visible_row_range.contains(&end_row)
 7697                        && cursor_row.map_or(true, |cursor_row| {
 7698                            !((start_row..end_row).contains(&cursor_row))
 7699                        })
 7700                })?;
 7701
 7702            content_origin
 7703                + point(
 7704                    -scroll_pixel_position.x,
 7705                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7706                )
 7707        };
 7708
 7709        origin.x -= BORDER_WIDTH;
 7710
 7711        window.defer_draw(element, origin, 1);
 7712
 7713        // Do not return an element, since it will already be drawn due to defer_draw.
 7714        None
 7715    }
 7716
 7717    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7718        px(30.)
 7719    }
 7720
 7721    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7722        if self.read_only(cx) {
 7723            cx.theme().players().read_only()
 7724        } else {
 7725            self.style.as_ref().unwrap().local_player
 7726        }
 7727    }
 7728
 7729    fn render_edit_prediction_accept_keybind(
 7730        &self,
 7731        window: &mut Window,
 7732        cx: &App,
 7733    ) -> Option<AnyElement> {
 7734        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7735        let accept_keystroke = accept_binding.keystroke()?;
 7736
 7737        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7738
 7739        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7740            Color::Accent
 7741        } else {
 7742            Color::Muted
 7743        };
 7744
 7745        h_flex()
 7746            .px_0p5()
 7747            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7748            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7749            .text_size(TextSize::XSmall.rems(cx))
 7750            .child(h_flex().children(ui::render_modifiers(
 7751                &accept_keystroke.modifiers,
 7752                PlatformStyle::platform(),
 7753                Some(modifiers_color),
 7754                Some(IconSize::XSmall.rems().into()),
 7755                true,
 7756            )))
 7757            .when(is_platform_style_mac, |parent| {
 7758                parent.child(accept_keystroke.key.clone())
 7759            })
 7760            .when(!is_platform_style_mac, |parent| {
 7761                parent.child(
 7762                    Key::new(
 7763                        util::capitalize(&accept_keystroke.key),
 7764                        Some(Color::Default),
 7765                    )
 7766                    .size(Some(IconSize::XSmall.rems().into())),
 7767                )
 7768            })
 7769            .into_any()
 7770            .into()
 7771    }
 7772
 7773    fn render_edit_prediction_line_popover(
 7774        &self,
 7775        label: impl Into<SharedString>,
 7776        icon: Option<IconName>,
 7777        window: &mut Window,
 7778        cx: &App,
 7779    ) -> Option<Stateful<Div>> {
 7780        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7781
 7782        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7783        let has_keybind = keybind.is_some();
 7784
 7785        let result = h_flex()
 7786            .id("ep-line-popover")
 7787            .py_0p5()
 7788            .pl_1()
 7789            .pr(padding_right)
 7790            .gap_1()
 7791            .rounded_md()
 7792            .border_1()
 7793            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7794            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7795            .shadow_sm()
 7796            .when(!has_keybind, |el| {
 7797                let status_colors = cx.theme().status();
 7798
 7799                el.bg(status_colors.error_background)
 7800                    .border_color(status_colors.error.opacity(0.6))
 7801                    .pl_2()
 7802                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7803                    .cursor_default()
 7804                    .hoverable_tooltip(move |_window, cx| {
 7805                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7806                    })
 7807            })
 7808            .children(keybind)
 7809            .child(
 7810                Label::new(label)
 7811                    .size(LabelSize::Small)
 7812                    .when(!has_keybind, |el| {
 7813                        el.color(cx.theme().status().error.into()).strikethrough()
 7814                    }),
 7815            )
 7816            .when(!has_keybind, |el| {
 7817                el.child(
 7818                    h_flex().ml_1().child(
 7819                        Icon::new(IconName::Info)
 7820                            .size(IconSize::Small)
 7821                            .color(cx.theme().status().error.into()),
 7822                    ),
 7823                )
 7824            })
 7825            .when_some(icon, |element, icon| {
 7826                element.child(
 7827                    div()
 7828                        .mt(px(1.5))
 7829                        .child(Icon::new(icon).size(IconSize::Small)),
 7830                )
 7831            });
 7832
 7833        Some(result)
 7834    }
 7835
 7836    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7837        let accent_color = cx.theme().colors().text_accent;
 7838        let editor_bg_color = cx.theme().colors().editor_background;
 7839        editor_bg_color.blend(accent_color.opacity(0.1))
 7840    }
 7841
 7842    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7843        let accent_color = cx.theme().colors().text_accent;
 7844        let editor_bg_color = cx.theme().colors().editor_background;
 7845        editor_bg_color.blend(accent_color.opacity(0.6))
 7846    }
 7847
 7848    fn render_edit_prediction_cursor_popover(
 7849        &self,
 7850        min_width: Pixels,
 7851        max_width: Pixels,
 7852        cursor_point: Point,
 7853        style: &EditorStyle,
 7854        accept_keystroke: Option<&gpui::Keystroke>,
 7855        _window: &Window,
 7856        cx: &mut Context<Editor>,
 7857    ) -> Option<AnyElement> {
 7858        let provider = self.edit_prediction_provider.as_ref()?;
 7859
 7860        if provider.provider.needs_terms_acceptance(cx) {
 7861            return Some(
 7862                h_flex()
 7863                    .min_w(min_width)
 7864                    .flex_1()
 7865                    .px_2()
 7866                    .py_1()
 7867                    .gap_3()
 7868                    .elevation_2(cx)
 7869                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7870                    .id("accept-terms")
 7871                    .cursor_pointer()
 7872                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7873                    .on_click(cx.listener(|this, _event, window, cx| {
 7874                        cx.stop_propagation();
 7875                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7876                        window.dispatch_action(
 7877                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7878                            cx,
 7879                        );
 7880                    }))
 7881                    .child(
 7882                        h_flex()
 7883                            .flex_1()
 7884                            .gap_2()
 7885                            .child(Icon::new(IconName::ZedPredict))
 7886                            .child(Label::new("Accept Terms of Service"))
 7887                            .child(div().w_full())
 7888                            .child(
 7889                                Icon::new(IconName::ArrowUpRight)
 7890                                    .color(Color::Muted)
 7891                                    .size(IconSize::Small),
 7892                            )
 7893                            .into_any_element(),
 7894                    )
 7895                    .into_any(),
 7896            );
 7897        }
 7898
 7899        let is_refreshing = provider.provider.is_refreshing(cx);
 7900
 7901        fn pending_completion_container() -> Div {
 7902            h_flex()
 7903                .h_full()
 7904                .flex_1()
 7905                .gap_2()
 7906                .child(Icon::new(IconName::ZedPredict))
 7907        }
 7908
 7909        let completion = match &self.active_inline_completion {
 7910            Some(prediction) => {
 7911                if !self.has_visible_completions_menu() {
 7912                    const RADIUS: Pixels = px(6.);
 7913                    const BORDER_WIDTH: Pixels = px(1.);
 7914
 7915                    return Some(
 7916                        h_flex()
 7917                            .elevation_2(cx)
 7918                            .border(BORDER_WIDTH)
 7919                            .border_color(cx.theme().colors().border)
 7920                            .when(accept_keystroke.is_none(), |el| {
 7921                                el.border_color(cx.theme().status().error)
 7922                            })
 7923                            .rounded(RADIUS)
 7924                            .rounded_tl(px(0.))
 7925                            .overflow_hidden()
 7926                            .child(div().px_1p5().child(match &prediction.completion {
 7927                                InlineCompletion::Move { target, snapshot } => {
 7928                                    use text::ToPoint as _;
 7929                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7930                                    {
 7931                                        Icon::new(IconName::ZedPredictDown)
 7932                                    } else {
 7933                                        Icon::new(IconName::ZedPredictUp)
 7934                                    }
 7935                                }
 7936                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7937                            }))
 7938                            .child(
 7939                                h_flex()
 7940                                    .gap_1()
 7941                                    .py_1()
 7942                                    .px_2()
 7943                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7944                                    .border_l_1()
 7945                                    .border_color(cx.theme().colors().border)
 7946                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7947                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7948                                        el.child(
 7949                                            Label::new("Hold")
 7950                                                .size(LabelSize::Small)
 7951                                                .when(accept_keystroke.is_none(), |el| {
 7952                                                    el.strikethrough()
 7953                                                })
 7954                                                .line_height_style(LineHeightStyle::UiLabel),
 7955                                        )
 7956                                    })
 7957                                    .id("edit_prediction_cursor_popover_keybind")
 7958                                    .when(accept_keystroke.is_none(), |el| {
 7959                                        let status_colors = cx.theme().status();
 7960
 7961                                        el.bg(status_colors.error_background)
 7962                                            .border_color(status_colors.error.opacity(0.6))
 7963                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7964                                            .cursor_default()
 7965                                            .hoverable_tooltip(move |_window, cx| {
 7966                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7967                                                    .into()
 7968                                            })
 7969                                    })
 7970                                    .when_some(
 7971                                        accept_keystroke.as_ref(),
 7972                                        |el, accept_keystroke| {
 7973                                            el.child(h_flex().children(ui::render_modifiers(
 7974                                                &accept_keystroke.modifiers,
 7975                                                PlatformStyle::platform(),
 7976                                                Some(Color::Default),
 7977                                                Some(IconSize::XSmall.rems().into()),
 7978                                                false,
 7979                                            )))
 7980                                        },
 7981                                    ),
 7982                            )
 7983                            .into_any(),
 7984                    );
 7985                }
 7986
 7987                self.render_edit_prediction_cursor_popover_preview(
 7988                    prediction,
 7989                    cursor_point,
 7990                    style,
 7991                    cx,
 7992                )?
 7993            }
 7994
 7995            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7996                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7997                    stale_completion,
 7998                    cursor_point,
 7999                    style,
 8000                    cx,
 8001                )?,
 8002
 8003                None => {
 8004                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8005                }
 8006            },
 8007
 8008            None => pending_completion_container().child(Label::new("No Prediction")),
 8009        };
 8010
 8011        let completion = if is_refreshing {
 8012            completion
 8013                .with_animation(
 8014                    "loading-completion",
 8015                    Animation::new(Duration::from_secs(2))
 8016                        .repeat()
 8017                        .with_easing(pulsating_between(0.4, 0.8)),
 8018                    |label, delta| label.opacity(delta),
 8019                )
 8020                .into_any_element()
 8021        } else {
 8022            completion.into_any_element()
 8023        };
 8024
 8025        let has_completion = self.active_inline_completion.is_some();
 8026
 8027        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8028        Some(
 8029            h_flex()
 8030                .min_w(min_width)
 8031                .max_w(max_width)
 8032                .flex_1()
 8033                .elevation_2(cx)
 8034                .border_color(cx.theme().colors().border)
 8035                .child(
 8036                    div()
 8037                        .flex_1()
 8038                        .py_1()
 8039                        .px_2()
 8040                        .overflow_hidden()
 8041                        .child(completion),
 8042                )
 8043                .when_some(accept_keystroke, |el, accept_keystroke| {
 8044                    if !accept_keystroke.modifiers.modified() {
 8045                        return el;
 8046                    }
 8047
 8048                    el.child(
 8049                        h_flex()
 8050                            .h_full()
 8051                            .border_l_1()
 8052                            .rounded_r_lg()
 8053                            .border_color(cx.theme().colors().border)
 8054                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8055                            .gap_1()
 8056                            .py_1()
 8057                            .px_2()
 8058                            .child(
 8059                                h_flex()
 8060                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8061                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8062                                    .child(h_flex().children(ui::render_modifiers(
 8063                                        &accept_keystroke.modifiers,
 8064                                        PlatformStyle::platform(),
 8065                                        Some(if !has_completion {
 8066                                            Color::Muted
 8067                                        } else {
 8068                                            Color::Default
 8069                                        }),
 8070                                        None,
 8071                                        false,
 8072                                    ))),
 8073                            )
 8074                            .child(Label::new("Preview").into_any_element())
 8075                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8076                    )
 8077                })
 8078                .into_any(),
 8079        )
 8080    }
 8081
 8082    fn render_edit_prediction_cursor_popover_preview(
 8083        &self,
 8084        completion: &InlineCompletionState,
 8085        cursor_point: Point,
 8086        style: &EditorStyle,
 8087        cx: &mut Context<Editor>,
 8088    ) -> Option<Div> {
 8089        use text::ToPoint as _;
 8090
 8091        fn render_relative_row_jump(
 8092            prefix: impl Into<String>,
 8093            current_row: u32,
 8094            target_row: u32,
 8095        ) -> Div {
 8096            let (row_diff, arrow) = if target_row < current_row {
 8097                (current_row - target_row, IconName::ArrowUp)
 8098            } else {
 8099                (target_row - current_row, IconName::ArrowDown)
 8100            };
 8101
 8102            h_flex()
 8103                .child(
 8104                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8105                        .color(Color::Muted)
 8106                        .size(LabelSize::Small),
 8107                )
 8108                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8109        }
 8110
 8111        match &completion.completion {
 8112            InlineCompletion::Move {
 8113                target, snapshot, ..
 8114            } => Some(
 8115                h_flex()
 8116                    .px_2()
 8117                    .gap_2()
 8118                    .flex_1()
 8119                    .child(
 8120                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8121                            Icon::new(IconName::ZedPredictDown)
 8122                        } else {
 8123                            Icon::new(IconName::ZedPredictUp)
 8124                        },
 8125                    )
 8126                    .child(Label::new("Jump to Edit")),
 8127            ),
 8128
 8129            InlineCompletion::Edit {
 8130                edits,
 8131                edit_preview,
 8132                snapshot,
 8133                display_mode: _,
 8134            } => {
 8135                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8136
 8137                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8138                    &snapshot,
 8139                    &edits,
 8140                    edit_preview.as_ref()?,
 8141                    true,
 8142                    cx,
 8143                )
 8144                .first_line_preview();
 8145
 8146                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8147                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8148
 8149                let preview = h_flex()
 8150                    .gap_1()
 8151                    .min_w_16()
 8152                    .child(styled_text)
 8153                    .when(has_more_lines, |parent| parent.child(""));
 8154
 8155                let left = if first_edit_row != cursor_point.row {
 8156                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8157                        .into_any_element()
 8158                } else {
 8159                    Icon::new(IconName::ZedPredict).into_any_element()
 8160                };
 8161
 8162                Some(
 8163                    h_flex()
 8164                        .h_full()
 8165                        .flex_1()
 8166                        .gap_2()
 8167                        .pr_1()
 8168                        .overflow_x_hidden()
 8169                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8170                        .child(left)
 8171                        .child(preview),
 8172                )
 8173            }
 8174        }
 8175    }
 8176
 8177    fn render_context_menu(
 8178        &self,
 8179        style: &EditorStyle,
 8180        max_height_in_lines: u32,
 8181        window: &mut Window,
 8182        cx: &mut Context<Editor>,
 8183    ) -> Option<AnyElement> {
 8184        let menu = self.context_menu.borrow();
 8185        let menu = menu.as_ref()?;
 8186        if !menu.visible() {
 8187            return None;
 8188        };
 8189        Some(menu.render(style, max_height_in_lines, window, cx))
 8190    }
 8191
 8192    fn render_context_menu_aside(
 8193        &mut self,
 8194        max_size: Size<Pixels>,
 8195        window: &mut Window,
 8196        cx: &mut Context<Editor>,
 8197    ) -> Option<AnyElement> {
 8198        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8199            if menu.visible() {
 8200                menu.render_aside(self, max_size, window, cx)
 8201            } else {
 8202                None
 8203            }
 8204        })
 8205    }
 8206
 8207    fn hide_context_menu(
 8208        &mut self,
 8209        window: &mut Window,
 8210        cx: &mut Context<Self>,
 8211    ) -> Option<CodeContextMenu> {
 8212        cx.notify();
 8213        self.completion_tasks.clear();
 8214        let context_menu = self.context_menu.borrow_mut().take();
 8215        self.stale_inline_completion_in_menu.take();
 8216        self.update_visible_inline_completion(window, cx);
 8217        context_menu
 8218    }
 8219
 8220    fn show_snippet_choices(
 8221        &mut self,
 8222        choices: &Vec<String>,
 8223        selection: Range<Anchor>,
 8224        cx: &mut Context<Self>,
 8225    ) {
 8226        if selection.start.buffer_id.is_none() {
 8227            return;
 8228        }
 8229        let buffer_id = selection.start.buffer_id.unwrap();
 8230        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8231        let id = post_inc(&mut self.next_completion_id);
 8232
 8233        if let Some(buffer) = buffer {
 8234            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8235                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 8236            ));
 8237        }
 8238    }
 8239
 8240    pub fn insert_snippet(
 8241        &mut self,
 8242        insertion_ranges: &[Range<usize>],
 8243        snippet: Snippet,
 8244        window: &mut Window,
 8245        cx: &mut Context<Self>,
 8246    ) -> Result<()> {
 8247        struct Tabstop<T> {
 8248            is_end_tabstop: bool,
 8249            ranges: Vec<Range<T>>,
 8250            choices: Option<Vec<String>>,
 8251        }
 8252
 8253        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8254            let snippet_text: Arc<str> = snippet.text.clone().into();
 8255            let edits = insertion_ranges
 8256                .iter()
 8257                .cloned()
 8258                .map(|range| (range, snippet_text.clone()));
 8259            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8260
 8261            let snapshot = &*buffer.read(cx);
 8262            let snippet = &snippet;
 8263            snippet
 8264                .tabstops
 8265                .iter()
 8266                .map(|tabstop| {
 8267                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8268                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8269                    });
 8270                    let mut tabstop_ranges = tabstop
 8271                        .ranges
 8272                        .iter()
 8273                        .flat_map(|tabstop_range| {
 8274                            let mut delta = 0_isize;
 8275                            insertion_ranges.iter().map(move |insertion_range| {
 8276                                let insertion_start = insertion_range.start as isize + delta;
 8277                                delta +=
 8278                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8279
 8280                                let start = ((insertion_start + tabstop_range.start) as usize)
 8281                                    .min(snapshot.len());
 8282                                let end = ((insertion_start + tabstop_range.end) as usize)
 8283                                    .min(snapshot.len());
 8284                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8285                            })
 8286                        })
 8287                        .collect::<Vec<_>>();
 8288                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8289
 8290                    Tabstop {
 8291                        is_end_tabstop,
 8292                        ranges: tabstop_ranges,
 8293                        choices: tabstop.choices.clone(),
 8294                    }
 8295                })
 8296                .collect::<Vec<_>>()
 8297        });
 8298        if let Some(tabstop) = tabstops.first() {
 8299            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8300                s.select_ranges(tabstop.ranges.iter().cloned());
 8301            });
 8302
 8303            if let Some(choices) = &tabstop.choices {
 8304                if let Some(selection) = tabstop.ranges.first() {
 8305                    self.show_snippet_choices(choices, selection.clone(), cx)
 8306                }
 8307            }
 8308
 8309            // If we're already at the last tabstop and it's at the end of the snippet,
 8310            // we're done, we don't need to keep the state around.
 8311            if !tabstop.is_end_tabstop {
 8312                let choices = tabstops
 8313                    .iter()
 8314                    .map(|tabstop| tabstop.choices.clone())
 8315                    .collect();
 8316
 8317                let ranges = tabstops
 8318                    .into_iter()
 8319                    .map(|tabstop| tabstop.ranges)
 8320                    .collect::<Vec<_>>();
 8321
 8322                self.snippet_stack.push(SnippetState {
 8323                    active_index: 0,
 8324                    ranges,
 8325                    choices,
 8326                });
 8327            }
 8328
 8329            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8330            if self.autoclose_regions.is_empty() {
 8331                let snapshot = self.buffer.read(cx).snapshot(cx);
 8332                for selection in &mut self.selections.all::<Point>(cx) {
 8333                    let selection_head = selection.head();
 8334                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8335                        continue;
 8336                    };
 8337
 8338                    let mut bracket_pair = None;
 8339                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8340                    let prev_chars = snapshot
 8341                        .reversed_chars_at(selection_head)
 8342                        .collect::<String>();
 8343                    for (pair, enabled) in scope.brackets() {
 8344                        if enabled
 8345                            && pair.close
 8346                            && prev_chars.starts_with(pair.start.as_str())
 8347                            && next_chars.starts_with(pair.end.as_str())
 8348                        {
 8349                            bracket_pair = Some(pair.clone());
 8350                            break;
 8351                        }
 8352                    }
 8353                    if let Some(pair) = bracket_pair {
 8354                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8355                        let autoclose_enabled =
 8356                            self.use_autoclose && snapshot_settings.use_autoclose;
 8357                        if autoclose_enabled {
 8358                            let start = snapshot.anchor_after(selection_head);
 8359                            let end = snapshot.anchor_after(selection_head);
 8360                            self.autoclose_regions.push(AutocloseRegion {
 8361                                selection_id: selection.id,
 8362                                range: start..end,
 8363                                pair,
 8364                            });
 8365                        }
 8366                    }
 8367                }
 8368            }
 8369        }
 8370        Ok(())
 8371    }
 8372
 8373    pub fn move_to_next_snippet_tabstop(
 8374        &mut self,
 8375        window: &mut Window,
 8376        cx: &mut Context<Self>,
 8377    ) -> bool {
 8378        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8379    }
 8380
 8381    pub fn move_to_prev_snippet_tabstop(
 8382        &mut self,
 8383        window: &mut Window,
 8384        cx: &mut Context<Self>,
 8385    ) -> bool {
 8386        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8387    }
 8388
 8389    pub fn move_to_snippet_tabstop(
 8390        &mut self,
 8391        bias: Bias,
 8392        window: &mut Window,
 8393        cx: &mut Context<Self>,
 8394    ) -> bool {
 8395        if let Some(mut snippet) = self.snippet_stack.pop() {
 8396            match bias {
 8397                Bias::Left => {
 8398                    if snippet.active_index > 0 {
 8399                        snippet.active_index -= 1;
 8400                    } else {
 8401                        self.snippet_stack.push(snippet);
 8402                        return false;
 8403                    }
 8404                }
 8405                Bias::Right => {
 8406                    if snippet.active_index + 1 < snippet.ranges.len() {
 8407                        snippet.active_index += 1;
 8408                    } else {
 8409                        self.snippet_stack.push(snippet);
 8410                        return false;
 8411                    }
 8412                }
 8413            }
 8414            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8415                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8416                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8417                });
 8418
 8419                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8420                    if let Some(selection) = current_ranges.first() {
 8421                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8422                    }
 8423                }
 8424
 8425                // If snippet state is not at the last tabstop, push it back on the stack
 8426                if snippet.active_index + 1 < snippet.ranges.len() {
 8427                    self.snippet_stack.push(snippet);
 8428                }
 8429                return true;
 8430            }
 8431        }
 8432
 8433        false
 8434    }
 8435
 8436    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8437        self.transact(window, cx, |this, window, cx| {
 8438            this.select_all(&SelectAll, window, cx);
 8439            this.insert("", window, cx);
 8440        });
 8441    }
 8442
 8443    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8444        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8445        self.transact(window, cx, |this, window, cx| {
 8446            this.select_autoclose_pair(window, cx);
 8447            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8448            if !this.linked_edit_ranges.is_empty() {
 8449                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8450                let snapshot = this.buffer.read(cx).snapshot(cx);
 8451
 8452                for selection in selections.iter() {
 8453                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8454                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8455                    if selection_start.buffer_id != selection_end.buffer_id {
 8456                        continue;
 8457                    }
 8458                    if let Some(ranges) =
 8459                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8460                    {
 8461                        for (buffer, entries) in ranges {
 8462                            linked_ranges.entry(buffer).or_default().extend(entries);
 8463                        }
 8464                    }
 8465                }
 8466            }
 8467
 8468            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8469            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8470            for selection in &mut selections {
 8471                if selection.is_empty() {
 8472                    let old_head = selection.head();
 8473                    let mut new_head =
 8474                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8475                            .to_point(&display_map);
 8476                    if let Some((buffer, line_buffer_range)) = display_map
 8477                        .buffer_snapshot
 8478                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8479                    {
 8480                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8481                        let indent_len = match indent_size.kind {
 8482                            IndentKind::Space => {
 8483                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8484                            }
 8485                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8486                        };
 8487                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8488                            let indent_len = indent_len.get();
 8489                            new_head = cmp::min(
 8490                                new_head,
 8491                                MultiBufferPoint::new(
 8492                                    old_head.row,
 8493                                    ((old_head.column - 1) / indent_len) * indent_len,
 8494                                ),
 8495                            );
 8496                        }
 8497                    }
 8498
 8499                    selection.set_head(new_head, SelectionGoal::None);
 8500                }
 8501            }
 8502
 8503            this.signature_help_state.set_backspace_pressed(true);
 8504            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8505                s.select(selections)
 8506            });
 8507            this.insert("", window, cx);
 8508            let empty_str: Arc<str> = Arc::from("");
 8509            for (buffer, edits) in linked_ranges {
 8510                let snapshot = buffer.read(cx).snapshot();
 8511                use text::ToPoint as TP;
 8512
 8513                let edits = edits
 8514                    .into_iter()
 8515                    .map(|range| {
 8516                        let end_point = TP::to_point(&range.end, &snapshot);
 8517                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8518
 8519                        if end_point == start_point {
 8520                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8521                                .saturating_sub(1);
 8522                            start_point =
 8523                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8524                        };
 8525
 8526                        (start_point..end_point, empty_str.clone())
 8527                    })
 8528                    .sorted_by_key(|(range, _)| range.start)
 8529                    .collect::<Vec<_>>();
 8530                buffer.update(cx, |this, cx| {
 8531                    this.edit(edits, None, cx);
 8532                })
 8533            }
 8534            this.refresh_inline_completion(true, false, window, cx);
 8535            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8536        });
 8537    }
 8538
 8539    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8540        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8541        self.transact(window, cx, |this, window, cx| {
 8542            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8543                s.move_with(|map, selection| {
 8544                    if selection.is_empty() {
 8545                        let cursor = movement::right(map, selection.head());
 8546                        selection.end = cursor;
 8547                        selection.reversed = true;
 8548                        selection.goal = SelectionGoal::None;
 8549                    }
 8550                })
 8551            });
 8552            this.insert("", window, cx);
 8553            this.refresh_inline_completion(true, false, window, cx);
 8554        });
 8555    }
 8556
 8557    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8558        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8559        if self.move_to_prev_snippet_tabstop(window, cx) {
 8560            return;
 8561        }
 8562        self.outdent(&Outdent, window, cx);
 8563    }
 8564
 8565    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8566        if self.move_to_next_snippet_tabstop(window, cx) {
 8567            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8568            return;
 8569        }
 8570        if self.read_only(cx) {
 8571            return;
 8572        }
 8573        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8574        let mut selections = self.selections.all_adjusted(cx);
 8575        let buffer = self.buffer.read(cx);
 8576        let snapshot = buffer.snapshot(cx);
 8577        let rows_iter = selections.iter().map(|s| s.head().row);
 8578        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8579
 8580        let mut edits = Vec::new();
 8581        let mut prev_edited_row = 0;
 8582        let mut row_delta = 0;
 8583        for selection in &mut selections {
 8584            if selection.start.row != prev_edited_row {
 8585                row_delta = 0;
 8586            }
 8587            prev_edited_row = selection.end.row;
 8588
 8589            // If the selection is non-empty, then increase the indentation of the selected lines.
 8590            if !selection.is_empty() {
 8591                row_delta =
 8592                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8593                continue;
 8594            }
 8595
 8596            // If the selection is empty and the cursor is in the leading whitespace before the
 8597            // suggested indentation, then auto-indent the line.
 8598            let cursor = selection.head();
 8599            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8600            if let Some(suggested_indent) =
 8601                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8602            {
 8603                if cursor.column < suggested_indent.len
 8604                    && cursor.column <= current_indent.len
 8605                    && current_indent.len <= suggested_indent.len
 8606                {
 8607                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8608                    selection.end = selection.start;
 8609                    if row_delta == 0 {
 8610                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8611                            cursor.row,
 8612                            current_indent,
 8613                            suggested_indent,
 8614                        ));
 8615                        row_delta = suggested_indent.len - current_indent.len;
 8616                    }
 8617                    continue;
 8618                }
 8619            }
 8620
 8621            // Otherwise, insert a hard or soft tab.
 8622            let settings = buffer.language_settings_at(cursor, cx);
 8623            let tab_size = if settings.hard_tabs {
 8624                IndentSize::tab()
 8625            } else {
 8626                let tab_size = settings.tab_size.get();
 8627                let indent_remainder = snapshot
 8628                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8629                    .flat_map(str::chars)
 8630                    .fold(row_delta % tab_size, |counter: u32, c| {
 8631                        if c == '\t' {
 8632                            0
 8633                        } else {
 8634                            (counter + 1) % tab_size
 8635                        }
 8636                    });
 8637
 8638                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8639                IndentSize::spaces(chars_to_next_tab_stop)
 8640            };
 8641            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8642            selection.end = selection.start;
 8643            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8644            row_delta += tab_size.len;
 8645        }
 8646
 8647        self.transact(window, cx, |this, window, cx| {
 8648            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8649            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8650                s.select(selections)
 8651            });
 8652            this.refresh_inline_completion(true, false, window, cx);
 8653        });
 8654    }
 8655
 8656    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8657        if self.read_only(cx) {
 8658            return;
 8659        }
 8660        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8661        let mut selections = self.selections.all::<Point>(cx);
 8662        let mut prev_edited_row = 0;
 8663        let mut row_delta = 0;
 8664        let mut edits = Vec::new();
 8665        let buffer = self.buffer.read(cx);
 8666        let snapshot = buffer.snapshot(cx);
 8667        for selection in &mut selections {
 8668            if selection.start.row != prev_edited_row {
 8669                row_delta = 0;
 8670            }
 8671            prev_edited_row = selection.end.row;
 8672
 8673            row_delta =
 8674                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8675        }
 8676
 8677        self.transact(window, cx, |this, window, cx| {
 8678            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8679            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8680                s.select(selections)
 8681            });
 8682        });
 8683    }
 8684
 8685    fn indent_selection(
 8686        buffer: &MultiBuffer,
 8687        snapshot: &MultiBufferSnapshot,
 8688        selection: &mut Selection<Point>,
 8689        edits: &mut Vec<(Range<Point>, String)>,
 8690        delta_for_start_row: u32,
 8691        cx: &App,
 8692    ) -> u32 {
 8693        let settings = buffer.language_settings_at(selection.start, cx);
 8694        let tab_size = settings.tab_size.get();
 8695        let indent_kind = if settings.hard_tabs {
 8696            IndentKind::Tab
 8697        } else {
 8698            IndentKind::Space
 8699        };
 8700        let mut start_row = selection.start.row;
 8701        let mut end_row = selection.end.row + 1;
 8702
 8703        // If a selection ends at the beginning of a line, don't indent
 8704        // that last line.
 8705        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8706            end_row -= 1;
 8707        }
 8708
 8709        // Avoid re-indenting a row that has already been indented by a
 8710        // previous selection, but still update this selection's column
 8711        // to reflect that indentation.
 8712        if delta_for_start_row > 0 {
 8713            start_row += 1;
 8714            selection.start.column += delta_for_start_row;
 8715            if selection.end.row == selection.start.row {
 8716                selection.end.column += delta_for_start_row;
 8717            }
 8718        }
 8719
 8720        let mut delta_for_end_row = 0;
 8721        let has_multiple_rows = start_row + 1 != end_row;
 8722        for row in start_row..end_row {
 8723            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8724            let indent_delta = match (current_indent.kind, indent_kind) {
 8725                (IndentKind::Space, IndentKind::Space) => {
 8726                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8727                    IndentSize::spaces(columns_to_next_tab_stop)
 8728                }
 8729                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8730                (_, IndentKind::Tab) => IndentSize::tab(),
 8731            };
 8732
 8733            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8734                0
 8735            } else {
 8736                selection.start.column
 8737            };
 8738            let row_start = Point::new(row, start);
 8739            edits.push((
 8740                row_start..row_start,
 8741                indent_delta.chars().collect::<String>(),
 8742            ));
 8743
 8744            // Update this selection's endpoints to reflect the indentation.
 8745            if row == selection.start.row {
 8746                selection.start.column += indent_delta.len;
 8747            }
 8748            if row == selection.end.row {
 8749                selection.end.column += indent_delta.len;
 8750                delta_for_end_row = indent_delta.len;
 8751            }
 8752        }
 8753
 8754        if selection.start.row == selection.end.row {
 8755            delta_for_start_row + delta_for_end_row
 8756        } else {
 8757            delta_for_end_row
 8758        }
 8759    }
 8760
 8761    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8762        if self.read_only(cx) {
 8763            return;
 8764        }
 8765        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8766        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8767        let selections = self.selections.all::<Point>(cx);
 8768        let mut deletion_ranges = Vec::new();
 8769        let mut last_outdent = None;
 8770        {
 8771            let buffer = self.buffer.read(cx);
 8772            let snapshot = buffer.snapshot(cx);
 8773            for selection in &selections {
 8774                let settings = buffer.language_settings_at(selection.start, cx);
 8775                let tab_size = settings.tab_size.get();
 8776                let mut rows = selection.spanned_rows(false, &display_map);
 8777
 8778                // Avoid re-outdenting a row that has already been outdented by a
 8779                // previous selection.
 8780                if let Some(last_row) = last_outdent {
 8781                    if last_row == rows.start {
 8782                        rows.start = rows.start.next_row();
 8783                    }
 8784                }
 8785                let has_multiple_rows = rows.len() > 1;
 8786                for row in rows.iter_rows() {
 8787                    let indent_size = snapshot.indent_size_for_line(row);
 8788                    if indent_size.len > 0 {
 8789                        let deletion_len = match indent_size.kind {
 8790                            IndentKind::Space => {
 8791                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8792                                if columns_to_prev_tab_stop == 0 {
 8793                                    tab_size
 8794                                } else {
 8795                                    columns_to_prev_tab_stop
 8796                                }
 8797                            }
 8798                            IndentKind::Tab => 1,
 8799                        };
 8800                        let start = if has_multiple_rows
 8801                            || deletion_len > selection.start.column
 8802                            || indent_size.len < selection.start.column
 8803                        {
 8804                            0
 8805                        } else {
 8806                            selection.start.column - deletion_len
 8807                        };
 8808                        deletion_ranges.push(
 8809                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8810                        );
 8811                        last_outdent = Some(row);
 8812                    }
 8813                }
 8814            }
 8815        }
 8816
 8817        self.transact(window, cx, |this, window, cx| {
 8818            this.buffer.update(cx, |buffer, cx| {
 8819                let empty_str: Arc<str> = Arc::default();
 8820                buffer.edit(
 8821                    deletion_ranges
 8822                        .into_iter()
 8823                        .map(|range| (range, empty_str.clone())),
 8824                    None,
 8825                    cx,
 8826                );
 8827            });
 8828            let selections = this.selections.all::<usize>(cx);
 8829            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8830                s.select(selections)
 8831            });
 8832        });
 8833    }
 8834
 8835    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8836        if self.read_only(cx) {
 8837            return;
 8838        }
 8839        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8840        let selections = self
 8841            .selections
 8842            .all::<usize>(cx)
 8843            .into_iter()
 8844            .map(|s| s.range());
 8845
 8846        self.transact(window, cx, |this, window, cx| {
 8847            this.buffer.update(cx, |buffer, cx| {
 8848                buffer.autoindent_ranges(selections, cx);
 8849            });
 8850            let selections = this.selections.all::<usize>(cx);
 8851            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8852                s.select(selections)
 8853            });
 8854        });
 8855    }
 8856
 8857    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8858        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8859        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8860        let selections = self.selections.all::<Point>(cx);
 8861
 8862        let mut new_cursors = Vec::new();
 8863        let mut edit_ranges = Vec::new();
 8864        let mut selections = selections.iter().peekable();
 8865        while let Some(selection) = selections.next() {
 8866            let mut rows = selection.spanned_rows(false, &display_map);
 8867            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8868
 8869            // Accumulate contiguous regions of rows that we want to delete.
 8870            while let Some(next_selection) = selections.peek() {
 8871                let next_rows = next_selection.spanned_rows(false, &display_map);
 8872                if next_rows.start <= rows.end {
 8873                    rows.end = next_rows.end;
 8874                    selections.next().unwrap();
 8875                } else {
 8876                    break;
 8877                }
 8878            }
 8879
 8880            let buffer = &display_map.buffer_snapshot;
 8881            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8882            let edit_end;
 8883            let cursor_buffer_row;
 8884            if buffer.max_point().row >= rows.end.0 {
 8885                // If there's a line after the range, delete the \n from the end of the row range
 8886                // and position the cursor on the next line.
 8887                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8888                cursor_buffer_row = rows.end;
 8889            } else {
 8890                // If there isn't a line after the range, delete the \n from the line before the
 8891                // start of the row range and position the cursor there.
 8892                edit_start = edit_start.saturating_sub(1);
 8893                edit_end = buffer.len();
 8894                cursor_buffer_row = rows.start.previous_row();
 8895            }
 8896
 8897            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8898            *cursor.column_mut() =
 8899                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8900
 8901            new_cursors.push((
 8902                selection.id,
 8903                buffer.anchor_after(cursor.to_point(&display_map)),
 8904            ));
 8905            edit_ranges.push(edit_start..edit_end);
 8906        }
 8907
 8908        self.transact(window, cx, |this, window, cx| {
 8909            let buffer = this.buffer.update(cx, |buffer, cx| {
 8910                let empty_str: Arc<str> = Arc::default();
 8911                buffer.edit(
 8912                    edit_ranges
 8913                        .into_iter()
 8914                        .map(|range| (range, empty_str.clone())),
 8915                    None,
 8916                    cx,
 8917                );
 8918                buffer.snapshot(cx)
 8919            });
 8920            let new_selections = new_cursors
 8921                .into_iter()
 8922                .map(|(id, cursor)| {
 8923                    let cursor = cursor.to_point(&buffer);
 8924                    Selection {
 8925                        id,
 8926                        start: cursor,
 8927                        end: cursor,
 8928                        reversed: false,
 8929                        goal: SelectionGoal::None,
 8930                    }
 8931                })
 8932                .collect();
 8933
 8934            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8935                s.select(new_selections);
 8936            });
 8937        });
 8938    }
 8939
 8940    pub fn join_lines_impl(
 8941        &mut self,
 8942        insert_whitespace: bool,
 8943        window: &mut Window,
 8944        cx: &mut Context<Self>,
 8945    ) {
 8946        if self.read_only(cx) {
 8947            return;
 8948        }
 8949        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8950        for selection in self.selections.all::<Point>(cx) {
 8951            let start = MultiBufferRow(selection.start.row);
 8952            // Treat single line selections as if they include the next line. Otherwise this action
 8953            // would do nothing for single line selections individual cursors.
 8954            let end = if selection.start.row == selection.end.row {
 8955                MultiBufferRow(selection.start.row + 1)
 8956            } else {
 8957                MultiBufferRow(selection.end.row)
 8958            };
 8959
 8960            if let Some(last_row_range) = row_ranges.last_mut() {
 8961                if start <= last_row_range.end {
 8962                    last_row_range.end = end;
 8963                    continue;
 8964                }
 8965            }
 8966            row_ranges.push(start..end);
 8967        }
 8968
 8969        let snapshot = self.buffer.read(cx).snapshot(cx);
 8970        let mut cursor_positions = Vec::new();
 8971        for row_range in &row_ranges {
 8972            let anchor = snapshot.anchor_before(Point::new(
 8973                row_range.end.previous_row().0,
 8974                snapshot.line_len(row_range.end.previous_row()),
 8975            ));
 8976            cursor_positions.push(anchor..anchor);
 8977        }
 8978
 8979        self.transact(window, cx, |this, window, cx| {
 8980            for row_range in row_ranges.into_iter().rev() {
 8981                for row in row_range.iter_rows().rev() {
 8982                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8983                    let next_line_row = row.next_row();
 8984                    let indent = snapshot.indent_size_for_line(next_line_row);
 8985                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8986
 8987                    let replace =
 8988                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8989                            " "
 8990                        } else {
 8991                            ""
 8992                        };
 8993
 8994                    this.buffer.update(cx, |buffer, cx| {
 8995                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8996                    });
 8997                }
 8998            }
 8999
 9000            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9001                s.select_anchor_ranges(cursor_positions)
 9002            });
 9003        });
 9004    }
 9005
 9006    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9007        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9008        self.join_lines_impl(true, window, cx);
 9009    }
 9010
 9011    pub fn sort_lines_case_sensitive(
 9012        &mut self,
 9013        _: &SortLinesCaseSensitive,
 9014        window: &mut Window,
 9015        cx: &mut Context<Self>,
 9016    ) {
 9017        self.manipulate_lines(window, cx, |lines| lines.sort())
 9018    }
 9019
 9020    pub fn sort_lines_case_insensitive(
 9021        &mut self,
 9022        _: &SortLinesCaseInsensitive,
 9023        window: &mut Window,
 9024        cx: &mut Context<Self>,
 9025    ) {
 9026        self.manipulate_lines(window, cx, |lines| {
 9027            lines.sort_by_key(|line| line.to_lowercase())
 9028        })
 9029    }
 9030
 9031    pub fn unique_lines_case_insensitive(
 9032        &mut self,
 9033        _: &UniqueLinesCaseInsensitive,
 9034        window: &mut Window,
 9035        cx: &mut Context<Self>,
 9036    ) {
 9037        self.manipulate_lines(window, cx, |lines| {
 9038            let mut seen = HashSet::default();
 9039            lines.retain(|line| seen.insert(line.to_lowercase()));
 9040        })
 9041    }
 9042
 9043    pub fn unique_lines_case_sensitive(
 9044        &mut self,
 9045        _: &UniqueLinesCaseSensitive,
 9046        window: &mut Window,
 9047        cx: &mut Context<Self>,
 9048    ) {
 9049        self.manipulate_lines(window, cx, |lines| {
 9050            let mut seen = HashSet::default();
 9051            lines.retain(|line| seen.insert(*line));
 9052        })
 9053    }
 9054
 9055    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9056        let Some(project) = self.project.clone() else {
 9057            return;
 9058        };
 9059        self.reload(project, window, cx)
 9060            .detach_and_notify_err(window, cx);
 9061    }
 9062
 9063    pub fn restore_file(
 9064        &mut self,
 9065        _: &::git::RestoreFile,
 9066        window: &mut Window,
 9067        cx: &mut Context<Self>,
 9068    ) {
 9069        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9070        let mut buffer_ids = HashSet::default();
 9071        let snapshot = self.buffer().read(cx).snapshot(cx);
 9072        for selection in self.selections.all::<usize>(cx) {
 9073            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9074        }
 9075
 9076        let buffer = self.buffer().read(cx);
 9077        let ranges = buffer_ids
 9078            .into_iter()
 9079            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9080            .collect::<Vec<_>>();
 9081
 9082        self.restore_hunks_in_ranges(ranges, window, cx);
 9083    }
 9084
 9085    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9086        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9087        let selections = self
 9088            .selections
 9089            .all(cx)
 9090            .into_iter()
 9091            .map(|s| s.range())
 9092            .collect();
 9093        self.restore_hunks_in_ranges(selections, window, cx);
 9094    }
 9095
 9096    pub fn restore_hunks_in_ranges(
 9097        &mut self,
 9098        ranges: Vec<Range<Point>>,
 9099        window: &mut Window,
 9100        cx: &mut Context<Editor>,
 9101    ) {
 9102        let mut revert_changes = HashMap::default();
 9103        let chunk_by = self
 9104            .snapshot(window, cx)
 9105            .hunks_for_ranges(ranges)
 9106            .into_iter()
 9107            .chunk_by(|hunk| hunk.buffer_id);
 9108        for (buffer_id, hunks) in &chunk_by {
 9109            let hunks = hunks.collect::<Vec<_>>();
 9110            for hunk in &hunks {
 9111                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9112            }
 9113            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9114        }
 9115        drop(chunk_by);
 9116        if !revert_changes.is_empty() {
 9117            self.transact(window, cx, |editor, window, cx| {
 9118                editor.restore(revert_changes, window, cx);
 9119            });
 9120        }
 9121    }
 9122
 9123    pub fn open_active_item_in_terminal(
 9124        &mut self,
 9125        _: &OpenInTerminal,
 9126        window: &mut Window,
 9127        cx: &mut Context<Self>,
 9128    ) {
 9129        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9130            let project_path = buffer.read(cx).project_path(cx)?;
 9131            let project = self.project.as_ref()?.read(cx);
 9132            let entry = project.entry_for_path(&project_path, cx)?;
 9133            let parent = match &entry.canonical_path {
 9134                Some(canonical_path) => canonical_path.to_path_buf(),
 9135                None => project.absolute_path(&project_path, cx)?,
 9136            }
 9137            .parent()?
 9138            .to_path_buf();
 9139            Some(parent)
 9140        }) {
 9141            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9142        }
 9143    }
 9144
 9145    fn set_breakpoint_context_menu(
 9146        &mut self,
 9147        display_row: DisplayRow,
 9148        position: Option<Anchor>,
 9149        clicked_point: gpui::Point<Pixels>,
 9150        window: &mut Window,
 9151        cx: &mut Context<Self>,
 9152    ) {
 9153        if !cx.has_flag::<Debugger>() {
 9154            return;
 9155        }
 9156        let source = self
 9157            .buffer
 9158            .read(cx)
 9159            .snapshot(cx)
 9160            .anchor_before(Point::new(display_row.0, 0u32));
 9161
 9162        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9163
 9164        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9165            self,
 9166            source,
 9167            clicked_point,
 9168            context_menu,
 9169            window,
 9170            cx,
 9171        );
 9172    }
 9173
 9174    fn add_edit_breakpoint_block(
 9175        &mut self,
 9176        anchor: Anchor,
 9177        breakpoint: &Breakpoint,
 9178        edit_action: BreakpointPromptEditAction,
 9179        window: &mut Window,
 9180        cx: &mut Context<Self>,
 9181    ) {
 9182        let weak_editor = cx.weak_entity();
 9183        let bp_prompt = cx.new(|cx| {
 9184            BreakpointPromptEditor::new(
 9185                weak_editor,
 9186                anchor,
 9187                breakpoint.clone(),
 9188                edit_action,
 9189                window,
 9190                cx,
 9191            )
 9192        });
 9193
 9194        let height = bp_prompt.update(cx, |this, cx| {
 9195            this.prompt
 9196                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9197        });
 9198        let cloned_prompt = bp_prompt.clone();
 9199        let blocks = vec![BlockProperties {
 9200            style: BlockStyle::Sticky,
 9201            placement: BlockPlacement::Above(anchor),
 9202            height: Some(height),
 9203            render: Arc::new(move |cx| {
 9204                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9205                cloned_prompt.clone().into_any_element()
 9206            }),
 9207            priority: 0,
 9208        }];
 9209
 9210        let focus_handle = bp_prompt.focus_handle(cx);
 9211        window.focus(&focus_handle);
 9212
 9213        let block_ids = self.insert_blocks(blocks, None, cx);
 9214        bp_prompt.update(cx, |prompt, _| {
 9215            prompt.add_block_ids(block_ids);
 9216        });
 9217    }
 9218
 9219    pub(crate) fn breakpoint_at_row(
 9220        &self,
 9221        row: u32,
 9222        window: &mut Window,
 9223        cx: &mut Context<Self>,
 9224    ) -> Option<(Anchor, Breakpoint)> {
 9225        let snapshot = self.snapshot(window, cx);
 9226        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9227
 9228        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9229    }
 9230
 9231    pub(crate) fn breakpoint_at_anchor(
 9232        &self,
 9233        breakpoint_position: Anchor,
 9234        snapshot: &EditorSnapshot,
 9235        cx: &mut Context<Self>,
 9236    ) -> Option<(Anchor, Breakpoint)> {
 9237        let project = self.project.clone()?;
 9238
 9239        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9240            snapshot
 9241                .buffer_snapshot
 9242                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9243        })?;
 9244
 9245        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9246        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9247        let buffer_snapshot = buffer.read(cx).snapshot();
 9248
 9249        let row = buffer_snapshot
 9250            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9251            .row;
 9252
 9253        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9254        let anchor_end = snapshot
 9255            .buffer_snapshot
 9256            .anchor_after(Point::new(row, line_len));
 9257
 9258        let bp = self
 9259            .breakpoint_store
 9260            .as_ref()?
 9261            .read_with(cx, |breakpoint_store, cx| {
 9262                breakpoint_store
 9263                    .breakpoints(
 9264                        &buffer,
 9265                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9266                        &buffer_snapshot,
 9267                        cx,
 9268                    )
 9269                    .next()
 9270                    .and_then(|(anchor, bp)| {
 9271                        let breakpoint_row = buffer_snapshot
 9272                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9273                            .row;
 9274
 9275                        if breakpoint_row == row {
 9276                            snapshot
 9277                                .buffer_snapshot
 9278                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9279                                .map(|anchor| (anchor, bp.clone()))
 9280                        } else {
 9281                            None
 9282                        }
 9283                    })
 9284            });
 9285        bp
 9286    }
 9287
 9288    pub fn edit_log_breakpoint(
 9289        &mut self,
 9290        _: &EditLogBreakpoint,
 9291        window: &mut Window,
 9292        cx: &mut Context<Self>,
 9293    ) {
 9294        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9295            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9296                message: None,
 9297                state: BreakpointState::Enabled,
 9298                condition: None,
 9299                hit_condition: None,
 9300            });
 9301
 9302            self.add_edit_breakpoint_block(
 9303                anchor,
 9304                &breakpoint,
 9305                BreakpointPromptEditAction::Log,
 9306                window,
 9307                cx,
 9308            );
 9309        }
 9310    }
 9311
 9312    fn breakpoints_at_cursors(
 9313        &self,
 9314        window: &mut Window,
 9315        cx: &mut Context<Self>,
 9316    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9317        let snapshot = self.snapshot(window, cx);
 9318        let cursors = self
 9319            .selections
 9320            .disjoint_anchors()
 9321            .into_iter()
 9322            .map(|selection| {
 9323                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9324
 9325                let breakpoint_position = self
 9326                    .breakpoint_at_row(cursor_position.row, window, cx)
 9327                    .map(|bp| bp.0)
 9328                    .unwrap_or_else(|| {
 9329                        snapshot
 9330                            .display_snapshot
 9331                            .buffer_snapshot
 9332                            .anchor_after(Point::new(cursor_position.row, 0))
 9333                    });
 9334
 9335                let breakpoint = self
 9336                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9337                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9338
 9339                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9340            })
 9341            // 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.
 9342            .collect::<HashMap<Anchor, _>>();
 9343
 9344        cursors.into_iter().collect()
 9345    }
 9346
 9347    pub fn enable_breakpoint(
 9348        &mut self,
 9349        _: &crate::actions::EnableBreakpoint,
 9350        window: &mut Window,
 9351        cx: &mut Context<Self>,
 9352    ) {
 9353        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9354            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9355                continue;
 9356            };
 9357            self.edit_breakpoint_at_anchor(
 9358                anchor,
 9359                breakpoint,
 9360                BreakpointEditAction::InvertState,
 9361                cx,
 9362            );
 9363        }
 9364    }
 9365
 9366    pub fn disable_breakpoint(
 9367        &mut self,
 9368        _: &crate::actions::DisableBreakpoint,
 9369        window: &mut Window,
 9370        cx: &mut Context<Self>,
 9371    ) {
 9372        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9373            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9374                continue;
 9375            };
 9376            self.edit_breakpoint_at_anchor(
 9377                anchor,
 9378                breakpoint,
 9379                BreakpointEditAction::InvertState,
 9380                cx,
 9381            );
 9382        }
 9383    }
 9384
 9385    pub fn toggle_breakpoint(
 9386        &mut self,
 9387        _: &crate::actions::ToggleBreakpoint,
 9388        window: &mut Window,
 9389        cx: &mut Context<Self>,
 9390    ) {
 9391        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9392            if let Some(breakpoint) = breakpoint {
 9393                self.edit_breakpoint_at_anchor(
 9394                    anchor,
 9395                    breakpoint,
 9396                    BreakpointEditAction::Toggle,
 9397                    cx,
 9398                );
 9399            } else {
 9400                self.edit_breakpoint_at_anchor(
 9401                    anchor,
 9402                    Breakpoint::new_standard(),
 9403                    BreakpointEditAction::Toggle,
 9404                    cx,
 9405                );
 9406            }
 9407        }
 9408    }
 9409
 9410    pub fn edit_breakpoint_at_anchor(
 9411        &mut self,
 9412        breakpoint_position: Anchor,
 9413        breakpoint: Breakpoint,
 9414        edit_action: BreakpointEditAction,
 9415        cx: &mut Context<Self>,
 9416    ) {
 9417        let Some(breakpoint_store) = &self.breakpoint_store else {
 9418            return;
 9419        };
 9420
 9421        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9422            if breakpoint_position == Anchor::min() {
 9423                self.buffer()
 9424                    .read(cx)
 9425                    .excerpt_buffer_ids()
 9426                    .into_iter()
 9427                    .next()
 9428            } else {
 9429                None
 9430            }
 9431        }) else {
 9432            return;
 9433        };
 9434
 9435        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9436            return;
 9437        };
 9438
 9439        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9440            breakpoint_store.toggle_breakpoint(
 9441                buffer,
 9442                (breakpoint_position.text_anchor, breakpoint),
 9443                edit_action,
 9444                cx,
 9445            );
 9446        });
 9447
 9448        cx.notify();
 9449    }
 9450
 9451    #[cfg(any(test, feature = "test-support"))]
 9452    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9453        self.breakpoint_store.clone()
 9454    }
 9455
 9456    pub fn prepare_restore_change(
 9457        &self,
 9458        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9459        hunk: &MultiBufferDiffHunk,
 9460        cx: &mut App,
 9461    ) -> Option<()> {
 9462        if hunk.is_created_file() {
 9463            return None;
 9464        }
 9465        let buffer = self.buffer.read(cx);
 9466        let diff = buffer.diff_for(hunk.buffer_id)?;
 9467        let buffer = buffer.buffer(hunk.buffer_id)?;
 9468        let buffer = buffer.read(cx);
 9469        let original_text = diff
 9470            .read(cx)
 9471            .base_text()
 9472            .as_rope()
 9473            .slice(hunk.diff_base_byte_range.clone());
 9474        let buffer_snapshot = buffer.snapshot();
 9475        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9476        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9477            probe
 9478                .0
 9479                .start
 9480                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9481                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9482        }) {
 9483            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9484            Some(())
 9485        } else {
 9486            None
 9487        }
 9488    }
 9489
 9490    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9491        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9492    }
 9493
 9494    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9495        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9496    }
 9497
 9498    fn manipulate_lines<Fn>(
 9499        &mut self,
 9500        window: &mut Window,
 9501        cx: &mut Context<Self>,
 9502        mut callback: Fn,
 9503    ) where
 9504        Fn: FnMut(&mut Vec<&str>),
 9505    {
 9506        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9507
 9508        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9509        let buffer = self.buffer.read(cx).snapshot(cx);
 9510
 9511        let mut edits = Vec::new();
 9512
 9513        let selections = self.selections.all::<Point>(cx);
 9514        let mut selections = selections.iter().peekable();
 9515        let mut contiguous_row_selections = Vec::new();
 9516        let mut new_selections = Vec::new();
 9517        let mut added_lines = 0;
 9518        let mut removed_lines = 0;
 9519
 9520        while let Some(selection) = selections.next() {
 9521            let (start_row, end_row) = consume_contiguous_rows(
 9522                &mut contiguous_row_selections,
 9523                selection,
 9524                &display_map,
 9525                &mut selections,
 9526            );
 9527
 9528            let start_point = Point::new(start_row.0, 0);
 9529            let end_point = Point::new(
 9530                end_row.previous_row().0,
 9531                buffer.line_len(end_row.previous_row()),
 9532            );
 9533            let text = buffer
 9534                .text_for_range(start_point..end_point)
 9535                .collect::<String>();
 9536
 9537            let mut lines = text.split('\n').collect_vec();
 9538
 9539            let lines_before = lines.len();
 9540            callback(&mut lines);
 9541            let lines_after = lines.len();
 9542
 9543            edits.push((start_point..end_point, lines.join("\n")));
 9544
 9545            // Selections must change based on added and removed line count
 9546            let start_row =
 9547                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9548            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9549            new_selections.push(Selection {
 9550                id: selection.id,
 9551                start: start_row,
 9552                end: end_row,
 9553                goal: SelectionGoal::None,
 9554                reversed: selection.reversed,
 9555            });
 9556
 9557            if lines_after > lines_before {
 9558                added_lines += lines_after - lines_before;
 9559            } else if lines_before > lines_after {
 9560                removed_lines += lines_before - lines_after;
 9561            }
 9562        }
 9563
 9564        self.transact(window, cx, |this, window, cx| {
 9565            let buffer = this.buffer.update(cx, |buffer, cx| {
 9566                buffer.edit(edits, None, cx);
 9567                buffer.snapshot(cx)
 9568            });
 9569
 9570            // Recalculate offsets on newly edited buffer
 9571            let new_selections = new_selections
 9572                .iter()
 9573                .map(|s| {
 9574                    let start_point = Point::new(s.start.0, 0);
 9575                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9576                    Selection {
 9577                        id: s.id,
 9578                        start: buffer.point_to_offset(start_point),
 9579                        end: buffer.point_to_offset(end_point),
 9580                        goal: s.goal,
 9581                        reversed: s.reversed,
 9582                    }
 9583                })
 9584                .collect();
 9585
 9586            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9587                s.select(new_selections);
 9588            });
 9589
 9590            this.request_autoscroll(Autoscroll::fit(), cx);
 9591        });
 9592    }
 9593
 9594    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9595        self.manipulate_text(window, cx, |text| {
 9596            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9597            if has_upper_case_characters {
 9598                text.to_lowercase()
 9599            } else {
 9600                text.to_uppercase()
 9601            }
 9602        })
 9603    }
 9604
 9605    pub fn convert_to_upper_case(
 9606        &mut self,
 9607        _: &ConvertToUpperCase,
 9608        window: &mut Window,
 9609        cx: &mut Context<Self>,
 9610    ) {
 9611        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9612    }
 9613
 9614    pub fn convert_to_lower_case(
 9615        &mut self,
 9616        _: &ConvertToLowerCase,
 9617        window: &mut Window,
 9618        cx: &mut Context<Self>,
 9619    ) {
 9620        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9621    }
 9622
 9623    pub fn convert_to_title_case(
 9624        &mut self,
 9625        _: &ConvertToTitleCase,
 9626        window: &mut Window,
 9627        cx: &mut Context<Self>,
 9628    ) {
 9629        self.manipulate_text(window, cx, |text| {
 9630            text.split('\n')
 9631                .map(|line| line.to_case(Case::Title))
 9632                .join("\n")
 9633        })
 9634    }
 9635
 9636    pub fn convert_to_snake_case(
 9637        &mut self,
 9638        _: &ConvertToSnakeCase,
 9639        window: &mut Window,
 9640        cx: &mut Context<Self>,
 9641    ) {
 9642        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9643    }
 9644
 9645    pub fn convert_to_kebab_case(
 9646        &mut self,
 9647        _: &ConvertToKebabCase,
 9648        window: &mut Window,
 9649        cx: &mut Context<Self>,
 9650    ) {
 9651        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9652    }
 9653
 9654    pub fn convert_to_upper_camel_case(
 9655        &mut self,
 9656        _: &ConvertToUpperCamelCase,
 9657        window: &mut Window,
 9658        cx: &mut Context<Self>,
 9659    ) {
 9660        self.manipulate_text(window, cx, |text| {
 9661            text.split('\n')
 9662                .map(|line| line.to_case(Case::UpperCamel))
 9663                .join("\n")
 9664        })
 9665    }
 9666
 9667    pub fn convert_to_lower_camel_case(
 9668        &mut self,
 9669        _: &ConvertToLowerCamelCase,
 9670        window: &mut Window,
 9671        cx: &mut Context<Self>,
 9672    ) {
 9673        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9674    }
 9675
 9676    pub fn convert_to_opposite_case(
 9677        &mut self,
 9678        _: &ConvertToOppositeCase,
 9679        window: &mut Window,
 9680        cx: &mut Context<Self>,
 9681    ) {
 9682        self.manipulate_text(window, cx, |text| {
 9683            text.chars()
 9684                .fold(String::with_capacity(text.len()), |mut t, c| {
 9685                    if c.is_uppercase() {
 9686                        t.extend(c.to_lowercase());
 9687                    } else {
 9688                        t.extend(c.to_uppercase());
 9689                    }
 9690                    t
 9691                })
 9692        })
 9693    }
 9694
 9695    pub fn convert_to_rot13(
 9696        &mut self,
 9697        _: &ConvertToRot13,
 9698        window: &mut Window,
 9699        cx: &mut Context<Self>,
 9700    ) {
 9701        self.manipulate_text(window, cx, |text| {
 9702            text.chars()
 9703                .map(|c| match c {
 9704                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9705                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9706                    _ => c,
 9707                })
 9708                .collect()
 9709        })
 9710    }
 9711
 9712    pub fn convert_to_rot47(
 9713        &mut self,
 9714        _: &ConvertToRot47,
 9715        window: &mut Window,
 9716        cx: &mut Context<Self>,
 9717    ) {
 9718        self.manipulate_text(window, cx, |text| {
 9719            text.chars()
 9720                .map(|c| {
 9721                    let code_point = c as u32;
 9722                    if code_point >= 33 && code_point <= 126 {
 9723                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9724                    }
 9725                    c
 9726                })
 9727                .collect()
 9728        })
 9729    }
 9730
 9731    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9732    where
 9733        Fn: FnMut(&str) -> String,
 9734    {
 9735        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9736        let buffer = self.buffer.read(cx).snapshot(cx);
 9737
 9738        let mut new_selections = Vec::new();
 9739        let mut edits = Vec::new();
 9740        let mut selection_adjustment = 0i32;
 9741
 9742        for selection in self.selections.all::<usize>(cx) {
 9743            let selection_is_empty = selection.is_empty();
 9744
 9745            let (start, end) = if selection_is_empty {
 9746                let word_range = movement::surrounding_word(
 9747                    &display_map,
 9748                    selection.start.to_display_point(&display_map),
 9749                );
 9750                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9751                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9752                (start, end)
 9753            } else {
 9754                (selection.start, selection.end)
 9755            };
 9756
 9757            let text = buffer.text_for_range(start..end).collect::<String>();
 9758            let old_length = text.len() as i32;
 9759            let text = callback(&text);
 9760
 9761            new_selections.push(Selection {
 9762                start: (start as i32 - selection_adjustment) as usize,
 9763                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9764                goal: SelectionGoal::None,
 9765                ..selection
 9766            });
 9767
 9768            selection_adjustment += old_length - text.len() as i32;
 9769
 9770            edits.push((start..end, text));
 9771        }
 9772
 9773        self.transact(window, cx, |this, window, cx| {
 9774            this.buffer.update(cx, |buffer, cx| {
 9775                buffer.edit(edits, None, cx);
 9776            });
 9777
 9778            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9779                s.select(new_selections);
 9780            });
 9781
 9782            this.request_autoscroll(Autoscroll::fit(), cx);
 9783        });
 9784    }
 9785
 9786    pub fn duplicate(
 9787        &mut self,
 9788        upwards: bool,
 9789        whole_lines: bool,
 9790        window: &mut Window,
 9791        cx: &mut Context<Self>,
 9792    ) {
 9793        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9794
 9795        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9796        let buffer = &display_map.buffer_snapshot;
 9797        let selections = self.selections.all::<Point>(cx);
 9798
 9799        let mut edits = Vec::new();
 9800        let mut selections_iter = selections.iter().peekable();
 9801        while let Some(selection) = selections_iter.next() {
 9802            let mut rows = selection.spanned_rows(false, &display_map);
 9803            // duplicate line-wise
 9804            if whole_lines || selection.start == selection.end {
 9805                // Avoid duplicating the same lines twice.
 9806                while let Some(next_selection) = selections_iter.peek() {
 9807                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9808                    if next_rows.start < rows.end {
 9809                        rows.end = next_rows.end;
 9810                        selections_iter.next().unwrap();
 9811                    } else {
 9812                        break;
 9813                    }
 9814                }
 9815
 9816                // Copy the text from the selected row region and splice it either at the start
 9817                // or end of the region.
 9818                let start = Point::new(rows.start.0, 0);
 9819                let end = Point::new(
 9820                    rows.end.previous_row().0,
 9821                    buffer.line_len(rows.end.previous_row()),
 9822                );
 9823                let text = buffer
 9824                    .text_for_range(start..end)
 9825                    .chain(Some("\n"))
 9826                    .collect::<String>();
 9827                let insert_location = if upwards {
 9828                    Point::new(rows.end.0, 0)
 9829                } else {
 9830                    start
 9831                };
 9832                edits.push((insert_location..insert_location, text));
 9833            } else {
 9834                // duplicate character-wise
 9835                let start = selection.start;
 9836                let end = selection.end;
 9837                let text = buffer.text_for_range(start..end).collect::<String>();
 9838                edits.push((selection.end..selection.end, text));
 9839            }
 9840        }
 9841
 9842        self.transact(window, cx, |this, _, cx| {
 9843            this.buffer.update(cx, |buffer, cx| {
 9844                buffer.edit(edits, None, cx);
 9845            });
 9846
 9847            this.request_autoscroll(Autoscroll::fit(), cx);
 9848        });
 9849    }
 9850
 9851    pub fn duplicate_line_up(
 9852        &mut self,
 9853        _: &DuplicateLineUp,
 9854        window: &mut Window,
 9855        cx: &mut Context<Self>,
 9856    ) {
 9857        self.duplicate(true, true, window, cx);
 9858    }
 9859
 9860    pub fn duplicate_line_down(
 9861        &mut self,
 9862        _: &DuplicateLineDown,
 9863        window: &mut Window,
 9864        cx: &mut Context<Self>,
 9865    ) {
 9866        self.duplicate(false, true, window, cx);
 9867    }
 9868
 9869    pub fn duplicate_selection(
 9870        &mut self,
 9871        _: &DuplicateSelection,
 9872        window: &mut Window,
 9873        cx: &mut Context<Self>,
 9874    ) {
 9875        self.duplicate(false, false, window, cx);
 9876    }
 9877
 9878    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9879        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9880
 9881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9882        let buffer = self.buffer.read(cx).snapshot(cx);
 9883
 9884        let mut edits = Vec::new();
 9885        let mut unfold_ranges = Vec::new();
 9886        let mut refold_creases = Vec::new();
 9887
 9888        let selections = self.selections.all::<Point>(cx);
 9889        let mut selections = selections.iter().peekable();
 9890        let mut contiguous_row_selections = Vec::new();
 9891        let mut new_selections = Vec::new();
 9892
 9893        while let Some(selection) = selections.next() {
 9894            // Find all the selections that span a contiguous row range
 9895            let (start_row, end_row) = consume_contiguous_rows(
 9896                &mut contiguous_row_selections,
 9897                selection,
 9898                &display_map,
 9899                &mut selections,
 9900            );
 9901
 9902            // Move the text spanned by the row range to be before the line preceding the row range
 9903            if start_row.0 > 0 {
 9904                let range_to_move = Point::new(
 9905                    start_row.previous_row().0,
 9906                    buffer.line_len(start_row.previous_row()),
 9907                )
 9908                    ..Point::new(
 9909                        end_row.previous_row().0,
 9910                        buffer.line_len(end_row.previous_row()),
 9911                    );
 9912                let insertion_point = display_map
 9913                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9914                    .0;
 9915
 9916                // Don't move lines across excerpts
 9917                if buffer
 9918                    .excerpt_containing(insertion_point..range_to_move.end)
 9919                    .is_some()
 9920                {
 9921                    let text = buffer
 9922                        .text_for_range(range_to_move.clone())
 9923                        .flat_map(|s| s.chars())
 9924                        .skip(1)
 9925                        .chain(['\n'])
 9926                        .collect::<String>();
 9927
 9928                    edits.push((
 9929                        buffer.anchor_after(range_to_move.start)
 9930                            ..buffer.anchor_before(range_to_move.end),
 9931                        String::new(),
 9932                    ));
 9933                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9934                    edits.push((insertion_anchor..insertion_anchor, text));
 9935
 9936                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9937
 9938                    // Move selections up
 9939                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9940                        |mut selection| {
 9941                            selection.start.row -= row_delta;
 9942                            selection.end.row -= row_delta;
 9943                            selection
 9944                        },
 9945                    ));
 9946
 9947                    // Move folds up
 9948                    unfold_ranges.push(range_to_move.clone());
 9949                    for fold in display_map.folds_in_range(
 9950                        buffer.anchor_before(range_to_move.start)
 9951                            ..buffer.anchor_after(range_to_move.end),
 9952                    ) {
 9953                        let mut start = fold.range.start.to_point(&buffer);
 9954                        let mut end = fold.range.end.to_point(&buffer);
 9955                        start.row -= row_delta;
 9956                        end.row -= row_delta;
 9957                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9958                    }
 9959                }
 9960            }
 9961
 9962            // If we didn't move line(s), preserve the existing selections
 9963            new_selections.append(&mut contiguous_row_selections);
 9964        }
 9965
 9966        self.transact(window, cx, |this, window, cx| {
 9967            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9968            this.buffer.update(cx, |buffer, cx| {
 9969                for (range, text) in edits {
 9970                    buffer.edit([(range, text)], None, cx);
 9971                }
 9972            });
 9973            this.fold_creases(refold_creases, true, window, cx);
 9974            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9975                s.select(new_selections);
 9976            })
 9977        });
 9978    }
 9979
 9980    pub fn move_line_down(
 9981        &mut self,
 9982        _: &MoveLineDown,
 9983        window: &mut Window,
 9984        cx: &mut Context<Self>,
 9985    ) {
 9986        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9987
 9988        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9989        let buffer = self.buffer.read(cx).snapshot(cx);
 9990
 9991        let mut edits = Vec::new();
 9992        let mut unfold_ranges = Vec::new();
 9993        let mut refold_creases = Vec::new();
 9994
 9995        let selections = self.selections.all::<Point>(cx);
 9996        let mut selections = selections.iter().peekable();
 9997        let mut contiguous_row_selections = Vec::new();
 9998        let mut new_selections = Vec::new();
 9999
10000        while let Some(selection) = selections.next() {
10001            // Find all the selections that span a contiguous row range
10002            let (start_row, end_row) = consume_contiguous_rows(
10003                &mut contiguous_row_selections,
10004                selection,
10005                &display_map,
10006                &mut selections,
10007            );
10008
10009            // Move the text spanned by the row range to be after the last line of the row range
10010            if end_row.0 <= buffer.max_point().row {
10011                let range_to_move =
10012                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10013                let insertion_point = display_map
10014                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10015                    .0;
10016
10017                // Don't move lines across excerpt boundaries
10018                if buffer
10019                    .excerpt_containing(range_to_move.start..insertion_point)
10020                    .is_some()
10021                {
10022                    let mut text = String::from("\n");
10023                    text.extend(buffer.text_for_range(range_to_move.clone()));
10024                    text.pop(); // Drop trailing newline
10025                    edits.push((
10026                        buffer.anchor_after(range_to_move.start)
10027                            ..buffer.anchor_before(range_to_move.end),
10028                        String::new(),
10029                    ));
10030                    let insertion_anchor = buffer.anchor_after(insertion_point);
10031                    edits.push((insertion_anchor..insertion_anchor, text));
10032
10033                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10034
10035                    // Move selections down
10036                    new_selections.extend(contiguous_row_selections.drain(..).map(
10037                        |mut selection| {
10038                            selection.start.row += row_delta;
10039                            selection.end.row += row_delta;
10040                            selection
10041                        },
10042                    ));
10043
10044                    // Move folds down
10045                    unfold_ranges.push(range_to_move.clone());
10046                    for fold in display_map.folds_in_range(
10047                        buffer.anchor_before(range_to_move.start)
10048                            ..buffer.anchor_after(range_to_move.end),
10049                    ) {
10050                        let mut start = fold.range.start.to_point(&buffer);
10051                        let mut end = fold.range.end.to_point(&buffer);
10052                        start.row += row_delta;
10053                        end.row += row_delta;
10054                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10055                    }
10056                }
10057            }
10058
10059            // If we didn't move line(s), preserve the existing selections
10060            new_selections.append(&mut contiguous_row_selections);
10061        }
10062
10063        self.transact(window, cx, |this, window, cx| {
10064            this.unfold_ranges(&unfold_ranges, true, true, cx);
10065            this.buffer.update(cx, |buffer, cx| {
10066                for (range, text) in edits {
10067                    buffer.edit([(range, text)], None, cx);
10068                }
10069            });
10070            this.fold_creases(refold_creases, true, window, cx);
10071            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10072                s.select(new_selections)
10073            });
10074        });
10075    }
10076
10077    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10078        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10079        let text_layout_details = &self.text_layout_details(window);
10080        self.transact(window, cx, |this, window, cx| {
10081            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10082                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10083                s.move_with(|display_map, selection| {
10084                    if !selection.is_empty() {
10085                        return;
10086                    }
10087
10088                    let mut head = selection.head();
10089                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10090                    if head.column() == display_map.line_len(head.row()) {
10091                        transpose_offset = display_map
10092                            .buffer_snapshot
10093                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10094                    }
10095
10096                    if transpose_offset == 0 {
10097                        return;
10098                    }
10099
10100                    *head.column_mut() += 1;
10101                    head = display_map.clip_point(head, Bias::Right);
10102                    let goal = SelectionGoal::HorizontalPosition(
10103                        display_map
10104                            .x_for_display_point(head, text_layout_details)
10105                            .into(),
10106                    );
10107                    selection.collapse_to(head, goal);
10108
10109                    let transpose_start = display_map
10110                        .buffer_snapshot
10111                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10112                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10113                        let transpose_end = display_map
10114                            .buffer_snapshot
10115                            .clip_offset(transpose_offset + 1, Bias::Right);
10116                        if let Some(ch) =
10117                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10118                        {
10119                            edits.push((transpose_start..transpose_offset, String::new()));
10120                            edits.push((transpose_end..transpose_end, ch.to_string()));
10121                        }
10122                    }
10123                });
10124                edits
10125            });
10126            this.buffer
10127                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10128            let selections = this.selections.all::<usize>(cx);
10129            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10130                s.select(selections);
10131            });
10132        });
10133    }
10134
10135    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10136        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10137        self.rewrap_impl(RewrapOptions::default(), cx)
10138    }
10139
10140    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10141        let buffer = self.buffer.read(cx).snapshot(cx);
10142        let selections = self.selections.all::<Point>(cx);
10143        let mut selections = selections.iter().peekable();
10144
10145        let mut edits = Vec::new();
10146        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10147
10148        while let Some(selection) = selections.next() {
10149            let mut start_row = selection.start.row;
10150            let mut end_row = selection.end.row;
10151
10152            // Skip selections that overlap with a range that has already been rewrapped.
10153            let selection_range = start_row..end_row;
10154            if rewrapped_row_ranges
10155                .iter()
10156                .any(|range| range.overlaps(&selection_range))
10157            {
10158                continue;
10159            }
10160
10161            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10162
10163            // Since not all lines in the selection may be at the same indent
10164            // level, choose the indent size that is the most common between all
10165            // of the lines.
10166            //
10167            // If there is a tie, we use the deepest indent.
10168            let (indent_size, indent_end) = {
10169                let mut indent_size_occurrences = HashMap::default();
10170                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10171
10172                for row in start_row..=end_row {
10173                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10174                    rows_by_indent_size.entry(indent).or_default().push(row);
10175                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10176                }
10177
10178                let indent_size = indent_size_occurrences
10179                    .into_iter()
10180                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10181                    .map(|(indent, _)| indent)
10182                    .unwrap_or_default();
10183                let row = rows_by_indent_size[&indent_size][0];
10184                let indent_end = Point::new(row, indent_size.len);
10185
10186                (indent_size, indent_end)
10187            };
10188
10189            let mut line_prefix = indent_size.chars().collect::<String>();
10190
10191            let mut inside_comment = false;
10192            if let Some(comment_prefix) =
10193                buffer
10194                    .language_scope_at(selection.head())
10195                    .and_then(|language| {
10196                        language
10197                            .line_comment_prefixes()
10198                            .iter()
10199                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10200                            .cloned()
10201                    })
10202            {
10203                line_prefix.push_str(&comment_prefix);
10204                inside_comment = true;
10205            }
10206
10207            let language_settings = buffer.language_settings_at(selection.head(), cx);
10208            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10209                RewrapBehavior::InComments => inside_comment,
10210                RewrapBehavior::InSelections => !selection.is_empty(),
10211                RewrapBehavior::Anywhere => true,
10212            };
10213
10214            let should_rewrap = options.override_language_settings
10215                || allow_rewrap_based_on_language
10216                || self.hard_wrap.is_some();
10217            if !should_rewrap {
10218                continue;
10219            }
10220
10221            if selection.is_empty() {
10222                'expand_upwards: while start_row > 0 {
10223                    let prev_row = start_row - 1;
10224                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10225                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10226                    {
10227                        start_row = prev_row;
10228                    } else {
10229                        break 'expand_upwards;
10230                    }
10231                }
10232
10233                'expand_downwards: while end_row < buffer.max_point().row {
10234                    let next_row = end_row + 1;
10235                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10236                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10237                    {
10238                        end_row = next_row;
10239                    } else {
10240                        break 'expand_downwards;
10241                    }
10242                }
10243            }
10244
10245            let start = Point::new(start_row, 0);
10246            let start_offset = start.to_offset(&buffer);
10247            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10248            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10249            let Some(lines_without_prefixes) = selection_text
10250                .lines()
10251                .map(|line| {
10252                    line.strip_prefix(&line_prefix)
10253                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10254                        .ok_or_else(|| {
10255                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10256                        })
10257                })
10258                .collect::<Result<Vec<_>, _>>()
10259                .log_err()
10260            else {
10261                continue;
10262            };
10263
10264            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10265                buffer
10266                    .language_settings_at(Point::new(start_row, 0), cx)
10267                    .preferred_line_length as usize
10268            });
10269            let wrapped_text = wrap_with_prefix(
10270                line_prefix,
10271                lines_without_prefixes.join("\n"),
10272                wrap_column,
10273                tab_size,
10274                options.preserve_existing_whitespace,
10275            );
10276
10277            // TODO: should always use char-based diff while still supporting cursor behavior that
10278            // matches vim.
10279            let mut diff_options = DiffOptions::default();
10280            if options.override_language_settings {
10281                diff_options.max_word_diff_len = 0;
10282                diff_options.max_word_diff_line_count = 0;
10283            } else {
10284                diff_options.max_word_diff_len = usize::MAX;
10285                diff_options.max_word_diff_line_count = usize::MAX;
10286            }
10287
10288            for (old_range, new_text) in
10289                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10290            {
10291                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10292                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10293                edits.push((edit_start..edit_end, new_text));
10294            }
10295
10296            rewrapped_row_ranges.push(start_row..=end_row);
10297        }
10298
10299        self.buffer
10300            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10301    }
10302
10303    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10304        let mut text = String::new();
10305        let buffer = self.buffer.read(cx).snapshot(cx);
10306        let mut selections = self.selections.all::<Point>(cx);
10307        let mut clipboard_selections = Vec::with_capacity(selections.len());
10308        {
10309            let max_point = buffer.max_point();
10310            let mut is_first = true;
10311            for selection in &mut selections {
10312                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10313                if is_entire_line {
10314                    selection.start = Point::new(selection.start.row, 0);
10315                    if !selection.is_empty() && selection.end.column == 0 {
10316                        selection.end = cmp::min(max_point, selection.end);
10317                    } else {
10318                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10319                    }
10320                    selection.goal = SelectionGoal::None;
10321                }
10322                if is_first {
10323                    is_first = false;
10324                } else {
10325                    text += "\n";
10326                }
10327                let mut len = 0;
10328                for chunk in buffer.text_for_range(selection.start..selection.end) {
10329                    text.push_str(chunk);
10330                    len += chunk.len();
10331                }
10332                clipboard_selections.push(ClipboardSelection {
10333                    len,
10334                    is_entire_line,
10335                    first_line_indent: buffer
10336                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10337                        .len,
10338                });
10339            }
10340        }
10341
10342        self.transact(window, cx, |this, window, cx| {
10343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10344                s.select(selections);
10345            });
10346            this.insert("", window, cx);
10347        });
10348        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10349    }
10350
10351    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10352        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10353        let item = self.cut_common(window, cx);
10354        cx.write_to_clipboard(item);
10355    }
10356
10357    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10358        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10359        self.change_selections(None, window, cx, |s| {
10360            s.move_with(|snapshot, sel| {
10361                if sel.is_empty() {
10362                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10363                }
10364            });
10365        });
10366        let item = self.cut_common(window, cx);
10367        cx.set_global(KillRing(item))
10368    }
10369
10370    pub fn kill_ring_yank(
10371        &mut self,
10372        _: &KillRingYank,
10373        window: &mut Window,
10374        cx: &mut Context<Self>,
10375    ) {
10376        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10377        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10378            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10379                (kill_ring.text().to_string(), kill_ring.metadata_json())
10380            } else {
10381                return;
10382            }
10383        } else {
10384            return;
10385        };
10386        self.do_paste(&text, metadata, false, window, cx);
10387    }
10388
10389    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10390        self.do_copy(true, cx);
10391    }
10392
10393    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10394        self.do_copy(false, cx);
10395    }
10396
10397    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10398        let selections = self.selections.all::<Point>(cx);
10399        let buffer = self.buffer.read(cx).read(cx);
10400        let mut text = String::new();
10401
10402        let mut clipboard_selections = Vec::with_capacity(selections.len());
10403        {
10404            let max_point = buffer.max_point();
10405            let mut is_first = true;
10406            for selection in &selections {
10407                let mut start = selection.start;
10408                let mut end = selection.end;
10409                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10410                if is_entire_line {
10411                    start = Point::new(start.row, 0);
10412                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10413                }
10414
10415                let mut trimmed_selections = Vec::new();
10416                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10417                    let row = MultiBufferRow(start.row);
10418                    let first_indent = buffer.indent_size_for_line(row);
10419                    if first_indent.len == 0 || start.column > first_indent.len {
10420                        trimmed_selections.push(start..end);
10421                    } else {
10422                        trimmed_selections.push(
10423                            Point::new(row.0, first_indent.len)
10424                                ..Point::new(row.0, buffer.line_len(row)),
10425                        );
10426                        for row in start.row + 1..=end.row {
10427                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10428                            if row == end.row {
10429                                line_len = end.column;
10430                            }
10431                            if line_len == 0 {
10432                                trimmed_selections
10433                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10434                                continue;
10435                            }
10436                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10437                            if row_indent_size.len >= first_indent.len {
10438                                trimmed_selections.push(
10439                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10440                                );
10441                            } else {
10442                                trimmed_selections.clear();
10443                                trimmed_selections.push(start..end);
10444                                break;
10445                            }
10446                        }
10447                    }
10448                } else {
10449                    trimmed_selections.push(start..end);
10450                }
10451
10452                for trimmed_range in trimmed_selections {
10453                    if is_first {
10454                        is_first = false;
10455                    } else {
10456                        text += "\n";
10457                    }
10458                    let mut len = 0;
10459                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10460                        text.push_str(chunk);
10461                        len += chunk.len();
10462                    }
10463                    clipboard_selections.push(ClipboardSelection {
10464                        len,
10465                        is_entire_line,
10466                        first_line_indent: buffer
10467                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10468                            .len,
10469                    });
10470                }
10471            }
10472        }
10473
10474        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10475            text,
10476            clipboard_selections,
10477        ));
10478    }
10479
10480    pub fn do_paste(
10481        &mut self,
10482        text: &String,
10483        clipboard_selections: Option<Vec<ClipboardSelection>>,
10484        handle_entire_lines: bool,
10485        window: &mut Window,
10486        cx: &mut Context<Self>,
10487    ) {
10488        if self.read_only(cx) {
10489            return;
10490        }
10491
10492        let clipboard_text = Cow::Borrowed(text);
10493
10494        self.transact(window, cx, |this, window, cx| {
10495            if let Some(mut clipboard_selections) = clipboard_selections {
10496                let old_selections = this.selections.all::<usize>(cx);
10497                let all_selections_were_entire_line =
10498                    clipboard_selections.iter().all(|s| s.is_entire_line);
10499                let first_selection_indent_column =
10500                    clipboard_selections.first().map(|s| s.first_line_indent);
10501                if clipboard_selections.len() != old_selections.len() {
10502                    clipboard_selections.drain(..);
10503                }
10504                let cursor_offset = this.selections.last::<usize>(cx).head();
10505                let mut auto_indent_on_paste = true;
10506
10507                this.buffer.update(cx, |buffer, cx| {
10508                    let snapshot = buffer.read(cx);
10509                    auto_indent_on_paste = snapshot
10510                        .language_settings_at(cursor_offset, cx)
10511                        .auto_indent_on_paste;
10512
10513                    let mut start_offset = 0;
10514                    let mut edits = Vec::new();
10515                    let mut original_indent_columns = Vec::new();
10516                    for (ix, selection) in old_selections.iter().enumerate() {
10517                        let to_insert;
10518                        let entire_line;
10519                        let original_indent_column;
10520                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10521                            let end_offset = start_offset + clipboard_selection.len;
10522                            to_insert = &clipboard_text[start_offset..end_offset];
10523                            entire_line = clipboard_selection.is_entire_line;
10524                            start_offset = end_offset + 1;
10525                            original_indent_column = Some(clipboard_selection.first_line_indent);
10526                        } else {
10527                            to_insert = clipboard_text.as_str();
10528                            entire_line = all_selections_were_entire_line;
10529                            original_indent_column = first_selection_indent_column
10530                        }
10531
10532                        // If the corresponding selection was empty when this slice of the
10533                        // clipboard text was written, then the entire line containing the
10534                        // selection was copied. If this selection is also currently empty,
10535                        // then paste the line before the current line of the buffer.
10536                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10537                            let column = selection.start.to_point(&snapshot).column as usize;
10538                            let line_start = selection.start - column;
10539                            line_start..line_start
10540                        } else {
10541                            selection.range()
10542                        };
10543
10544                        edits.push((range, to_insert));
10545                        original_indent_columns.push(original_indent_column);
10546                    }
10547                    drop(snapshot);
10548
10549                    buffer.edit(
10550                        edits,
10551                        if auto_indent_on_paste {
10552                            Some(AutoindentMode::Block {
10553                                original_indent_columns,
10554                            })
10555                        } else {
10556                            None
10557                        },
10558                        cx,
10559                    );
10560                });
10561
10562                let selections = this.selections.all::<usize>(cx);
10563                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10564                    s.select(selections)
10565                });
10566            } else {
10567                this.insert(&clipboard_text, window, cx);
10568            }
10569        });
10570    }
10571
10572    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10573        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10574        if let Some(item) = cx.read_from_clipboard() {
10575            let entries = item.entries();
10576
10577            match entries.first() {
10578                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10579                // of all the pasted entries.
10580                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10581                    .do_paste(
10582                        clipboard_string.text(),
10583                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10584                        true,
10585                        window,
10586                        cx,
10587                    ),
10588                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10589            }
10590        }
10591    }
10592
10593    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10594        if self.read_only(cx) {
10595            return;
10596        }
10597
10598        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10599
10600        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10601            if let Some((selections, _)) =
10602                self.selection_history.transaction(transaction_id).cloned()
10603            {
10604                self.change_selections(None, window, cx, |s| {
10605                    s.select_anchors(selections.to_vec());
10606                });
10607            } else {
10608                log::error!(
10609                    "No entry in selection_history found for undo. \
10610                     This may correspond to a bug where undo does not update the selection. \
10611                     If this is occurring, please add details to \
10612                     https://github.com/zed-industries/zed/issues/22692"
10613                );
10614            }
10615            self.request_autoscroll(Autoscroll::fit(), cx);
10616            self.unmark_text(window, cx);
10617            self.refresh_inline_completion(true, false, window, cx);
10618            cx.emit(EditorEvent::Edited { transaction_id });
10619            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10620        }
10621    }
10622
10623    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10624        if self.read_only(cx) {
10625            return;
10626        }
10627
10628        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10629
10630        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10631            if let Some((_, Some(selections))) =
10632                self.selection_history.transaction(transaction_id).cloned()
10633            {
10634                self.change_selections(None, window, cx, |s| {
10635                    s.select_anchors(selections.to_vec());
10636                });
10637            } else {
10638                log::error!(
10639                    "No entry in selection_history found for redo. \
10640                     This may correspond to a bug where undo does not update the selection. \
10641                     If this is occurring, please add details to \
10642                     https://github.com/zed-industries/zed/issues/22692"
10643                );
10644            }
10645            self.request_autoscroll(Autoscroll::fit(), cx);
10646            self.unmark_text(window, cx);
10647            self.refresh_inline_completion(true, false, window, cx);
10648            cx.emit(EditorEvent::Edited { transaction_id });
10649        }
10650    }
10651
10652    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10653        self.buffer
10654            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10655    }
10656
10657    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10658        self.buffer
10659            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10660    }
10661
10662    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10663        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10664        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10665            s.move_with(|map, selection| {
10666                let cursor = if selection.is_empty() {
10667                    movement::left(map, selection.start)
10668                } else {
10669                    selection.start
10670                };
10671                selection.collapse_to(cursor, SelectionGoal::None);
10672            });
10673        })
10674    }
10675
10676    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10677        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10678        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10679            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10680        })
10681    }
10682
10683    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10684        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10685        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686            s.move_with(|map, selection| {
10687                let cursor = if selection.is_empty() {
10688                    movement::right(map, selection.end)
10689                } else {
10690                    selection.end
10691                };
10692                selection.collapse_to(cursor, SelectionGoal::None)
10693            });
10694        })
10695    }
10696
10697    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10698        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10699        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10700            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10701        })
10702    }
10703
10704    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10705        if self.take_rename(true, window, cx).is_some() {
10706            return;
10707        }
10708
10709        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10710            cx.propagate();
10711            return;
10712        }
10713
10714        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10715
10716        let text_layout_details = &self.text_layout_details(window);
10717        let selection_count = self.selections.count();
10718        let first_selection = self.selections.first_anchor();
10719
10720        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10721            s.move_with(|map, selection| {
10722                if !selection.is_empty() {
10723                    selection.goal = SelectionGoal::None;
10724                }
10725                let (cursor, goal) = movement::up(
10726                    map,
10727                    selection.start,
10728                    selection.goal,
10729                    false,
10730                    text_layout_details,
10731                );
10732                selection.collapse_to(cursor, goal);
10733            });
10734        });
10735
10736        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10737        {
10738            cx.propagate();
10739        }
10740    }
10741
10742    pub fn move_up_by_lines(
10743        &mut self,
10744        action: &MoveUpByLines,
10745        window: &mut Window,
10746        cx: &mut Context<Self>,
10747    ) {
10748        if self.take_rename(true, window, cx).is_some() {
10749            return;
10750        }
10751
10752        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10753            cx.propagate();
10754            return;
10755        }
10756
10757        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10758
10759        let text_layout_details = &self.text_layout_details(window);
10760
10761        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10762            s.move_with(|map, selection| {
10763                if !selection.is_empty() {
10764                    selection.goal = SelectionGoal::None;
10765                }
10766                let (cursor, goal) = movement::up_by_rows(
10767                    map,
10768                    selection.start,
10769                    action.lines,
10770                    selection.goal,
10771                    false,
10772                    text_layout_details,
10773                );
10774                selection.collapse_to(cursor, goal);
10775            });
10776        })
10777    }
10778
10779    pub fn move_down_by_lines(
10780        &mut self,
10781        action: &MoveDownByLines,
10782        window: &mut Window,
10783        cx: &mut Context<Self>,
10784    ) {
10785        if self.take_rename(true, window, cx).is_some() {
10786            return;
10787        }
10788
10789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10790            cx.propagate();
10791            return;
10792        }
10793
10794        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10795
10796        let text_layout_details = &self.text_layout_details(window);
10797
10798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10799            s.move_with(|map, selection| {
10800                if !selection.is_empty() {
10801                    selection.goal = SelectionGoal::None;
10802                }
10803                let (cursor, goal) = movement::down_by_rows(
10804                    map,
10805                    selection.start,
10806                    action.lines,
10807                    selection.goal,
10808                    false,
10809                    text_layout_details,
10810                );
10811                selection.collapse_to(cursor, goal);
10812            });
10813        })
10814    }
10815
10816    pub fn select_down_by_lines(
10817        &mut self,
10818        action: &SelectDownByLines,
10819        window: &mut Window,
10820        cx: &mut Context<Self>,
10821    ) {
10822        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10823        let text_layout_details = &self.text_layout_details(window);
10824        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10825            s.move_heads_with(|map, head, goal| {
10826                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10827            })
10828        })
10829    }
10830
10831    pub fn select_up_by_lines(
10832        &mut self,
10833        action: &SelectUpByLines,
10834        window: &mut Window,
10835        cx: &mut Context<Self>,
10836    ) {
10837        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10838        let text_layout_details = &self.text_layout_details(window);
10839        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840            s.move_heads_with(|map, head, goal| {
10841                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10842            })
10843        })
10844    }
10845
10846    pub fn select_page_up(
10847        &mut self,
10848        _: &SelectPageUp,
10849        window: &mut Window,
10850        cx: &mut Context<Self>,
10851    ) {
10852        let Some(row_count) = self.visible_row_count() else {
10853            return;
10854        };
10855
10856        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10857
10858        let text_layout_details = &self.text_layout_details(window);
10859
10860        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10861            s.move_heads_with(|map, head, goal| {
10862                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10863            })
10864        })
10865    }
10866
10867    pub fn move_page_up(
10868        &mut self,
10869        action: &MovePageUp,
10870        window: &mut Window,
10871        cx: &mut Context<Self>,
10872    ) {
10873        if self.take_rename(true, window, cx).is_some() {
10874            return;
10875        }
10876
10877        if self
10878            .context_menu
10879            .borrow_mut()
10880            .as_mut()
10881            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10882            .unwrap_or(false)
10883        {
10884            return;
10885        }
10886
10887        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10888            cx.propagate();
10889            return;
10890        }
10891
10892        let Some(row_count) = self.visible_row_count() else {
10893            return;
10894        };
10895
10896        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10897
10898        let autoscroll = if action.center_cursor {
10899            Autoscroll::center()
10900        } else {
10901            Autoscroll::fit()
10902        };
10903
10904        let text_layout_details = &self.text_layout_details(window);
10905
10906        self.change_selections(Some(autoscroll), window, cx, |s| {
10907            s.move_with(|map, selection| {
10908                if !selection.is_empty() {
10909                    selection.goal = SelectionGoal::None;
10910                }
10911                let (cursor, goal) = movement::up_by_rows(
10912                    map,
10913                    selection.end,
10914                    row_count,
10915                    selection.goal,
10916                    false,
10917                    text_layout_details,
10918                );
10919                selection.collapse_to(cursor, goal);
10920            });
10921        });
10922    }
10923
10924    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10925        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10926        let text_layout_details = &self.text_layout_details(window);
10927        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10928            s.move_heads_with(|map, head, goal| {
10929                movement::up(map, head, goal, false, text_layout_details)
10930            })
10931        })
10932    }
10933
10934    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10935        self.take_rename(true, window, cx);
10936
10937        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10938            cx.propagate();
10939            return;
10940        }
10941
10942        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10943
10944        let text_layout_details = &self.text_layout_details(window);
10945        let selection_count = self.selections.count();
10946        let first_selection = self.selections.first_anchor();
10947
10948        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10949            s.move_with(|map, selection| {
10950                if !selection.is_empty() {
10951                    selection.goal = SelectionGoal::None;
10952                }
10953                let (cursor, goal) = movement::down(
10954                    map,
10955                    selection.end,
10956                    selection.goal,
10957                    false,
10958                    text_layout_details,
10959                );
10960                selection.collapse_to(cursor, goal);
10961            });
10962        });
10963
10964        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10965        {
10966            cx.propagate();
10967        }
10968    }
10969
10970    pub fn select_page_down(
10971        &mut self,
10972        _: &SelectPageDown,
10973        window: &mut Window,
10974        cx: &mut Context<Self>,
10975    ) {
10976        let Some(row_count) = self.visible_row_count() else {
10977            return;
10978        };
10979
10980        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10981
10982        let text_layout_details = &self.text_layout_details(window);
10983
10984        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10985            s.move_heads_with(|map, head, goal| {
10986                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10987            })
10988        })
10989    }
10990
10991    pub fn move_page_down(
10992        &mut self,
10993        action: &MovePageDown,
10994        window: &mut Window,
10995        cx: &mut Context<Self>,
10996    ) {
10997        if self.take_rename(true, window, cx).is_some() {
10998            return;
10999        }
11000
11001        if self
11002            .context_menu
11003            .borrow_mut()
11004            .as_mut()
11005            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11006            .unwrap_or(false)
11007        {
11008            return;
11009        }
11010
11011        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11012            cx.propagate();
11013            return;
11014        }
11015
11016        let Some(row_count) = self.visible_row_count() else {
11017            return;
11018        };
11019
11020        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11021
11022        let autoscroll = if action.center_cursor {
11023            Autoscroll::center()
11024        } else {
11025            Autoscroll::fit()
11026        };
11027
11028        let text_layout_details = &self.text_layout_details(window);
11029        self.change_selections(Some(autoscroll), window, cx, |s| {
11030            s.move_with(|map, selection| {
11031                if !selection.is_empty() {
11032                    selection.goal = SelectionGoal::None;
11033                }
11034                let (cursor, goal) = movement::down_by_rows(
11035                    map,
11036                    selection.end,
11037                    row_count,
11038                    selection.goal,
11039                    false,
11040                    text_layout_details,
11041                );
11042                selection.collapse_to(cursor, goal);
11043            });
11044        });
11045    }
11046
11047    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11048        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11049        let text_layout_details = &self.text_layout_details(window);
11050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11051            s.move_heads_with(|map, head, goal| {
11052                movement::down(map, head, goal, false, text_layout_details)
11053            })
11054        });
11055    }
11056
11057    pub fn context_menu_first(
11058        &mut self,
11059        _: &ContextMenuFirst,
11060        _window: &mut Window,
11061        cx: &mut Context<Self>,
11062    ) {
11063        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11064            context_menu.select_first(self.completion_provider.as_deref(), cx);
11065        }
11066    }
11067
11068    pub fn context_menu_prev(
11069        &mut self,
11070        _: &ContextMenuPrevious,
11071        _window: &mut Window,
11072        cx: &mut Context<Self>,
11073    ) {
11074        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11075            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11076        }
11077    }
11078
11079    pub fn context_menu_next(
11080        &mut self,
11081        _: &ContextMenuNext,
11082        _window: &mut Window,
11083        cx: &mut Context<Self>,
11084    ) {
11085        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11086            context_menu.select_next(self.completion_provider.as_deref(), cx);
11087        }
11088    }
11089
11090    pub fn context_menu_last(
11091        &mut self,
11092        _: &ContextMenuLast,
11093        _window: &mut Window,
11094        cx: &mut Context<Self>,
11095    ) {
11096        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11097            context_menu.select_last(self.completion_provider.as_deref(), cx);
11098        }
11099    }
11100
11101    pub fn move_to_previous_word_start(
11102        &mut self,
11103        _: &MoveToPreviousWordStart,
11104        window: &mut Window,
11105        cx: &mut Context<Self>,
11106    ) {
11107        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11108        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11109            s.move_cursors_with(|map, head, _| {
11110                (
11111                    movement::previous_word_start(map, head),
11112                    SelectionGoal::None,
11113                )
11114            });
11115        })
11116    }
11117
11118    pub fn move_to_previous_subword_start(
11119        &mut self,
11120        _: &MoveToPreviousSubwordStart,
11121        window: &mut Window,
11122        cx: &mut Context<Self>,
11123    ) {
11124        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11125        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11126            s.move_cursors_with(|map, head, _| {
11127                (
11128                    movement::previous_subword_start(map, head),
11129                    SelectionGoal::None,
11130                )
11131            });
11132        })
11133    }
11134
11135    pub fn select_to_previous_word_start(
11136        &mut self,
11137        _: &SelectToPreviousWordStart,
11138        window: &mut Window,
11139        cx: &mut Context<Self>,
11140    ) {
11141        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11142        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11143            s.move_heads_with(|map, head, _| {
11144                (
11145                    movement::previous_word_start(map, head),
11146                    SelectionGoal::None,
11147                )
11148            });
11149        })
11150    }
11151
11152    pub fn select_to_previous_subword_start(
11153        &mut self,
11154        _: &SelectToPreviousSubwordStart,
11155        window: &mut Window,
11156        cx: &mut Context<Self>,
11157    ) {
11158        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11159        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11160            s.move_heads_with(|map, head, _| {
11161                (
11162                    movement::previous_subword_start(map, head),
11163                    SelectionGoal::None,
11164                )
11165            });
11166        })
11167    }
11168
11169    pub fn delete_to_previous_word_start(
11170        &mut self,
11171        action: &DeleteToPreviousWordStart,
11172        window: &mut Window,
11173        cx: &mut Context<Self>,
11174    ) {
11175        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11176        self.transact(window, cx, |this, window, cx| {
11177            this.select_autoclose_pair(window, cx);
11178            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11179                s.move_with(|map, selection| {
11180                    if selection.is_empty() {
11181                        let cursor = if action.ignore_newlines {
11182                            movement::previous_word_start(map, selection.head())
11183                        } else {
11184                            movement::previous_word_start_or_newline(map, selection.head())
11185                        };
11186                        selection.set_head(cursor, SelectionGoal::None);
11187                    }
11188                });
11189            });
11190            this.insert("", window, cx);
11191        });
11192    }
11193
11194    pub fn delete_to_previous_subword_start(
11195        &mut self,
11196        _: &DeleteToPreviousSubwordStart,
11197        window: &mut Window,
11198        cx: &mut Context<Self>,
11199    ) {
11200        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11201        self.transact(window, cx, |this, window, cx| {
11202            this.select_autoclose_pair(window, cx);
11203            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11204                s.move_with(|map, selection| {
11205                    if selection.is_empty() {
11206                        let cursor = movement::previous_subword_start(map, selection.head());
11207                        selection.set_head(cursor, SelectionGoal::None);
11208                    }
11209                });
11210            });
11211            this.insert("", window, cx);
11212        });
11213    }
11214
11215    pub fn move_to_next_word_end(
11216        &mut self,
11217        _: &MoveToNextWordEnd,
11218        window: &mut Window,
11219        cx: &mut Context<Self>,
11220    ) {
11221        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11222        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11223            s.move_cursors_with(|map, head, _| {
11224                (movement::next_word_end(map, head), SelectionGoal::None)
11225            });
11226        })
11227    }
11228
11229    pub fn move_to_next_subword_end(
11230        &mut self,
11231        _: &MoveToNextSubwordEnd,
11232        window: &mut Window,
11233        cx: &mut Context<Self>,
11234    ) {
11235        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11236        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11237            s.move_cursors_with(|map, head, _| {
11238                (movement::next_subword_end(map, head), SelectionGoal::None)
11239            });
11240        })
11241    }
11242
11243    pub fn select_to_next_word_end(
11244        &mut self,
11245        _: &SelectToNextWordEnd,
11246        window: &mut Window,
11247        cx: &mut Context<Self>,
11248    ) {
11249        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11250        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11251            s.move_heads_with(|map, head, _| {
11252                (movement::next_word_end(map, head), SelectionGoal::None)
11253            });
11254        })
11255    }
11256
11257    pub fn select_to_next_subword_end(
11258        &mut self,
11259        _: &SelectToNextSubwordEnd,
11260        window: &mut Window,
11261        cx: &mut Context<Self>,
11262    ) {
11263        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11264        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11265            s.move_heads_with(|map, head, _| {
11266                (movement::next_subword_end(map, head), SelectionGoal::None)
11267            });
11268        })
11269    }
11270
11271    pub fn delete_to_next_word_end(
11272        &mut self,
11273        action: &DeleteToNextWordEnd,
11274        window: &mut Window,
11275        cx: &mut Context<Self>,
11276    ) {
11277        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11278        self.transact(window, cx, |this, window, cx| {
11279            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11280                s.move_with(|map, selection| {
11281                    if selection.is_empty() {
11282                        let cursor = if action.ignore_newlines {
11283                            movement::next_word_end(map, selection.head())
11284                        } else {
11285                            movement::next_word_end_or_newline(map, selection.head())
11286                        };
11287                        selection.set_head(cursor, SelectionGoal::None);
11288                    }
11289                });
11290            });
11291            this.insert("", window, cx);
11292        });
11293    }
11294
11295    pub fn delete_to_next_subword_end(
11296        &mut self,
11297        _: &DeleteToNextSubwordEnd,
11298        window: &mut Window,
11299        cx: &mut Context<Self>,
11300    ) {
11301        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11302        self.transact(window, cx, |this, window, cx| {
11303            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11304                s.move_with(|map, selection| {
11305                    if selection.is_empty() {
11306                        let cursor = movement::next_subword_end(map, selection.head());
11307                        selection.set_head(cursor, SelectionGoal::None);
11308                    }
11309                });
11310            });
11311            this.insert("", window, cx);
11312        });
11313    }
11314
11315    pub fn move_to_beginning_of_line(
11316        &mut self,
11317        action: &MoveToBeginningOfLine,
11318        window: &mut Window,
11319        cx: &mut Context<Self>,
11320    ) {
11321        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11323            s.move_cursors_with(|map, head, _| {
11324                (
11325                    movement::indented_line_beginning(
11326                        map,
11327                        head,
11328                        action.stop_at_soft_wraps,
11329                        action.stop_at_indent,
11330                    ),
11331                    SelectionGoal::None,
11332                )
11333            });
11334        })
11335    }
11336
11337    pub fn select_to_beginning_of_line(
11338        &mut self,
11339        action: &SelectToBeginningOfLine,
11340        window: &mut Window,
11341        cx: &mut Context<Self>,
11342    ) {
11343        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11344        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11345            s.move_heads_with(|map, head, _| {
11346                (
11347                    movement::indented_line_beginning(
11348                        map,
11349                        head,
11350                        action.stop_at_soft_wraps,
11351                        action.stop_at_indent,
11352                    ),
11353                    SelectionGoal::None,
11354                )
11355            });
11356        });
11357    }
11358
11359    pub fn delete_to_beginning_of_line(
11360        &mut self,
11361        action: &DeleteToBeginningOfLine,
11362        window: &mut Window,
11363        cx: &mut Context<Self>,
11364    ) {
11365        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11366        self.transact(window, cx, |this, window, cx| {
11367            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11368                s.move_with(|_, selection| {
11369                    selection.reversed = true;
11370                });
11371            });
11372
11373            this.select_to_beginning_of_line(
11374                &SelectToBeginningOfLine {
11375                    stop_at_soft_wraps: false,
11376                    stop_at_indent: action.stop_at_indent,
11377                },
11378                window,
11379                cx,
11380            );
11381            this.backspace(&Backspace, window, cx);
11382        });
11383    }
11384
11385    pub fn move_to_end_of_line(
11386        &mut self,
11387        action: &MoveToEndOfLine,
11388        window: &mut Window,
11389        cx: &mut Context<Self>,
11390    ) {
11391        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11392        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11393            s.move_cursors_with(|map, head, _| {
11394                (
11395                    movement::line_end(map, head, action.stop_at_soft_wraps),
11396                    SelectionGoal::None,
11397                )
11398            });
11399        })
11400    }
11401
11402    pub fn select_to_end_of_line(
11403        &mut self,
11404        action: &SelectToEndOfLine,
11405        window: &mut Window,
11406        cx: &mut Context<Self>,
11407    ) {
11408        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11410            s.move_heads_with(|map, head, _| {
11411                (
11412                    movement::line_end(map, head, action.stop_at_soft_wraps),
11413                    SelectionGoal::None,
11414                )
11415            });
11416        })
11417    }
11418
11419    pub fn delete_to_end_of_line(
11420        &mut self,
11421        _: &DeleteToEndOfLine,
11422        window: &mut Window,
11423        cx: &mut Context<Self>,
11424    ) {
11425        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11426        self.transact(window, cx, |this, window, cx| {
11427            this.select_to_end_of_line(
11428                &SelectToEndOfLine {
11429                    stop_at_soft_wraps: false,
11430                },
11431                window,
11432                cx,
11433            );
11434            this.delete(&Delete, window, cx);
11435        });
11436    }
11437
11438    pub fn cut_to_end_of_line(
11439        &mut self,
11440        _: &CutToEndOfLine,
11441        window: &mut Window,
11442        cx: &mut Context<Self>,
11443    ) {
11444        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11445        self.transact(window, cx, |this, window, cx| {
11446            this.select_to_end_of_line(
11447                &SelectToEndOfLine {
11448                    stop_at_soft_wraps: false,
11449                },
11450                window,
11451                cx,
11452            );
11453            this.cut(&Cut, window, cx);
11454        });
11455    }
11456
11457    pub fn move_to_start_of_paragraph(
11458        &mut self,
11459        _: &MoveToStartOfParagraph,
11460        window: &mut Window,
11461        cx: &mut Context<Self>,
11462    ) {
11463        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11464            cx.propagate();
11465            return;
11466        }
11467        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11469            s.move_with(|map, selection| {
11470                selection.collapse_to(
11471                    movement::start_of_paragraph(map, selection.head(), 1),
11472                    SelectionGoal::None,
11473                )
11474            });
11475        })
11476    }
11477
11478    pub fn move_to_end_of_paragraph(
11479        &mut self,
11480        _: &MoveToEndOfParagraph,
11481        window: &mut Window,
11482        cx: &mut Context<Self>,
11483    ) {
11484        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11485            cx.propagate();
11486            return;
11487        }
11488        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11489        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11490            s.move_with(|map, selection| {
11491                selection.collapse_to(
11492                    movement::end_of_paragraph(map, selection.head(), 1),
11493                    SelectionGoal::None,
11494                )
11495            });
11496        })
11497    }
11498
11499    pub fn select_to_start_of_paragraph(
11500        &mut self,
11501        _: &SelectToStartOfParagraph,
11502        window: &mut Window,
11503        cx: &mut Context<Self>,
11504    ) {
11505        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11506            cx.propagate();
11507            return;
11508        }
11509        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11510        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11511            s.move_heads_with(|map, head, _| {
11512                (
11513                    movement::start_of_paragraph(map, head, 1),
11514                    SelectionGoal::None,
11515                )
11516            });
11517        })
11518    }
11519
11520    pub fn select_to_end_of_paragraph(
11521        &mut self,
11522        _: &SelectToEndOfParagraph,
11523        window: &mut Window,
11524        cx: &mut Context<Self>,
11525    ) {
11526        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11527            cx.propagate();
11528            return;
11529        }
11530        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11531        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11532            s.move_heads_with(|map, head, _| {
11533                (
11534                    movement::end_of_paragraph(map, head, 1),
11535                    SelectionGoal::None,
11536                )
11537            });
11538        })
11539    }
11540
11541    pub fn move_to_start_of_excerpt(
11542        &mut self,
11543        _: &MoveToStartOfExcerpt,
11544        window: &mut Window,
11545        cx: &mut Context<Self>,
11546    ) {
11547        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11548            cx.propagate();
11549            return;
11550        }
11551        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11552        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11553            s.move_with(|map, selection| {
11554                selection.collapse_to(
11555                    movement::start_of_excerpt(
11556                        map,
11557                        selection.head(),
11558                        workspace::searchable::Direction::Prev,
11559                    ),
11560                    SelectionGoal::None,
11561                )
11562            });
11563        })
11564    }
11565
11566    pub fn move_to_start_of_next_excerpt(
11567        &mut self,
11568        _: &MoveToStartOfNextExcerpt,
11569        window: &mut Window,
11570        cx: &mut Context<Self>,
11571    ) {
11572        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11573            cx.propagate();
11574            return;
11575        }
11576
11577        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11578            s.move_with(|map, selection| {
11579                selection.collapse_to(
11580                    movement::start_of_excerpt(
11581                        map,
11582                        selection.head(),
11583                        workspace::searchable::Direction::Next,
11584                    ),
11585                    SelectionGoal::None,
11586                )
11587            });
11588        })
11589    }
11590
11591    pub fn move_to_end_of_excerpt(
11592        &mut self,
11593        _: &MoveToEndOfExcerpt,
11594        window: &mut Window,
11595        cx: &mut Context<Self>,
11596    ) {
11597        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11598            cx.propagate();
11599            return;
11600        }
11601        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11602        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11603            s.move_with(|map, selection| {
11604                selection.collapse_to(
11605                    movement::end_of_excerpt(
11606                        map,
11607                        selection.head(),
11608                        workspace::searchable::Direction::Next,
11609                    ),
11610                    SelectionGoal::None,
11611                )
11612            });
11613        })
11614    }
11615
11616    pub fn move_to_end_of_previous_excerpt(
11617        &mut self,
11618        _: &MoveToEndOfPreviousExcerpt,
11619        window: &mut Window,
11620        cx: &mut Context<Self>,
11621    ) {
11622        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11623            cx.propagate();
11624            return;
11625        }
11626        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11627        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11628            s.move_with(|map, selection| {
11629                selection.collapse_to(
11630                    movement::end_of_excerpt(
11631                        map,
11632                        selection.head(),
11633                        workspace::searchable::Direction::Prev,
11634                    ),
11635                    SelectionGoal::None,
11636                )
11637            });
11638        })
11639    }
11640
11641    pub fn select_to_start_of_excerpt(
11642        &mut self,
11643        _: &SelectToStartOfExcerpt,
11644        window: &mut Window,
11645        cx: &mut Context<Self>,
11646    ) {
11647        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11648            cx.propagate();
11649            return;
11650        }
11651        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11652        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11653            s.move_heads_with(|map, head, _| {
11654                (
11655                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11656                    SelectionGoal::None,
11657                )
11658            });
11659        })
11660    }
11661
11662    pub fn select_to_start_of_next_excerpt(
11663        &mut self,
11664        _: &SelectToStartOfNextExcerpt,
11665        window: &mut Window,
11666        cx: &mut Context<Self>,
11667    ) {
11668        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11669            cx.propagate();
11670            return;
11671        }
11672        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11673        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11674            s.move_heads_with(|map, head, _| {
11675                (
11676                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11677                    SelectionGoal::None,
11678                )
11679            });
11680        })
11681    }
11682
11683    pub fn select_to_end_of_excerpt(
11684        &mut self,
11685        _: &SelectToEndOfExcerpt,
11686        window: &mut Window,
11687        cx: &mut Context<Self>,
11688    ) {
11689        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11690            cx.propagate();
11691            return;
11692        }
11693        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11694        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11695            s.move_heads_with(|map, head, _| {
11696                (
11697                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11698                    SelectionGoal::None,
11699                )
11700            });
11701        })
11702    }
11703
11704    pub fn select_to_end_of_previous_excerpt(
11705        &mut self,
11706        _: &SelectToEndOfPreviousExcerpt,
11707        window: &mut Window,
11708        cx: &mut Context<Self>,
11709    ) {
11710        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11711            cx.propagate();
11712            return;
11713        }
11714        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11715        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11716            s.move_heads_with(|map, head, _| {
11717                (
11718                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11719                    SelectionGoal::None,
11720                )
11721            });
11722        })
11723    }
11724
11725    pub fn move_to_beginning(
11726        &mut self,
11727        _: &MoveToBeginning,
11728        window: &mut Window,
11729        cx: &mut Context<Self>,
11730    ) {
11731        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11732            cx.propagate();
11733            return;
11734        }
11735        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11736        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11737            s.select_ranges(vec![0..0]);
11738        });
11739    }
11740
11741    pub fn select_to_beginning(
11742        &mut self,
11743        _: &SelectToBeginning,
11744        window: &mut Window,
11745        cx: &mut Context<Self>,
11746    ) {
11747        let mut selection = self.selections.last::<Point>(cx);
11748        selection.set_head(Point::zero(), SelectionGoal::None);
11749        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11750        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11751            s.select(vec![selection]);
11752        });
11753    }
11754
11755    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11756        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11757            cx.propagate();
11758            return;
11759        }
11760        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11761        let cursor = self.buffer.read(cx).read(cx).len();
11762        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11763            s.select_ranges(vec![cursor..cursor])
11764        });
11765    }
11766
11767    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11768        self.nav_history = nav_history;
11769    }
11770
11771    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11772        self.nav_history.as_ref()
11773    }
11774
11775    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11776        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11777    }
11778
11779    fn push_to_nav_history(
11780        &mut self,
11781        cursor_anchor: Anchor,
11782        new_position: Option<Point>,
11783        is_deactivate: bool,
11784        cx: &mut Context<Self>,
11785    ) {
11786        if let Some(nav_history) = self.nav_history.as_mut() {
11787            let buffer = self.buffer.read(cx).read(cx);
11788            let cursor_position = cursor_anchor.to_point(&buffer);
11789            let scroll_state = self.scroll_manager.anchor();
11790            let scroll_top_row = scroll_state.top_row(&buffer);
11791            drop(buffer);
11792
11793            if let Some(new_position) = new_position {
11794                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11795                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11796                    return;
11797                }
11798            }
11799
11800            nav_history.push(
11801                Some(NavigationData {
11802                    cursor_anchor,
11803                    cursor_position,
11804                    scroll_anchor: scroll_state,
11805                    scroll_top_row,
11806                }),
11807                cx,
11808            );
11809            cx.emit(EditorEvent::PushedToNavHistory {
11810                anchor: cursor_anchor,
11811                is_deactivate,
11812            })
11813        }
11814    }
11815
11816    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11817        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11818        let buffer = self.buffer.read(cx).snapshot(cx);
11819        let mut selection = self.selections.first::<usize>(cx);
11820        selection.set_head(buffer.len(), SelectionGoal::None);
11821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11822            s.select(vec![selection]);
11823        });
11824    }
11825
11826    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11827        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11828        let end = self.buffer.read(cx).read(cx).len();
11829        self.change_selections(None, window, cx, |s| {
11830            s.select_ranges(vec![0..end]);
11831        });
11832    }
11833
11834    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11835        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11836        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11837        let mut selections = self.selections.all::<Point>(cx);
11838        let max_point = display_map.buffer_snapshot.max_point();
11839        for selection in &mut selections {
11840            let rows = selection.spanned_rows(true, &display_map);
11841            selection.start = Point::new(rows.start.0, 0);
11842            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11843            selection.reversed = false;
11844        }
11845        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11846            s.select(selections);
11847        });
11848    }
11849
11850    pub fn split_selection_into_lines(
11851        &mut self,
11852        _: &SplitSelectionIntoLines,
11853        window: &mut Window,
11854        cx: &mut Context<Self>,
11855    ) {
11856        let selections = self
11857            .selections
11858            .all::<Point>(cx)
11859            .into_iter()
11860            .map(|selection| selection.start..selection.end)
11861            .collect::<Vec<_>>();
11862        self.unfold_ranges(&selections, true, true, cx);
11863
11864        let mut new_selection_ranges = Vec::new();
11865        {
11866            let buffer = self.buffer.read(cx).read(cx);
11867            for selection in selections {
11868                for row in selection.start.row..selection.end.row {
11869                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11870                    new_selection_ranges.push(cursor..cursor);
11871                }
11872
11873                let is_multiline_selection = selection.start.row != selection.end.row;
11874                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11875                // so this action feels more ergonomic when paired with other selection operations
11876                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11877                if !should_skip_last {
11878                    new_selection_ranges.push(selection.end..selection.end);
11879                }
11880            }
11881        }
11882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11883            s.select_ranges(new_selection_ranges);
11884        });
11885    }
11886
11887    pub fn add_selection_above(
11888        &mut self,
11889        _: &AddSelectionAbove,
11890        window: &mut Window,
11891        cx: &mut Context<Self>,
11892    ) {
11893        self.add_selection(true, window, cx);
11894    }
11895
11896    pub fn add_selection_below(
11897        &mut self,
11898        _: &AddSelectionBelow,
11899        window: &mut Window,
11900        cx: &mut Context<Self>,
11901    ) {
11902        self.add_selection(false, window, cx);
11903    }
11904
11905    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11906        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11907
11908        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11909        let mut selections = self.selections.all::<Point>(cx);
11910        let text_layout_details = self.text_layout_details(window);
11911        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11912            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11913            let range = oldest_selection.display_range(&display_map).sorted();
11914
11915            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11916            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11917            let positions = start_x.min(end_x)..start_x.max(end_x);
11918
11919            selections.clear();
11920            let mut stack = Vec::new();
11921            for row in range.start.row().0..=range.end.row().0 {
11922                if let Some(selection) = self.selections.build_columnar_selection(
11923                    &display_map,
11924                    DisplayRow(row),
11925                    &positions,
11926                    oldest_selection.reversed,
11927                    &text_layout_details,
11928                ) {
11929                    stack.push(selection.id);
11930                    selections.push(selection);
11931                }
11932            }
11933
11934            if above {
11935                stack.reverse();
11936            }
11937
11938            AddSelectionsState { above, stack }
11939        });
11940
11941        let last_added_selection = *state.stack.last().unwrap();
11942        let mut new_selections = Vec::new();
11943        if above == state.above {
11944            let end_row = if above {
11945                DisplayRow(0)
11946            } else {
11947                display_map.max_point().row()
11948            };
11949
11950            'outer: for selection in selections {
11951                if selection.id == last_added_selection {
11952                    let range = selection.display_range(&display_map).sorted();
11953                    debug_assert_eq!(range.start.row(), range.end.row());
11954                    let mut row = range.start.row();
11955                    let positions =
11956                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11957                            px(start)..px(end)
11958                        } else {
11959                            let start_x =
11960                                display_map.x_for_display_point(range.start, &text_layout_details);
11961                            let end_x =
11962                                display_map.x_for_display_point(range.end, &text_layout_details);
11963                            start_x.min(end_x)..start_x.max(end_x)
11964                        };
11965
11966                    while row != end_row {
11967                        if above {
11968                            row.0 -= 1;
11969                        } else {
11970                            row.0 += 1;
11971                        }
11972
11973                        if let Some(new_selection) = self.selections.build_columnar_selection(
11974                            &display_map,
11975                            row,
11976                            &positions,
11977                            selection.reversed,
11978                            &text_layout_details,
11979                        ) {
11980                            state.stack.push(new_selection.id);
11981                            if above {
11982                                new_selections.push(new_selection);
11983                                new_selections.push(selection);
11984                            } else {
11985                                new_selections.push(selection);
11986                                new_selections.push(new_selection);
11987                            }
11988
11989                            continue 'outer;
11990                        }
11991                    }
11992                }
11993
11994                new_selections.push(selection);
11995            }
11996        } else {
11997            new_selections = selections;
11998            new_selections.retain(|s| s.id != last_added_selection);
11999            state.stack.pop();
12000        }
12001
12002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12003            s.select(new_selections);
12004        });
12005        if state.stack.len() > 1 {
12006            self.add_selections_state = Some(state);
12007        }
12008    }
12009
12010    pub fn select_next_match_internal(
12011        &mut self,
12012        display_map: &DisplaySnapshot,
12013        replace_newest: bool,
12014        autoscroll: Option<Autoscroll>,
12015        window: &mut Window,
12016        cx: &mut Context<Self>,
12017    ) -> Result<()> {
12018        fn select_next_match_ranges(
12019            this: &mut Editor,
12020            range: Range<usize>,
12021            reversed: bool,
12022            replace_newest: bool,
12023            auto_scroll: Option<Autoscroll>,
12024            window: &mut Window,
12025            cx: &mut Context<Editor>,
12026        ) {
12027            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12028            this.change_selections(auto_scroll, window, cx, |s| {
12029                if replace_newest {
12030                    s.delete(s.newest_anchor().id);
12031                }
12032                if reversed {
12033                    s.insert_range(range.end..range.start);
12034                } else {
12035                    s.insert_range(range);
12036                }
12037            });
12038        }
12039
12040        let buffer = &display_map.buffer_snapshot;
12041        let mut selections = self.selections.all::<usize>(cx);
12042        if let Some(mut select_next_state) = self.select_next_state.take() {
12043            let query = &select_next_state.query;
12044            if !select_next_state.done {
12045                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12046                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12047                let mut next_selected_range = None;
12048
12049                let bytes_after_last_selection =
12050                    buffer.bytes_in_range(last_selection.end..buffer.len());
12051                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12052                let query_matches = query
12053                    .stream_find_iter(bytes_after_last_selection)
12054                    .map(|result| (last_selection.end, result))
12055                    .chain(
12056                        query
12057                            .stream_find_iter(bytes_before_first_selection)
12058                            .map(|result| (0, result)),
12059                    );
12060
12061                for (start_offset, query_match) in query_matches {
12062                    let query_match = query_match.unwrap(); // can only fail due to I/O
12063                    let offset_range =
12064                        start_offset + query_match.start()..start_offset + query_match.end();
12065                    let display_range = offset_range.start.to_display_point(display_map)
12066                        ..offset_range.end.to_display_point(display_map);
12067
12068                    if !select_next_state.wordwise
12069                        || (!movement::is_inside_word(display_map, display_range.start)
12070                            && !movement::is_inside_word(display_map, display_range.end))
12071                    {
12072                        // TODO: This is n^2, because we might check all the selections
12073                        if !selections
12074                            .iter()
12075                            .any(|selection| selection.range().overlaps(&offset_range))
12076                        {
12077                            next_selected_range = Some(offset_range);
12078                            break;
12079                        }
12080                    }
12081                }
12082
12083                if let Some(next_selected_range) = next_selected_range {
12084                    select_next_match_ranges(
12085                        self,
12086                        next_selected_range,
12087                        last_selection.reversed,
12088                        replace_newest,
12089                        autoscroll,
12090                        window,
12091                        cx,
12092                    );
12093                } else {
12094                    select_next_state.done = true;
12095                }
12096            }
12097
12098            self.select_next_state = Some(select_next_state);
12099        } else {
12100            let mut only_carets = true;
12101            let mut same_text_selected = true;
12102            let mut selected_text = None;
12103
12104            let mut selections_iter = selections.iter().peekable();
12105            while let Some(selection) = selections_iter.next() {
12106                if selection.start != selection.end {
12107                    only_carets = false;
12108                }
12109
12110                if same_text_selected {
12111                    if selected_text.is_none() {
12112                        selected_text =
12113                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12114                    }
12115
12116                    if let Some(next_selection) = selections_iter.peek() {
12117                        if next_selection.range().len() == selection.range().len() {
12118                            let next_selected_text = buffer
12119                                .text_for_range(next_selection.range())
12120                                .collect::<String>();
12121                            if Some(next_selected_text) != selected_text {
12122                                same_text_selected = false;
12123                                selected_text = None;
12124                            }
12125                        } else {
12126                            same_text_selected = false;
12127                            selected_text = None;
12128                        }
12129                    }
12130                }
12131            }
12132
12133            if only_carets {
12134                for selection in &mut selections {
12135                    let word_range = movement::surrounding_word(
12136                        display_map,
12137                        selection.start.to_display_point(display_map),
12138                    );
12139                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12140                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12141                    selection.goal = SelectionGoal::None;
12142                    selection.reversed = false;
12143                    select_next_match_ranges(
12144                        self,
12145                        selection.start..selection.end,
12146                        selection.reversed,
12147                        replace_newest,
12148                        autoscroll,
12149                        window,
12150                        cx,
12151                    );
12152                }
12153
12154                if selections.len() == 1 {
12155                    let selection = selections
12156                        .last()
12157                        .expect("ensured that there's only one selection");
12158                    let query = buffer
12159                        .text_for_range(selection.start..selection.end)
12160                        .collect::<String>();
12161                    let is_empty = query.is_empty();
12162                    let select_state = SelectNextState {
12163                        query: AhoCorasick::new(&[query])?,
12164                        wordwise: true,
12165                        done: is_empty,
12166                    };
12167                    self.select_next_state = Some(select_state);
12168                } else {
12169                    self.select_next_state = None;
12170                }
12171            } else if let Some(selected_text) = selected_text {
12172                self.select_next_state = Some(SelectNextState {
12173                    query: AhoCorasick::new(&[selected_text])?,
12174                    wordwise: false,
12175                    done: false,
12176                });
12177                self.select_next_match_internal(
12178                    display_map,
12179                    replace_newest,
12180                    autoscroll,
12181                    window,
12182                    cx,
12183                )?;
12184            }
12185        }
12186        Ok(())
12187    }
12188
12189    pub fn select_all_matches(
12190        &mut self,
12191        _action: &SelectAllMatches,
12192        window: &mut Window,
12193        cx: &mut Context<Self>,
12194    ) -> Result<()> {
12195        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12196
12197        self.push_to_selection_history();
12198        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12199
12200        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12201        let Some(select_next_state) = self.select_next_state.as_mut() else {
12202            return Ok(());
12203        };
12204        if select_next_state.done {
12205            return Ok(());
12206        }
12207
12208        let mut new_selections = Vec::new();
12209
12210        let reversed = self.selections.oldest::<usize>(cx).reversed;
12211        let buffer = &display_map.buffer_snapshot;
12212        let query_matches = select_next_state
12213            .query
12214            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12215
12216        for query_match in query_matches.into_iter() {
12217            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12218            let offset_range = if reversed {
12219                query_match.end()..query_match.start()
12220            } else {
12221                query_match.start()..query_match.end()
12222            };
12223            let display_range = offset_range.start.to_display_point(&display_map)
12224                ..offset_range.end.to_display_point(&display_map);
12225
12226            if !select_next_state.wordwise
12227                || (!movement::is_inside_word(&display_map, display_range.start)
12228                    && !movement::is_inside_word(&display_map, display_range.end))
12229            {
12230                new_selections.push(offset_range.start..offset_range.end);
12231            }
12232        }
12233
12234        select_next_state.done = true;
12235        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12236        self.change_selections(None, window, cx, |selections| {
12237            selections.select_ranges(new_selections)
12238        });
12239
12240        Ok(())
12241    }
12242
12243    pub fn select_next(
12244        &mut self,
12245        action: &SelectNext,
12246        window: &mut Window,
12247        cx: &mut Context<Self>,
12248    ) -> Result<()> {
12249        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12250        self.push_to_selection_history();
12251        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12252        self.select_next_match_internal(
12253            &display_map,
12254            action.replace_newest,
12255            Some(Autoscroll::newest()),
12256            window,
12257            cx,
12258        )?;
12259        Ok(())
12260    }
12261
12262    pub fn select_previous(
12263        &mut self,
12264        action: &SelectPrevious,
12265        window: &mut Window,
12266        cx: &mut Context<Self>,
12267    ) -> Result<()> {
12268        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12269        self.push_to_selection_history();
12270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12271        let buffer = &display_map.buffer_snapshot;
12272        let mut selections = self.selections.all::<usize>(cx);
12273        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12274            let query = &select_prev_state.query;
12275            if !select_prev_state.done {
12276                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12277                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12278                let mut next_selected_range = None;
12279                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12280                let bytes_before_last_selection =
12281                    buffer.reversed_bytes_in_range(0..last_selection.start);
12282                let bytes_after_first_selection =
12283                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12284                let query_matches = query
12285                    .stream_find_iter(bytes_before_last_selection)
12286                    .map(|result| (last_selection.start, result))
12287                    .chain(
12288                        query
12289                            .stream_find_iter(bytes_after_first_selection)
12290                            .map(|result| (buffer.len(), result)),
12291                    );
12292                for (end_offset, query_match) in query_matches {
12293                    let query_match = query_match.unwrap(); // can only fail due to I/O
12294                    let offset_range =
12295                        end_offset - query_match.end()..end_offset - query_match.start();
12296                    let display_range = offset_range.start.to_display_point(&display_map)
12297                        ..offset_range.end.to_display_point(&display_map);
12298
12299                    if !select_prev_state.wordwise
12300                        || (!movement::is_inside_word(&display_map, display_range.start)
12301                            && !movement::is_inside_word(&display_map, display_range.end))
12302                    {
12303                        next_selected_range = Some(offset_range);
12304                        break;
12305                    }
12306                }
12307
12308                if let Some(next_selected_range) = next_selected_range {
12309                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12310                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12311                        if action.replace_newest {
12312                            s.delete(s.newest_anchor().id);
12313                        }
12314                        if last_selection.reversed {
12315                            s.insert_range(next_selected_range.end..next_selected_range.start);
12316                        } else {
12317                            s.insert_range(next_selected_range);
12318                        }
12319                    });
12320                } else {
12321                    select_prev_state.done = true;
12322                }
12323            }
12324
12325            self.select_prev_state = Some(select_prev_state);
12326        } else {
12327            let mut only_carets = true;
12328            let mut same_text_selected = true;
12329            let mut selected_text = None;
12330
12331            let mut selections_iter = selections.iter().peekable();
12332            while let Some(selection) = selections_iter.next() {
12333                if selection.start != selection.end {
12334                    only_carets = false;
12335                }
12336
12337                if same_text_selected {
12338                    if selected_text.is_none() {
12339                        selected_text =
12340                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12341                    }
12342
12343                    if let Some(next_selection) = selections_iter.peek() {
12344                        if next_selection.range().len() == selection.range().len() {
12345                            let next_selected_text = buffer
12346                                .text_for_range(next_selection.range())
12347                                .collect::<String>();
12348                            if Some(next_selected_text) != selected_text {
12349                                same_text_selected = false;
12350                                selected_text = None;
12351                            }
12352                        } else {
12353                            same_text_selected = false;
12354                            selected_text = None;
12355                        }
12356                    }
12357                }
12358            }
12359
12360            if only_carets {
12361                for selection in &mut selections {
12362                    let word_range = movement::surrounding_word(
12363                        &display_map,
12364                        selection.start.to_display_point(&display_map),
12365                    );
12366                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12367                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12368                    selection.goal = SelectionGoal::None;
12369                    selection.reversed = false;
12370                }
12371                if selections.len() == 1 {
12372                    let selection = selections
12373                        .last()
12374                        .expect("ensured that there's only one selection");
12375                    let query = buffer
12376                        .text_for_range(selection.start..selection.end)
12377                        .collect::<String>();
12378                    let is_empty = query.is_empty();
12379                    let select_state = SelectNextState {
12380                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12381                        wordwise: true,
12382                        done: is_empty,
12383                    };
12384                    self.select_prev_state = Some(select_state);
12385                } else {
12386                    self.select_prev_state = None;
12387                }
12388
12389                self.unfold_ranges(
12390                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12391                    false,
12392                    true,
12393                    cx,
12394                );
12395                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12396                    s.select(selections);
12397                });
12398            } else if let Some(selected_text) = selected_text {
12399                self.select_prev_state = Some(SelectNextState {
12400                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12401                    wordwise: false,
12402                    done: false,
12403                });
12404                self.select_previous(action, window, cx)?;
12405            }
12406        }
12407        Ok(())
12408    }
12409
12410    pub fn find_next_match(
12411        &mut self,
12412        _: &FindNextMatch,
12413        window: &mut Window,
12414        cx: &mut Context<Self>,
12415    ) -> Result<()> {
12416        let selections = self.selections.disjoint_anchors();
12417        match selections.first() {
12418            Some(first) if selections.len() >= 2 => {
12419                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12420                    s.select_ranges([first.range()]);
12421                });
12422            }
12423            _ => self.select_next(
12424                &SelectNext {
12425                    replace_newest: true,
12426                },
12427                window,
12428                cx,
12429            )?,
12430        }
12431        Ok(())
12432    }
12433
12434    pub fn find_previous_match(
12435        &mut self,
12436        _: &FindPreviousMatch,
12437        window: &mut Window,
12438        cx: &mut Context<Self>,
12439    ) -> Result<()> {
12440        let selections = self.selections.disjoint_anchors();
12441        match selections.last() {
12442            Some(last) if selections.len() >= 2 => {
12443                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12444                    s.select_ranges([last.range()]);
12445                });
12446            }
12447            _ => self.select_previous(
12448                &SelectPrevious {
12449                    replace_newest: true,
12450                },
12451                window,
12452                cx,
12453            )?,
12454        }
12455        Ok(())
12456    }
12457
12458    pub fn toggle_comments(
12459        &mut self,
12460        action: &ToggleComments,
12461        window: &mut Window,
12462        cx: &mut Context<Self>,
12463    ) {
12464        if self.read_only(cx) {
12465            return;
12466        }
12467        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12468        let text_layout_details = &self.text_layout_details(window);
12469        self.transact(window, cx, |this, window, cx| {
12470            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12471            let mut edits = Vec::new();
12472            let mut selection_edit_ranges = Vec::new();
12473            let mut last_toggled_row = None;
12474            let snapshot = this.buffer.read(cx).read(cx);
12475            let empty_str: Arc<str> = Arc::default();
12476            let mut suffixes_inserted = Vec::new();
12477            let ignore_indent = action.ignore_indent;
12478
12479            fn comment_prefix_range(
12480                snapshot: &MultiBufferSnapshot,
12481                row: MultiBufferRow,
12482                comment_prefix: &str,
12483                comment_prefix_whitespace: &str,
12484                ignore_indent: bool,
12485            ) -> Range<Point> {
12486                let indent_size = if ignore_indent {
12487                    0
12488                } else {
12489                    snapshot.indent_size_for_line(row).len
12490                };
12491
12492                let start = Point::new(row.0, indent_size);
12493
12494                let mut line_bytes = snapshot
12495                    .bytes_in_range(start..snapshot.max_point())
12496                    .flatten()
12497                    .copied();
12498
12499                // If this line currently begins with the line comment prefix, then record
12500                // the range containing the prefix.
12501                if line_bytes
12502                    .by_ref()
12503                    .take(comment_prefix.len())
12504                    .eq(comment_prefix.bytes())
12505                {
12506                    // Include any whitespace that matches the comment prefix.
12507                    let matching_whitespace_len = line_bytes
12508                        .zip(comment_prefix_whitespace.bytes())
12509                        .take_while(|(a, b)| a == b)
12510                        .count() as u32;
12511                    let end = Point::new(
12512                        start.row,
12513                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12514                    );
12515                    start..end
12516                } else {
12517                    start..start
12518                }
12519            }
12520
12521            fn comment_suffix_range(
12522                snapshot: &MultiBufferSnapshot,
12523                row: MultiBufferRow,
12524                comment_suffix: &str,
12525                comment_suffix_has_leading_space: bool,
12526            ) -> Range<Point> {
12527                let end = Point::new(row.0, snapshot.line_len(row));
12528                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12529
12530                let mut line_end_bytes = snapshot
12531                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12532                    .flatten()
12533                    .copied();
12534
12535                let leading_space_len = if suffix_start_column > 0
12536                    && line_end_bytes.next() == Some(b' ')
12537                    && comment_suffix_has_leading_space
12538                {
12539                    1
12540                } else {
12541                    0
12542                };
12543
12544                // If this line currently begins with the line comment prefix, then record
12545                // the range containing the prefix.
12546                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12547                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12548                    start..end
12549                } else {
12550                    end..end
12551                }
12552            }
12553
12554            // TODO: Handle selections that cross excerpts
12555            for selection in &mut selections {
12556                let start_column = snapshot
12557                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12558                    .len;
12559                let language = if let Some(language) =
12560                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12561                {
12562                    language
12563                } else {
12564                    continue;
12565                };
12566
12567                selection_edit_ranges.clear();
12568
12569                // If multiple selections contain a given row, avoid processing that
12570                // row more than once.
12571                let mut start_row = MultiBufferRow(selection.start.row);
12572                if last_toggled_row == Some(start_row) {
12573                    start_row = start_row.next_row();
12574                }
12575                let end_row =
12576                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12577                        MultiBufferRow(selection.end.row - 1)
12578                    } else {
12579                        MultiBufferRow(selection.end.row)
12580                    };
12581                last_toggled_row = Some(end_row);
12582
12583                if start_row > end_row {
12584                    continue;
12585                }
12586
12587                // If the language has line comments, toggle those.
12588                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12589
12590                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12591                if ignore_indent {
12592                    full_comment_prefixes = full_comment_prefixes
12593                        .into_iter()
12594                        .map(|s| Arc::from(s.trim_end()))
12595                        .collect();
12596                }
12597
12598                if !full_comment_prefixes.is_empty() {
12599                    let first_prefix = full_comment_prefixes
12600                        .first()
12601                        .expect("prefixes is non-empty");
12602                    let prefix_trimmed_lengths = full_comment_prefixes
12603                        .iter()
12604                        .map(|p| p.trim_end_matches(' ').len())
12605                        .collect::<SmallVec<[usize; 4]>>();
12606
12607                    let mut all_selection_lines_are_comments = true;
12608
12609                    for row in start_row.0..=end_row.0 {
12610                        let row = MultiBufferRow(row);
12611                        if start_row < end_row && snapshot.is_line_blank(row) {
12612                            continue;
12613                        }
12614
12615                        let prefix_range = full_comment_prefixes
12616                            .iter()
12617                            .zip(prefix_trimmed_lengths.iter().copied())
12618                            .map(|(prefix, trimmed_prefix_len)| {
12619                                comment_prefix_range(
12620                                    snapshot.deref(),
12621                                    row,
12622                                    &prefix[..trimmed_prefix_len],
12623                                    &prefix[trimmed_prefix_len..],
12624                                    ignore_indent,
12625                                )
12626                            })
12627                            .max_by_key(|range| range.end.column - range.start.column)
12628                            .expect("prefixes is non-empty");
12629
12630                        if prefix_range.is_empty() {
12631                            all_selection_lines_are_comments = false;
12632                        }
12633
12634                        selection_edit_ranges.push(prefix_range);
12635                    }
12636
12637                    if all_selection_lines_are_comments {
12638                        edits.extend(
12639                            selection_edit_ranges
12640                                .iter()
12641                                .cloned()
12642                                .map(|range| (range, empty_str.clone())),
12643                        );
12644                    } else {
12645                        let min_column = selection_edit_ranges
12646                            .iter()
12647                            .map(|range| range.start.column)
12648                            .min()
12649                            .unwrap_or(0);
12650                        edits.extend(selection_edit_ranges.iter().map(|range| {
12651                            let position = Point::new(range.start.row, min_column);
12652                            (position..position, first_prefix.clone())
12653                        }));
12654                    }
12655                } else if let Some((full_comment_prefix, comment_suffix)) =
12656                    language.block_comment_delimiters()
12657                {
12658                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12659                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12660                    let prefix_range = comment_prefix_range(
12661                        snapshot.deref(),
12662                        start_row,
12663                        comment_prefix,
12664                        comment_prefix_whitespace,
12665                        ignore_indent,
12666                    );
12667                    let suffix_range = comment_suffix_range(
12668                        snapshot.deref(),
12669                        end_row,
12670                        comment_suffix.trim_start_matches(' '),
12671                        comment_suffix.starts_with(' '),
12672                    );
12673
12674                    if prefix_range.is_empty() || suffix_range.is_empty() {
12675                        edits.push((
12676                            prefix_range.start..prefix_range.start,
12677                            full_comment_prefix.clone(),
12678                        ));
12679                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12680                        suffixes_inserted.push((end_row, comment_suffix.len()));
12681                    } else {
12682                        edits.push((prefix_range, empty_str.clone()));
12683                        edits.push((suffix_range, empty_str.clone()));
12684                    }
12685                } else {
12686                    continue;
12687                }
12688            }
12689
12690            drop(snapshot);
12691            this.buffer.update(cx, |buffer, cx| {
12692                buffer.edit(edits, None, cx);
12693            });
12694
12695            // Adjust selections so that they end before any comment suffixes that
12696            // were inserted.
12697            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12698            let mut selections = this.selections.all::<Point>(cx);
12699            let snapshot = this.buffer.read(cx).read(cx);
12700            for selection in &mut selections {
12701                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12702                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12703                        Ordering::Less => {
12704                            suffixes_inserted.next();
12705                            continue;
12706                        }
12707                        Ordering::Greater => break,
12708                        Ordering::Equal => {
12709                            if selection.end.column == snapshot.line_len(row) {
12710                                if selection.is_empty() {
12711                                    selection.start.column -= suffix_len as u32;
12712                                }
12713                                selection.end.column -= suffix_len as u32;
12714                            }
12715                            break;
12716                        }
12717                    }
12718                }
12719            }
12720
12721            drop(snapshot);
12722            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12723                s.select(selections)
12724            });
12725
12726            let selections = this.selections.all::<Point>(cx);
12727            let selections_on_single_row = selections.windows(2).all(|selections| {
12728                selections[0].start.row == selections[1].start.row
12729                    && selections[0].end.row == selections[1].end.row
12730                    && selections[0].start.row == selections[0].end.row
12731            });
12732            let selections_selecting = selections
12733                .iter()
12734                .any(|selection| selection.start != selection.end);
12735            let advance_downwards = action.advance_downwards
12736                && selections_on_single_row
12737                && !selections_selecting
12738                && !matches!(this.mode, EditorMode::SingleLine { .. });
12739
12740            if advance_downwards {
12741                let snapshot = this.buffer.read(cx).snapshot(cx);
12742
12743                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12744                    s.move_cursors_with(|display_snapshot, display_point, _| {
12745                        let mut point = display_point.to_point(display_snapshot);
12746                        point.row += 1;
12747                        point = snapshot.clip_point(point, Bias::Left);
12748                        let display_point = point.to_display_point(display_snapshot);
12749                        let goal = SelectionGoal::HorizontalPosition(
12750                            display_snapshot
12751                                .x_for_display_point(display_point, text_layout_details)
12752                                .into(),
12753                        );
12754                        (display_point, goal)
12755                    })
12756                });
12757            }
12758        });
12759    }
12760
12761    pub fn select_enclosing_symbol(
12762        &mut self,
12763        _: &SelectEnclosingSymbol,
12764        window: &mut Window,
12765        cx: &mut Context<Self>,
12766    ) {
12767        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12768
12769        let buffer = self.buffer.read(cx).snapshot(cx);
12770        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12771
12772        fn update_selection(
12773            selection: &Selection<usize>,
12774            buffer_snap: &MultiBufferSnapshot,
12775        ) -> Option<Selection<usize>> {
12776            let cursor = selection.head();
12777            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12778            for symbol in symbols.iter().rev() {
12779                let start = symbol.range.start.to_offset(buffer_snap);
12780                let end = symbol.range.end.to_offset(buffer_snap);
12781                let new_range = start..end;
12782                if start < selection.start || end > selection.end {
12783                    return Some(Selection {
12784                        id: selection.id,
12785                        start: new_range.start,
12786                        end: new_range.end,
12787                        goal: SelectionGoal::None,
12788                        reversed: selection.reversed,
12789                    });
12790                }
12791            }
12792            None
12793        }
12794
12795        let mut selected_larger_symbol = false;
12796        let new_selections = old_selections
12797            .iter()
12798            .map(|selection| match update_selection(selection, &buffer) {
12799                Some(new_selection) => {
12800                    if new_selection.range() != selection.range() {
12801                        selected_larger_symbol = true;
12802                    }
12803                    new_selection
12804                }
12805                None => selection.clone(),
12806            })
12807            .collect::<Vec<_>>();
12808
12809        if selected_larger_symbol {
12810            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12811                s.select(new_selections);
12812            });
12813        }
12814    }
12815
12816    pub fn select_larger_syntax_node(
12817        &mut self,
12818        _: &SelectLargerSyntaxNode,
12819        window: &mut Window,
12820        cx: &mut Context<Self>,
12821    ) {
12822        let Some(visible_row_count) = self.visible_row_count() else {
12823            return;
12824        };
12825        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12826        if old_selections.is_empty() {
12827            return;
12828        }
12829
12830        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12831
12832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12833        let buffer = self.buffer.read(cx).snapshot(cx);
12834
12835        let mut selected_larger_node = false;
12836        let mut new_selections = old_selections
12837            .iter()
12838            .map(|selection| {
12839                let old_range = selection.start..selection.end;
12840
12841                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12842                    // manually select word at selection
12843                    if ["string_content", "inline"].contains(&node.kind()) {
12844                        let word_range = {
12845                            let display_point = buffer
12846                                .offset_to_point(old_range.start)
12847                                .to_display_point(&display_map);
12848                            let Range { start, end } =
12849                                movement::surrounding_word(&display_map, display_point);
12850                            start.to_point(&display_map).to_offset(&buffer)
12851                                ..end.to_point(&display_map).to_offset(&buffer)
12852                        };
12853                        // ignore if word is already selected
12854                        if !word_range.is_empty() && old_range != word_range {
12855                            let last_word_range = {
12856                                let display_point = buffer
12857                                    .offset_to_point(old_range.end)
12858                                    .to_display_point(&display_map);
12859                                let Range { start, end } =
12860                                    movement::surrounding_word(&display_map, display_point);
12861                                start.to_point(&display_map).to_offset(&buffer)
12862                                    ..end.to_point(&display_map).to_offset(&buffer)
12863                            };
12864                            // only select word if start and end point belongs to same word
12865                            if word_range == last_word_range {
12866                                selected_larger_node = true;
12867                                return Selection {
12868                                    id: selection.id,
12869                                    start: word_range.start,
12870                                    end: word_range.end,
12871                                    goal: SelectionGoal::None,
12872                                    reversed: selection.reversed,
12873                                };
12874                            }
12875                        }
12876                    }
12877                }
12878
12879                let mut new_range = old_range.clone();
12880                let mut new_node = None;
12881                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12882                {
12883                    new_node = Some(node);
12884                    new_range = match containing_range {
12885                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12886                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12887                    };
12888                    if !display_map.intersects_fold(new_range.start)
12889                        && !display_map.intersects_fold(new_range.end)
12890                    {
12891                        break;
12892                    }
12893                }
12894
12895                if let Some(node) = new_node {
12896                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12897                    // nodes. Parent and grandparent are also logged because this operation will not
12898                    // visit nodes that have the same range as their parent.
12899                    log::info!("Node: {node:?}");
12900                    let parent = node.parent();
12901                    log::info!("Parent: {parent:?}");
12902                    let grandparent = parent.and_then(|x| x.parent());
12903                    log::info!("Grandparent: {grandparent:?}");
12904                }
12905
12906                selected_larger_node |= new_range != old_range;
12907                Selection {
12908                    id: selection.id,
12909                    start: new_range.start,
12910                    end: new_range.end,
12911                    goal: SelectionGoal::None,
12912                    reversed: selection.reversed,
12913                }
12914            })
12915            .collect::<Vec<_>>();
12916
12917        if !selected_larger_node {
12918            return; // don't put this call in the history
12919        }
12920
12921        // scroll based on transformation done to the last selection created by the user
12922        let (last_old, last_new) = old_selections
12923            .last()
12924            .zip(new_selections.last().cloned())
12925            .expect("old_selections isn't empty");
12926
12927        // revert selection
12928        let is_selection_reversed = {
12929            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12930            new_selections.last_mut().expect("checked above").reversed =
12931                should_newest_selection_be_reversed;
12932            should_newest_selection_be_reversed
12933        };
12934
12935        if selected_larger_node {
12936            self.select_syntax_node_history.disable_clearing = true;
12937            self.change_selections(None, window, cx, |s| {
12938                s.select(new_selections.clone());
12939            });
12940            self.select_syntax_node_history.disable_clearing = false;
12941        }
12942
12943        let start_row = last_new.start.to_display_point(&display_map).row().0;
12944        let end_row = last_new.end.to_display_point(&display_map).row().0;
12945        let selection_height = end_row - start_row + 1;
12946        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12947
12948        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12949        let scroll_behavior = if fits_on_the_screen {
12950            self.request_autoscroll(Autoscroll::fit(), cx);
12951            SelectSyntaxNodeScrollBehavior::FitSelection
12952        } else if is_selection_reversed {
12953            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12954            SelectSyntaxNodeScrollBehavior::CursorTop
12955        } else {
12956            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12957            SelectSyntaxNodeScrollBehavior::CursorBottom
12958        };
12959
12960        self.select_syntax_node_history.push((
12961            old_selections,
12962            scroll_behavior,
12963            is_selection_reversed,
12964        ));
12965    }
12966
12967    pub fn select_smaller_syntax_node(
12968        &mut self,
12969        _: &SelectSmallerSyntaxNode,
12970        window: &mut Window,
12971        cx: &mut Context<Self>,
12972    ) {
12973        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12974
12975        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12976            self.select_syntax_node_history.pop()
12977        {
12978            if let Some(selection) = selections.last_mut() {
12979                selection.reversed = is_selection_reversed;
12980            }
12981
12982            self.select_syntax_node_history.disable_clearing = true;
12983            self.change_selections(None, window, cx, |s| {
12984                s.select(selections.to_vec());
12985            });
12986            self.select_syntax_node_history.disable_clearing = false;
12987
12988            match scroll_behavior {
12989                SelectSyntaxNodeScrollBehavior::CursorTop => {
12990                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12991                }
12992                SelectSyntaxNodeScrollBehavior::FitSelection => {
12993                    self.request_autoscroll(Autoscroll::fit(), cx);
12994                }
12995                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12996                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12997                }
12998            }
12999        }
13000    }
13001
13002    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13003        if !EditorSettings::get_global(cx).gutter.runnables {
13004            self.clear_tasks();
13005            return Task::ready(());
13006        }
13007        let project = self.project.as_ref().map(Entity::downgrade);
13008        let task_sources = self.lsp_task_sources(cx);
13009        cx.spawn_in(window, async move |editor, cx| {
13010            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13011            let Some(project) = project.and_then(|p| p.upgrade()) else {
13012                return;
13013            };
13014            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13015                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13016            }) else {
13017                return;
13018            };
13019
13020            let hide_runnables = project
13021                .update(cx, |project, cx| {
13022                    // Do not display any test indicators in non-dev server remote projects.
13023                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13024                })
13025                .unwrap_or(true);
13026            if hide_runnables {
13027                return;
13028            }
13029            let new_rows =
13030                cx.background_spawn({
13031                    let snapshot = display_snapshot.clone();
13032                    async move {
13033                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13034                    }
13035                })
13036                    .await;
13037            let Ok(lsp_tasks) =
13038                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13039            else {
13040                return;
13041            };
13042            let lsp_tasks = lsp_tasks.await;
13043
13044            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13045                lsp_tasks
13046                    .into_iter()
13047                    .flat_map(|(kind, tasks)| {
13048                        tasks.into_iter().filter_map(move |(location, task)| {
13049                            Some((kind.clone(), location?, task))
13050                        })
13051                    })
13052                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13053                        let buffer = location.target.buffer;
13054                        let buffer_snapshot = buffer.read(cx).snapshot();
13055                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13056                            |(excerpt_id, snapshot, _)| {
13057                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13058                                    display_snapshot
13059                                        .buffer_snapshot
13060                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13061                                } else {
13062                                    None
13063                                }
13064                            },
13065                        );
13066                        if let Some(offset) = offset {
13067                            let task_buffer_range =
13068                                location.target.range.to_point(&buffer_snapshot);
13069                            let context_buffer_range =
13070                                task_buffer_range.to_offset(&buffer_snapshot);
13071                            let context_range = BufferOffset(context_buffer_range.start)
13072                                ..BufferOffset(context_buffer_range.end);
13073
13074                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13075                                .or_insert_with(|| RunnableTasks {
13076                                    templates: Vec::new(),
13077                                    offset,
13078                                    column: task_buffer_range.start.column,
13079                                    extra_variables: HashMap::default(),
13080                                    context_range,
13081                                })
13082                                .templates
13083                                .push((kind, task.original_task().clone()));
13084                        }
13085
13086                        acc
13087                    })
13088            }) else {
13089                return;
13090            };
13091
13092            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13093            editor
13094                .update(cx, |editor, _| {
13095                    editor.clear_tasks();
13096                    for (key, mut value) in rows {
13097                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13098                            value.templates.extend(lsp_tasks.templates);
13099                        }
13100
13101                        editor.insert_tasks(key, value);
13102                    }
13103                    for (key, value) in lsp_tasks_by_rows {
13104                        editor.insert_tasks(key, value);
13105                    }
13106                })
13107                .ok();
13108        })
13109    }
13110    fn fetch_runnable_ranges(
13111        snapshot: &DisplaySnapshot,
13112        range: Range<Anchor>,
13113    ) -> Vec<language::RunnableRange> {
13114        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13115    }
13116
13117    fn runnable_rows(
13118        project: Entity<Project>,
13119        snapshot: DisplaySnapshot,
13120        runnable_ranges: Vec<RunnableRange>,
13121        mut cx: AsyncWindowContext,
13122    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13123        runnable_ranges
13124            .into_iter()
13125            .filter_map(|mut runnable| {
13126                let tasks = cx
13127                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13128                    .ok()?;
13129                if tasks.is_empty() {
13130                    return None;
13131                }
13132
13133                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13134
13135                let row = snapshot
13136                    .buffer_snapshot
13137                    .buffer_line_for_row(MultiBufferRow(point.row))?
13138                    .1
13139                    .start
13140                    .row;
13141
13142                let context_range =
13143                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13144                Some((
13145                    (runnable.buffer_id, row),
13146                    RunnableTasks {
13147                        templates: tasks,
13148                        offset: snapshot
13149                            .buffer_snapshot
13150                            .anchor_before(runnable.run_range.start),
13151                        context_range,
13152                        column: point.column,
13153                        extra_variables: runnable.extra_captures,
13154                    },
13155                ))
13156            })
13157            .collect()
13158    }
13159
13160    fn templates_with_tags(
13161        project: &Entity<Project>,
13162        runnable: &mut Runnable,
13163        cx: &mut App,
13164    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13165        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13166            let (worktree_id, file) = project
13167                .buffer_for_id(runnable.buffer, cx)
13168                .and_then(|buffer| buffer.read(cx).file())
13169                .map(|file| (file.worktree_id(cx), file.clone()))
13170                .unzip();
13171
13172            (
13173                project.task_store().read(cx).task_inventory().cloned(),
13174                worktree_id,
13175                file,
13176            )
13177        });
13178
13179        let mut templates_with_tags = mem::take(&mut runnable.tags)
13180            .into_iter()
13181            .flat_map(|RunnableTag(tag)| {
13182                inventory
13183                    .as_ref()
13184                    .into_iter()
13185                    .flat_map(|inventory| {
13186                        inventory.read(cx).list_tasks(
13187                            file.clone(),
13188                            Some(runnable.language.clone()),
13189                            worktree_id,
13190                            cx,
13191                        )
13192                    })
13193                    .filter(move |(_, template)| {
13194                        template.tags.iter().any(|source_tag| source_tag == &tag)
13195                    })
13196            })
13197            .sorted_by_key(|(kind, _)| kind.to_owned())
13198            .collect::<Vec<_>>();
13199        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13200            // Strongest source wins; if we have worktree tag binding, prefer that to
13201            // global and language bindings;
13202            // if we have a global binding, prefer that to language binding.
13203            let first_mismatch = templates_with_tags
13204                .iter()
13205                .position(|(tag_source, _)| tag_source != leading_tag_source);
13206            if let Some(index) = first_mismatch {
13207                templates_with_tags.truncate(index);
13208            }
13209        }
13210
13211        templates_with_tags
13212    }
13213
13214    pub fn move_to_enclosing_bracket(
13215        &mut self,
13216        _: &MoveToEnclosingBracket,
13217        window: &mut Window,
13218        cx: &mut Context<Self>,
13219    ) {
13220        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13221        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13222            s.move_offsets_with(|snapshot, selection| {
13223                let Some(enclosing_bracket_ranges) =
13224                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13225                else {
13226                    return;
13227                };
13228
13229                let mut best_length = usize::MAX;
13230                let mut best_inside = false;
13231                let mut best_in_bracket_range = false;
13232                let mut best_destination = None;
13233                for (open, close) in enclosing_bracket_ranges {
13234                    let close = close.to_inclusive();
13235                    let length = close.end() - open.start;
13236                    let inside = selection.start >= open.end && selection.end <= *close.start();
13237                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13238                        || close.contains(&selection.head());
13239
13240                    // If best is next to a bracket and current isn't, skip
13241                    if !in_bracket_range && best_in_bracket_range {
13242                        continue;
13243                    }
13244
13245                    // Prefer smaller lengths unless best is inside and current isn't
13246                    if length > best_length && (best_inside || !inside) {
13247                        continue;
13248                    }
13249
13250                    best_length = length;
13251                    best_inside = inside;
13252                    best_in_bracket_range = in_bracket_range;
13253                    best_destination = Some(
13254                        if close.contains(&selection.start) && close.contains(&selection.end) {
13255                            if inside { open.end } else { open.start }
13256                        } else if inside {
13257                            *close.start()
13258                        } else {
13259                            *close.end()
13260                        },
13261                    );
13262                }
13263
13264                if let Some(destination) = best_destination {
13265                    selection.collapse_to(destination, SelectionGoal::None);
13266                }
13267            })
13268        });
13269    }
13270
13271    pub fn undo_selection(
13272        &mut self,
13273        _: &UndoSelection,
13274        window: &mut Window,
13275        cx: &mut Context<Self>,
13276    ) {
13277        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13278        self.end_selection(window, cx);
13279        self.selection_history.mode = SelectionHistoryMode::Undoing;
13280        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13281            self.change_selections(None, window, cx, |s| {
13282                s.select_anchors(entry.selections.to_vec())
13283            });
13284            self.select_next_state = entry.select_next_state;
13285            self.select_prev_state = entry.select_prev_state;
13286            self.add_selections_state = entry.add_selections_state;
13287            self.request_autoscroll(Autoscroll::newest(), cx);
13288        }
13289        self.selection_history.mode = SelectionHistoryMode::Normal;
13290    }
13291
13292    pub fn redo_selection(
13293        &mut self,
13294        _: &RedoSelection,
13295        window: &mut Window,
13296        cx: &mut Context<Self>,
13297    ) {
13298        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13299        self.end_selection(window, cx);
13300        self.selection_history.mode = SelectionHistoryMode::Redoing;
13301        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13302            self.change_selections(None, window, cx, |s| {
13303                s.select_anchors(entry.selections.to_vec())
13304            });
13305            self.select_next_state = entry.select_next_state;
13306            self.select_prev_state = entry.select_prev_state;
13307            self.add_selections_state = entry.add_selections_state;
13308            self.request_autoscroll(Autoscroll::newest(), cx);
13309        }
13310        self.selection_history.mode = SelectionHistoryMode::Normal;
13311    }
13312
13313    pub fn expand_excerpts(
13314        &mut self,
13315        action: &ExpandExcerpts,
13316        _: &mut Window,
13317        cx: &mut Context<Self>,
13318    ) {
13319        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13320    }
13321
13322    pub fn expand_excerpts_down(
13323        &mut self,
13324        action: &ExpandExcerptsDown,
13325        _: &mut Window,
13326        cx: &mut Context<Self>,
13327    ) {
13328        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13329    }
13330
13331    pub fn expand_excerpts_up(
13332        &mut self,
13333        action: &ExpandExcerptsUp,
13334        _: &mut Window,
13335        cx: &mut Context<Self>,
13336    ) {
13337        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13338    }
13339
13340    pub fn expand_excerpts_for_direction(
13341        &mut self,
13342        lines: u32,
13343        direction: ExpandExcerptDirection,
13344
13345        cx: &mut Context<Self>,
13346    ) {
13347        let selections = self.selections.disjoint_anchors();
13348
13349        let lines = if lines == 0 {
13350            EditorSettings::get_global(cx).expand_excerpt_lines
13351        } else {
13352            lines
13353        };
13354
13355        self.buffer.update(cx, |buffer, cx| {
13356            let snapshot = buffer.snapshot(cx);
13357            let mut excerpt_ids = selections
13358                .iter()
13359                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13360                .collect::<Vec<_>>();
13361            excerpt_ids.sort();
13362            excerpt_ids.dedup();
13363            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13364        })
13365    }
13366
13367    pub fn expand_excerpt(
13368        &mut self,
13369        excerpt: ExcerptId,
13370        direction: ExpandExcerptDirection,
13371        window: &mut Window,
13372        cx: &mut Context<Self>,
13373    ) {
13374        let current_scroll_position = self.scroll_position(cx);
13375        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13376        let mut should_scroll_up = false;
13377
13378        if direction == ExpandExcerptDirection::Down {
13379            let multi_buffer = self.buffer.read(cx);
13380            let snapshot = multi_buffer.snapshot(cx);
13381            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13382                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13383                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13384                        let buffer_snapshot = buffer.read(cx).snapshot();
13385                        let excerpt_end_row =
13386                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13387                        let last_row = buffer_snapshot.max_point().row;
13388                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13389                        should_scroll_up = lines_below >= lines_to_expand;
13390                    }
13391                }
13392            }
13393        }
13394
13395        self.buffer.update(cx, |buffer, cx| {
13396            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13397        });
13398
13399        if should_scroll_up {
13400            let new_scroll_position =
13401                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13402            self.set_scroll_position(new_scroll_position, window, cx);
13403        }
13404    }
13405
13406    pub fn go_to_singleton_buffer_point(
13407        &mut self,
13408        point: Point,
13409        window: &mut Window,
13410        cx: &mut Context<Self>,
13411    ) {
13412        self.go_to_singleton_buffer_range(point..point, window, cx);
13413    }
13414
13415    pub fn go_to_singleton_buffer_range(
13416        &mut self,
13417        range: Range<Point>,
13418        window: &mut Window,
13419        cx: &mut Context<Self>,
13420    ) {
13421        let multibuffer = self.buffer().read(cx);
13422        let Some(buffer) = multibuffer.as_singleton() else {
13423            return;
13424        };
13425        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13426            return;
13427        };
13428        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13429            return;
13430        };
13431        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13432            s.select_anchor_ranges([start..end])
13433        });
13434    }
13435
13436    pub fn go_to_diagnostic(
13437        &mut self,
13438        _: &GoToDiagnostic,
13439        window: &mut Window,
13440        cx: &mut Context<Self>,
13441    ) {
13442        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13443        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13444    }
13445
13446    pub fn go_to_prev_diagnostic(
13447        &mut self,
13448        _: &GoToPreviousDiagnostic,
13449        window: &mut Window,
13450        cx: &mut Context<Self>,
13451    ) {
13452        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13453        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13454    }
13455
13456    pub fn go_to_diagnostic_impl(
13457        &mut self,
13458        direction: Direction,
13459        window: &mut Window,
13460        cx: &mut Context<Self>,
13461    ) {
13462        let buffer = self.buffer.read(cx).snapshot(cx);
13463        let selection = self.selections.newest::<usize>(cx);
13464
13465        let mut active_group_id = None;
13466        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13467            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13468                active_group_id = Some(active_group.group_id);
13469            }
13470        }
13471
13472        fn filtered(
13473            snapshot: EditorSnapshot,
13474            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13475        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13476            diagnostics
13477                .filter(|entry| entry.range.start != entry.range.end)
13478                .filter(|entry| !entry.diagnostic.is_unnecessary)
13479                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13480        }
13481
13482        let snapshot = self.snapshot(window, cx);
13483        let before = filtered(
13484            snapshot.clone(),
13485            buffer
13486                .diagnostics_in_range(0..selection.start)
13487                .filter(|entry| entry.range.start <= selection.start),
13488        );
13489        let after = filtered(
13490            snapshot,
13491            buffer
13492                .diagnostics_in_range(selection.start..buffer.len())
13493                .filter(|entry| entry.range.start >= selection.start),
13494        );
13495
13496        let mut found: Option<DiagnosticEntry<usize>> = None;
13497        if direction == Direction::Prev {
13498            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13499            {
13500                for diagnostic in prev_diagnostics.into_iter().rev() {
13501                    if diagnostic.range.start != selection.start
13502                        || active_group_id
13503                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13504                    {
13505                        found = Some(diagnostic);
13506                        break 'outer;
13507                    }
13508                }
13509            }
13510        } else {
13511            for diagnostic in after.chain(before) {
13512                if diagnostic.range.start != selection.start
13513                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13514                {
13515                    found = Some(diagnostic);
13516                    break;
13517                }
13518            }
13519        }
13520        let Some(next_diagnostic) = found else {
13521            return;
13522        };
13523
13524        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13525            return;
13526        };
13527        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13528            s.select_ranges(vec![
13529                next_diagnostic.range.start..next_diagnostic.range.start,
13530            ])
13531        });
13532        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13533        self.refresh_inline_completion(false, true, window, cx);
13534    }
13535
13536    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13537        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13538        let snapshot = self.snapshot(window, cx);
13539        let selection = self.selections.newest::<Point>(cx);
13540        self.go_to_hunk_before_or_after_position(
13541            &snapshot,
13542            selection.head(),
13543            Direction::Next,
13544            window,
13545            cx,
13546        );
13547    }
13548
13549    pub fn go_to_hunk_before_or_after_position(
13550        &mut self,
13551        snapshot: &EditorSnapshot,
13552        position: Point,
13553        direction: Direction,
13554        window: &mut Window,
13555        cx: &mut Context<Editor>,
13556    ) {
13557        let row = if direction == Direction::Next {
13558            self.hunk_after_position(snapshot, position)
13559                .map(|hunk| hunk.row_range.start)
13560        } else {
13561            self.hunk_before_position(snapshot, position)
13562        };
13563
13564        if let Some(row) = row {
13565            let destination = Point::new(row.0, 0);
13566            let autoscroll = Autoscroll::center();
13567
13568            self.unfold_ranges(&[destination..destination], false, false, cx);
13569            self.change_selections(Some(autoscroll), window, cx, |s| {
13570                s.select_ranges([destination..destination]);
13571            });
13572        }
13573    }
13574
13575    fn hunk_after_position(
13576        &mut self,
13577        snapshot: &EditorSnapshot,
13578        position: Point,
13579    ) -> Option<MultiBufferDiffHunk> {
13580        snapshot
13581            .buffer_snapshot
13582            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13583            .find(|hunk| hunk.row_range.start.0 > position.row)
13584            .or_else(|| {
13585                snapshot
13586                    .buffer_snapshot
13587                    .diff_hunks_in_range(Point::zero()..position)
13588                    .find(|hunk| hunk.row_range.end.0 < position.row)
13589            })
13590    }
13591
13592    fn go_to_prev_hunk(
13593        &mut self,
13594        _: &GoToPreviousHunk,
13595        window: &mut Window,
13596        cx: &mut Context<Self>,
13597    ) {
13598        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13599        let snapshot = self.snapshot(window, cx);
13600        let selection = self.selections.newest::<Point>(cx);
13601        self.go_to_hunk_before_or_after_position(
13602            &snapshot,
13603            selection.head(),
13604            Direction::Prev,
13605            window,
13606            cx,
13607        );
13608    }
13609
13610    fn hunk_before_position(
13611        &mut self,
13612        snapshot: &EditorSnapshot,
13613        position: Point,
13614    ) -> Option<MultiBufferRow> {
13615        snapshot
13616            .buffer_snapshot
13617            .diff_hunk_before(position)
13618            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13619    }
13620
13621    fn go_to_next_change(
13622        &mut self,
13623        _: &GoToNextChange,
13624        window: &mut Window,
13625        cx: &mut Context<Self>,
13626    ) {
13627        if let Some(selections) = self
13628            .change_list
13629            .next_change(1, Direction::Next)
13630            .map(|s| s.to_vec())
13631        {
13632            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13633                let map = s.display_map();
13634                s.select_display_ranges(selections.iter().map(|a| {
13635                    let point = a.to_display_point(&map);
13636                    point..point
13637                }))
13638            })
13639        }
13640    }
13641
13642    fn go_to_previous_change(
13643        &mut self,
13644        _: &GoToPreviousChange,
13645        window: &mut Window,
13646        cx: &mut Context<Self>,
13647    ) {
13648        if let Some(selections) = self
13649            .change_list
13650            .next_change(1, Direction::Prev)
13651            .map(|s| s.to_vec())
13652        {
13653            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13654                let map = s.display_map();
13655                s.select_display_ranges(selections.iter().map(|a| {
13656                    let point = a.to_display_point(&map);
13657                    point..point
13658                }))
13659            })
13660        }
13661    }
13662
13663    fn go_to_line<T: 'static>(
13664        &mut self,
13665        position: Anchor,
13666        highlight_color: Option<Hsla>,
13667        window: &mut Window,
13668        cx: &mut Context<Self>,
13669    ) {
13670        let snapshot = self.snapshot(window, cx).display_snapshot;
13671        let position = position.to_point(&snapshot.buffer_snapshot);
13672        let start = snapshot
13673            .buffer_snapshot
13674            .clip_point(Point::new(position.row, 0), Bias::Left);
13675        let end = start + Point::new(1, 0);
13676        let start = snapshot.buffer_snapshot.anchor_before(start);
13677        let end = snapshot.buffer_snapshot.anchor_before(end);
13678
13679        self.highlight_rows::<T>(
13680            start..end,
13681            highlight_color
13682                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13683            Default::default(),
13684            cx,
13685        );
13686        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13687    }
13688
13689    pub fn go_to_definition(
13690        &mut self,
13691        _: &GoToDefinition,
13692        window: &mut Window,
13693        cx: &mut Context<Self>,
13694    ) -> Task<Result<Navigated>> {
13695        let definition =
13696            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13697        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13698        cx.spawn_in(window, async move |editor, cx| {
13699            if definition.await? == Navigated::Yes {
13700                return Ok(Navigated::Yes);
13701            }
13702            match fallback_strategy {
13703                GoToDefinitionFallback::None => Ok(Navigated::No),
13704                GoToDefinitionFallback::FindAllReferences => {
13705                    match editor.update_in(cx, |editor, window, cx| {
13706                        editor.find_all_references(&FindAllReferences, window, cx)
13707                    })? {
13708                        Some(references) => references.await,
13709                        None => Ok(Navigated::No),
13710                    }
13711                }
13712            }
13713        })
13714    }
13715
13716    pub fn go_to_declaration(
13717        &mut self,
13718        _: &GoToDeclaration,
13719        window: &mut Window,
13720        cx: &mut Context<Self>,
13721    ) -> Task<Result<Navigated>> {
13722        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13723    }
13724
13725    pub fn go_to_declaration_split(
13726        &mut self,
13727        _: &GoToDeclaration,
13728        window: &mut Window,
13729        cx: &mut Context<Self>,
13730    ) -> Task<Result<Navigated>> {
13731        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13732    }
13733
13734    pub fn go_to_implementation(
13735        &mut self,
13736        _: &GoToImplementation,
13737        window: &mut Window,
13738        cx: &mut Context<Self>,
13739    ) -> Task<Result<Navigated>> {
13740        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13741    }
13742
13743    pub fn go_to_implementation_split(
13744        &mut self,
13745        _: &GoToImplementationSplit,
13746        window: &mut Window,
13747        cx: &mut Context<Self>,
13748    ) -> Task<Result<Navigated>> {
13749        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13750    }
13751
13752    pub fn go_to_type_definition(
13753        &mut self,
13754        _: &GoToTypeDefinition,
13755        window: &mut Window,
13756        cx: &mut Context<Self>,
13757    ) -> Task<Result<Navigated>> {
13758        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13759    }
13760
13761    pub fn go_to_definition_split(
13762        &mut self,
13763        _: &GoToDefinitionSplit,
13764        window: &mut Window,
13765        cx: &mut Context<Self>,
13766    ) -> Task<Result<Navigated>> {
13767        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13768    }
13769
13770    pub fn go_to_type_definition_split(
13771        &mut self,
13772        _: &GoToTypeDefinitionSplit,
13773        window: &mut Window,
13774        cx: &mut Context<Self>,
13775    ) -> Task<Result<Navigated>> {
13776        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13777    }
13778
13779    fn go_to_definition_of_kind(
13780        &mut self,
13781        kind: GotoDefinitionKind,
13782        split: bool,
13783        window: &mut Window,
13784        cx: &mut Context<Self>,
13785    ) -> Task<Result<Navigated>> {
13786        let Some(provider) = self.semantics_provider.clone() else {
13787            return Task::ready(Ok(Navigated::No));
13788        };
13789        let head = self.selections.newest::<usize>(cx).head();
13790        let buffer = self.buffer.read(cx);
13791        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13792            text_anchor
13793        } else {
13794            return Task::ready(Ok(Navigated::No));
13795        };
13796
13797        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13798            return Task::ready(Ok(Navigated::No));
13799        };
13800
13801        cx.spawn_in(window, async move |editor, cx| {
13802            let definitions = definitions.await?;
13803            let navigated = editor
13804                .update_in(cx, |editor, window, cx| {
13805                    editor.navigate_to_hover_links(
13806                        Some(kind),
13807                        definitions
13808                            .into_iter()
13809                            .filter(|location| {
13810                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13811                            })
13812                            .map(HoverLink::Text)
13813                            .collect::<Vec<_>>(),
13814                        split,
13815                        window,
13816                        cx,
13817                    )
13818                })?
13819                .await?;
13820            anyhow::Ok(navigated)
13821        })
13822    }
13823
13824    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13825        let selection = self.selections.newest_anchor();
13826        let head = selection.head();
13827        let tail = selection.tail();
13828
13829        let Some((buffer, start_position)) =
13830            self.buffer.read(cx).text_anchor_for_position(head, cx)
13831        else {
13832            return;
13833        };
13834
13835        let end_position = if head != tail {
13836            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13837                return;
13838            };
13839            Some(pos)
13840        } else {
13841            None
13842        };
13843
13844        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13845            let url = if let Some(end_pos) = end_position {
13846                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13847            } else {
13848                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13849            };
13850
13851            if let Some(url) = url {
13852                editor.update(cx, |_, cx| {
13853                    cx.open_url(&url);
13854                })
13855            } else {
13856                Ok(())
13857            }
13858        });
13859
13860        url_finder.detach();
13861    }
13862
13863    pub fn open_selected_filename(
13864        &mut self,
13865        _: &OpenSelectedFilename,
13866        window: &mut Window,
13867        cx: &mut Context<Self>,
13868    ) {
13869        let Some(workspace) = self.workspace() else {
13870            return;
13871        };
13872
13873        let position = self.selections.newest_anchor().head();
13874
13875        let Some((buffer, buffer_position)) =
13876            self.buffer.read(cx).text_anchor_for_position(position, cx)
13877        else {
13878            return;
13879        };
13880
13881        let project = self.project.clone();
13882
13883        cx.spawn_in(window, async move |_, cx| {
13884            let result = find_file(&buffer, project, buffer_position, cx).await;
13885
13886            if let Some((_, path)) = result {
13887                workspace
13888                    .update_in(cx, |workspace, window, cx| {
13889                        workspace.open_resolved_path(path, window, cx)
13890                    })?
13891                    .await?;
13892            }
13893            anyhow::Ok(())
13894        })
13895        .detach();
13896    }
13897
13898    pub(crate) fn navigate_to_hover_links(
13899        &mut self,
13900        kind: Option<GotoDefinitionKind>,
13901        mut definitions: Vec<HoverLink>,
13902        split: bool,
13903        window: &mut Window,
13904        cx: &mut Context<Editor>,
13905    ) -> Task<Result<Navigated>> {
13906        // If there is one definition, just open it directly
13907        if definitions.len() == 1 {
13908            let definition = definitions.pop().unwrap();
13909
13910            enum TargetTaskResult {
13911                Location(Option<Location>),
13912                AlreadyNavigated,
13913            }
13914
13915            let target_task = match definition {
13916                HoverLink::Text(link) => {
13917                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13918                }
13919                HoverLink::InlayHint(lsp_location, server_id) => {
13920                    let computation =
13921                        self.compute_target_location(lsp_location, server_id, window, cx);
13922                    cx.background_spawn(async move {
13923                        let location = computation.await?;
13924                        Ok(TargetTaskResult::Location(location))
13925                    })
13926                }
13927                HoverLink::Url(url) => {
13928                    cx.open_url(&url);
13929                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13930                }
13931                HoverLink::File(path) => {
13932                    if let Some(workspace) = self.workspace() {
13933                        cx.spawn_in(window, async move |_, cx| {
13934                            workspace
13935                                .update_in(cx, |workspace, window, cx| {
13936                                    workspace.open_resolved_path(path, window, cx)
13937                                })?
13938                                .await
13939                                .map(|_| TargetTaskResult::AlreadyNavigated)
13940                        })
13941                    } else {
13942                        Task::ready(Ok(TargetTaskResult::Location(None)))
13943                    }
13944                }
13945            };
13946            cx.spawn_in(window, async move |editor, cx| {
13947                let target = match target_task.await.context("target resolution task")? {
13948                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13949                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13950                    TargetTaskResult::Location(Some(target)) => target,
13951                };
13952
13953                editor.update_in(cx, |editor, window, cx| {
13954                    let Some(workspace) = editor.workspace() else {
13955                        return Navigated::No;
13956                    };
13957                    let pane = workspace.read(cx).active_pane().clone();
13958
13959                    let range = target.range.to_point(target.buffer.read(cx));
13960                    let range = editor.range_for_match(&range);
13961                    let range = collapse_multiline_range(range);
13962
13963                    if !split
13964                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13965                    {
13966                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13967                    } else {
13968                        window.defer(cx, move |window, cx| {
13969                            let target_editor: Entity<Self> =
13970                                workspace.update(cx, |workspace, cx| {
13971                                    let pane = if split {
13972                                        workspace.adjacent_pane(window, cx)
13973                                    } else {
13974                                        workspace.active_pane().clone()
13975                                    };
13976
13977                                    workspace.open_project_item(
13978                                        pane,
13979                                        target.buffer.clone(),
13980                                        true,
13981                                        true,
13982                                        window,
13983                                        cx,
13984                                    )
13985                                });
13986                            target_editor.update(cx, |target_editor, cx| {
13987                                // When selecting a definition in a different buffer, disable the nav history
13988                                // to avoid creating a history entry at the previous cursor location.
13989                                pane.update(cx, |pane, _| pane.disable_history());
13990                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13991                                pane.update(cx, |pane, _| pane.enable_history());
13992                            });
13993                        });
13994                    }
13995                    Navigated::Yes
13996                })
13997            })
13998        } else if !definitions.is_empty() {
13999            cx.spawn_in(window, async move |editor, cx| {
14000                let (title, location_tasks, workspace) = editor
14001                    .update_in(cx, |editor, window, cx| {
14002                        let tab_kind = match kind {
14003                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14004                            _ => "Definitions",
14005                        };
14006                        let title = definitions
14007                            .iter()
14008                            .find_map(|definition| match definition {
14009                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14010                                    let buffer = origin.buffer.read(cx);
14011                                    format!(
14012                                        "{} for {}",
14013                                        tab_kind,
14014                                        buffer
14015                                            .text_for_range(origin.range.clone())
14016                                            .collect::<String>()
14017                                    )
14018                                }),
14019                                HoverLink::InlayHint(_, _) => None,
14020                                HoverLink::Url(_) => None,
14021                                HoverLink::File(_) => None,
14022                            })
14023                            .unwrap_or(tab_kind.to_string());
14024                        let location_tasks = definitions
14025                            .into_iter()
14026                            .map(|definition| match definition {
14027                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14028                                HoverLink::InlayHint(lsp_location, server_id) => editor
14029                                    .compute_target_location(lsp_location, server_id, window, cx),
14030                                HoverLink::Url(_) => Task::ready(Ok(None)),
14031                                HoverLink::File(_) => Task::ready(Ok(None)),
14032                            })
14033                            .collect::<Vec<_>>();
14034                        (title, location_tasks, editor.workspace().clone())
14035                    })
14036                    .context("location tasks preparation")?;
14037
14038                let locations = future::join_all(location_tasks)
14039                    .await
14040                    .into_iter()
14041                    .filter_map(|location| location.transpose())
14042                    .collect::<Result<_>>()
14043                    .context("location tasks")?;
14044
14045                let Some(workspace) = workspace else {
14046                    return Ok(Navigated::No);
14047                };
14048                let opened = workspace
14049                    .update_in(cx, |workspace, window, cx| {
14050                        Self::open_locations_in_multibuffer(
14051                            workspace,
14052                            locations,
14053                            title,
14054                            split,
14055                            MultibufferSelectionMode::First,
14056                            window,
14057                            cx,
14058                        )
14059                    })
14060                    .ok();
14061
14062                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14063            })
14064        } else {
14065            Task::ready(Ok(Navigated::No))
14066        }
14067    }
14068
14069    fn compute_target_location(
14070        &self,
14071        lsp_location: lsp::Location,
14072        server_id: LanguageServerId,
14073        window: &mut Window,
14074        cx: &mut Context<Self>,
14075    ) -> Task<anyhow::Result<Option<Location>>> {
14076        let Some(project) = self.project.clone() else {
14077            return Task::ready(Ok(None));
14078        };
14079
14080        cx.spawn_in(window, async move |editor, cx| {
14081            let location_task = editor.update(cx, |_, cx| {
14082                project.update(cx, |project, cx| {
14083                    let language_server_name = project
14084                        .language_server_statuses(cx)
14085                        .find(|(id, _)| server_id == *id)
14086                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14087                    language_server_name.map(|language_server_name| {
14088                        project.open_local_buffer_via_lsp(
14089                            lsp_location.uri.clone(),
14090                            server_id,
14091                            language_server_name,
14092                            cx,
14093                        )
14094                    })
14095                })
14096            })?;
14097            let location = match location_task {
14098                Some(task) => Some({
14099                    let target_buffer_handle = task.await.context("open local buffer")?;
14100                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14101                        let target_start = target_buffer
14102                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14103                        let target_end = target_buffer
14104                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14105                        target_buffer.anchor_after(target_start)
14106                            ..target_buffer.anchor_before(target_end)
14107                    })?;
14108                    Location {
14109                        buffer: target_buffer_handle,
14110                        range,
14111                    }
14112                }),
14113                None => None,
14114            };
14115            Ok(location)
14116        })
14117    }
14118
14119    pub fn find_all_references(
14120        &mut self,
14121        _: &FindAllReferences,
14122        window: &mut Window,
14123        cx: &mut Context<Self>,
14124    ) -> Option<Task<Result<Navigated>>> {
14125        let selection = self.selections.newest::<usize>(cx);
14126        let multi_buffer = self.buffer.read(cx);
14127        let head = selection.head();
14128
14129        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14130        let head_anchor = multi_buffer_snapshot.anchor_at(
14131            head,
14132            if head < selection.tail() {
14133                Bias::Right
14134            } else {
14135                Bias::Left
14136            },
14137        );
14138
14139        match self
14140            .find_all_references_task_sources
14141            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14142        {
14143            Ok(_) => {
14144                log::info!(
14145                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14146                );
14147                return None;
14148            }
14149            Err(i) => {
14150                self.find_all_references_task_sources.insert(i, head_anchor);
14151            }
14152        }
14153
14154        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14155        let workspace = self.workspace()?;
14156        let project = workspace.read(cx).project().clone();
14157        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14158        Some(cx.spawn_in(window, async move |editor, cx| {
14159            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14160                if let Ok(i) = editor
14161                    .find_all_references_task_sources
14162                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14163                {
14164                    editor.find_all_references_task_sources.remove(i);
14165                }
14166            });
14167
14168            let locations = references.await?;
14169            if locations.is_empty() {
14170                return anyhow::Ok(Navigated::No);
14171            }
14172
14173            workspace.update_in(cx, |workspace, window, cx| {
14174                let title = locations
14175                    .first()
14176                    .as_ref()
14177                    .map(|location| {
14178                        let buffer = location.buffer.read(cx);
14179                        format!(
14180                            "References to `{}`",
14181                            buffer
14182                                .text_for_range(location.range.clone())
14183                                .collect::<String>()
14184                        )
14185                    })
14186                    .unwrap();
14187                Self::open_locations_in_multibuffer(
14188                    workspace,
14189                    locations,
14190                    title,
14191                    false,
14192                    MultibufferSelectionMode::First,
14193                    window,
14194                    cx,
14195                );
14196                Navigated::Yes
14197            })
14198        }))
14199    }
14200
14201    /// Opens a multibuffer with the given project locations in it
14202    pub fn open_locations_in_multibuffer(
14203        workspace: &mut Workspace,
14204        mut locations: Vec<Location>,
14205        title: String,
14206        split: bool,
14207        multibuffer_selection_mode: MultibufferSelectionMode,
14208        window: &mut Window,
14209        cx: &mut Context<Workspace>,
14210    ) {
14211        // If there are multiple definitions, open them in a multibuffer
14212        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14213        let mut locations = locations.into_iter().peekable();
14214        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14215        let capability = workspace.project().read(cx).capability();
14216
14217        let excerpt_buffer = cx.new(|cx| {
14218            let mut multibuffer = MultiBuffer::new(capability);
14219            while let Some(location) = locations.next() {
14220                let buffer = location.buffer.read(cx);
14221                let mut ranges_for_buffer = Vec::new();
14222                let range = location.range.to_point(buffer);
14223                ranges_for_buffer.push(range.clone());
14224
14225                while let Some(next_location) = locations.peek() {
14226                    if next_location.buffer == location.buffer {
14227                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14228                        locations.next();
14229                    } else {
14230                        break;
14231                    }
14232                }
14233
14234                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14235                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14236                    PathKey::for_buffer(&location.buffer, cx),
14237                    location.buffer.clone(),
14238                    ranges_for_buffer,
14239                    DEFAULT_MULTIBUFFER_CONTEXT,
14240                    cx,
14241                );
14242                ranges.extend(new_ranges)
14243            }
14244
14245            multibuffer.with_title(title)
14246        });
14247
14248        let editor = cx.new(|cx| {
14249            Editor::for_multibuffer(
14250                excerpt_buffer,
14251                Some(workspace.project().clone()),
14252                window,
14253                cx,
14254            )
14255        });
14256        editor.update(cx, |editor, cx| {
14257            match multibuffer_selection_mode {
14258                MultibufferSelectionMode::First => {
14259                    if let Some(first_range) = ranges.first() {
14260                        editor.change_selections(None, window, cx, |selections| {
14261                            selections.clear_disjoint();
14262                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14263                        });
14264                    }
14265                    editor.highlight_background::<Self>(
14266                        &ranges,
14267                        |theme| theme.editor_highlighted_line_background,
14268                        cx,
14269                    );
14270                }
14271                MultibufferSelectionMode::All => {
14272                    editor.change_selections(None, window, cx, |selections| {
14273                        selections.clear_disjoint();
14274                        selections.select_anchor_ranges(ranges);
14275                    });
14276                }
14277            }
14278            editor.register_buffers_with_language_servers(cx);
14279        });
14280
14281        let item = Box::new(editor);
14282        let item_id = item.item_id();
14283
14284        if split {
14285            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14286        } else {
14287            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14288                let (preview_item_id, preview_item_idx) =
14289                    workspace.active_pane().update(cx, |pane, _| {
14290                        (pane.preview_item_id(), pane.preview_item_idx())
14291                    });
14292
14293                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14294
14295                if let Some(preview_item_id) = preview_item_id {
14296                    workspace.active_pane().update(cx, |pane, cx| {
14297                        pane.remove_item(preview_item_id, false, false, window, cx);
14298                    });
14299                }
14300            } else {
14301                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14302            }
14303        }
14304        workspace.active_pane().update(cx, |pane, cx| {
14305            pane.set_preview_item_id(Some(item_id), cx);
14306        });
14307    }
14308
14309    pub fn rename(
14310        &mut self,
14311        _: &Rename,
14312        window: &mut Window,
14313        cx: &mut Context<Self>,
14314    ) -> Option<Task<Result<()>>> {
14315        use language::ToOffset as _;
14316
14317        let provider = self.semantics_provider.clone()?;
14318        let selection = self.selections.newest_anchor().clone();
14319        let (cursor_buffer, cursor_buffer_position) = self
14320            .buffer
14321            .read(cx)
14322            .text_anchor_for_position(selection.head(), cx)?;
14323        let (tail_buffer, cursor_buffer_position_end) = self
14324            .buffer
14325            .read(cx)
14326            .text_anchor_for_position(selection.tail(), cx)?;
14327        if tail_buffer != cursor_buffer {
14328            return None;
14329        }
14330
14331        let snapshot = cursor_buffer.read(cx).snapshot();
14332        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14333        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14334        let prepare_rename = provider
14335            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14336            .unwrap_or_else(|| Task::ready(Ok(None)));
14337        drop(snapshot);
14338
14339        Some(cx.spawn_in(window, async move |this, cx| {
14340            let rename_range = if let Some(range) = prepare_rename.await? {
14341                Some(range)
14342            } else {
14343                this.update(cx, |this, cx| {
14344                    let buffer = this.buffer.read(cx).snapshot(cx);
14345                    let mut buffer_highlights = this
14346                        .document_highlights_for_position(selection.head(), &buffer)
14347                        .filter(|highlight| {
14348                            highlight.start.excerpt_id == selection.head().excerpt_id
14349                                && highlight.end.excerpt_id == selection.head().excerpt_id
14350                        });
14351                    buffer_highlights
14352                        .next()
14353                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14354                })?
14355            };
14356            if let Some(rename_range) = rename_range {
14357                this.update_in(cx, |this, window, cx| {
14358                    let snapshot = cursor_buffer.read(cx).snapshot();
14359                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14360                    let cursor_offset_in_rename_range =
14361                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14362                    let cursor_offset_in_rename_range_end =
14363                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14364
14365                    this.take_rename(false, window, cx);
14366                    let buffer = this.buffer.read(cx).read(cx);
14367                    let cursor_offset = selection.head().to_offset(&buffer);
14368                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14369                    let rename_end = rename_start + rename_buffer_range.len();
14370                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14371                    let mut old_highlight_id = None;
14372                    let old_name: Arc<str> = buffer
14373                        .chunks(rename_start..rename_end, true)
14374                        .map(|chunk| {
14375                            if old_highlight_id.is_none() {
14376                                old_highlight_id = chunk.syntax_highlight_id;
14377                            }
14378                            chunk.text
14379                        })
14380                        .collect::<String>()
14381                        .into();
14382
14383                    drop(buffer);
14384
14385                    // Position the selection in the rename editor so that it matches the current selection.
14386                    this.show_local_selections = false;
14387                    let rename_editor = cx.new(|cx| {
14388                        let mut editor = Editor::single_line(window, cx);
14389                        editor.buffer.update(cx, |buffer, cx| {
14390                            buffer.edit([(0..0, old_name.clone())], None, cx)
14391                        });
14392                        let rename_selection_range = match cursor_offset_in_rename_range
14393                            .cmp(&cursor_offset_in_rename_range_end)
14394                        {
14395                            Ordering::Equal => {
14396                                editor.select_all(&SelectAll, window, cx);
14397                                return editor;
14398                            }
14399                            Ordering::Less => {
14400                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14401                            }
14402                            Ordering::Greater => {
14403                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14404                            }
14405                        };
14406                        if rename_selection_range.end > old_name.len() {
14407                            editor.select_all(&SelectAll, window, cx);
14408                        } else {
14409                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14410                                s.select_ranges([rename_selection_range]);
14411                            });
14412                        }
14413                        editor
14414                    });
14415                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14416                        if e == &EditorEvent::Focused {
14417                            cx.emit(EditorEvent::FocusedIn)
14418                        }
14419                    })
14420                    .detach();
14421
14422                    let write_highlights =
14423                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14424                    let read_highlights =
14425                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14426                    let ranges = write_highlights
14427                        .iter()
14428                        .flat_map(|(_, ranges)| ranges.iter())
14429                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14430                        .cloned()
14431                        .collect();
14432
14433                    this.highlight_text::<Rename>(
14434                        ranges,
14435                        HighlightStyle {
14436                            fade_out: Some(0.6),
14437                            ..Default::default()
14438                        },
14439                        cx,
14440                    );
14441                    let rename_focus_handle = rename_editor.focus_handle(cx);
14442                    window.focus(&rename_focus_handle);
14443                    let block_id = this.insert_blocks(
14444                        [BlockProperties {
14445                            style: BlockStyle::Flex,
14446                            placement: BlockPlacement::Below(range.start),
14447                            height: Some(1),
14448                            render: Arc::new({
14449                                let rename_editor = rename_editor.clone();
14450                                move |cx: &mut BlockContext| {
14451                                    let mut text_style = cx.editor_style.text.clone();
14452                                    if let Some(highlight_style) = old_highlight_id
14453                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14454                                    {
14455                                        text_style = text_style.highlight(highlight_style);
14456                                    }
14457                                    div()
14458                                        .block_mouse_down()
14459                                        .pl(cx.anchor_x)
14460                                        .child(EditorElement::new(
14461                                            &rename_editor,
14462                                            EditorStyle {
14463                                                background: cx.theme().system().transparent,
14464                                                local_player: cx.editor_style.local_player,
14465                                                text: text_style,
14466                                                scrollbar_width: cx.editor_style.scrollbar_width,
14467                                                syntax: cx.editor_style.syntax.clone(),
14468                                                status: cx.editor_style.status.clone(),
14469                                                inlay_hints_style: HighlightStyle {
14470                                                    font_weight: Some(FontWeight::BOLD),
14471                                                    ..make_inlay_hints_style(cx.app)
14472                                                },
14473                                                inline_completion_styles: make_suggestion_styles(
14474                                                    cx.app,
14475                                                ),
14476                                                ..EditorStyle::default()
14477                                            },
14478                                        ))
14479                                        .into_any_element()
14480                                }
14481                            }),
14482                            priority: 0,
14483                        }],
14484                        Some(Autoscroll::fit()),
14485                        cx,
14486                    )[0];
14487                    this.pending_rename = Some(RenameState {
14488                        range,
14489                        old_name,
14490                        editor: rename_editor,
14491                        block_id,
14492                    });
14493                })?;
14494            }
14495
14496            Ok(())
14497        }))
14498    }
14499
14500    pub fn confirm_rename(
14501        &mut self,
14502        _: &ConfirmRename,
14503        window: &mut Window,
14504        cx: &mut Context<Self>,
14505    ) -> Option<Task<Result<()>>> {
14506        let rename = self.take_rename(false, window, cx)?;
14507        let workspace = self.workspace()?.downgrade();
14508        let (buffer, start) = self
14509            .buffer
14510            .read(cx)
14511            .text_anchor_for_position(rename.range.start, cx)?;
14512        let (end_buffer, _) = self
14513            .buffer
14514            .read(cx)
14515            .text_anchor_for_position(rename.range.end, cx)?;
14516        if buffer != end_buffer {
14517            return None;
14518        }
14519
14520        let old_name = rename.old_name;
14521        let new_name = rename.editor.read(cx).text(cx);
14522
14523        let rename = self.semantics_provider.as_ref()?.perform_rename(
14524            &buffer,
14525            start,
14526            new_name.clone(),
14527            cx,
14528        )?;
14529
14530        Some(cx.spawn_in(window, async move |editor, cx| {
14531            let project_transaction = rename.await?;
14532            Self::open_project_transaction(
14533                &editor,
14534                workspace,
14535                project_transaction,
14536                format!("Rename: {}{}", old_name, new_name),
14537                cx,
14538            )
14539            .await?;
14540
14541            editor.update(cx, |editor, cx| {
14542                editor.refresh_document_highlights(cx);
14543            })?;
14544            Ok(())
14545        }))
14546    }
14547
14548    fn take_rename(
14549        &mut self,
14550        moving_cursor: bool,
14551        window: &mut Window,
14552        cx: &mut Context<Self>,
14553    ) -> Option<RenameState> {
14554        let rename = self.pending_rename.take()?;
14555        if rename.editor.focus_handle(cx).is_focused(window) {
14556            window.focus(&self.focus_handle);
14557        }
14558
14559        self.remove_blocks(
14560            [rename.block_id].into_iter().collect(),
14561            Some(Autoscroll::fit()),
14562            cx,
14563        );
14564        self.clear_highlights::<Rename>(cx);
14565        self.show_local_selections = true;
14566
14567        if moving_cursor {
14568            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14569                editor.selections.newest::<usize>(cx).head()
14570            });
14571
14572            // Update the selection to match the position of the selection inside
14573            // the rename editor.
14574            let snapshot = self.buffer.read(cx).read(cx);
14575            let rename_range = rename.range.to_offset(&snapshot);
14576            let cursor_in_editor = snapshot
14577                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14578                .min(rename_range.end);
14579            drop(snapshot);
14580
14581            self.change_selections(None, window, cx, |s| {
14582                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14583            });
14584        } else {
14585            self.refresh_document_highlights(cx);
14586        }
14587
14588        Some(rename)
14589    }
14590
14591    pub fn pending_rename(&self) -> Option<&RenameState> {
14592        self.pending_rename.as_ref()
14593    }
14594
14595    fn format(
14596        &mut self,
14597        _: &Format,
14598        window: &mut Window,
14599        cx: &mut Context<Self>,
14600    ) -> Option<Task<Result<()>>> {
14601        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14602
14603        let project = match &self.project {
14604            Some(project) => project.clone(),
14605            None => return None,
14606        };
14607
14608        Some(self.perform_format(
14609            project,
14610            FormatTrigger::Manual,
14611            FormatTarget::Buffers,
14612            window,
14613            cx,
14614        ))
14615    }
14616
14617    fn format_selections(
14618        &mut self,
14619        _: &FormatSelections,
14620        window: &mut Window,
14621        cx: &mut Context<Self>,
14622    ) -> Option<Task<Result<()>>> {
14623        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14624
14625        let project = match &self.project {
14626            Some(project) => project.clone(),
14627            None => return None,
14628        };
14629
14630        let ranges = self
14631            .selections
14632            .all_adjusted(cx)
14633            .into_iter()
14634            .map(|selection| selection.range())
14635            .collect_vec();
14636
14637        Some(self.perform_format(
14638            project,
14639            FormatTrigger::Manual,
14640            FormatTarget::Ranges(ranges),
14641            window,
14642            cx,
14643        ))
14644    }
14645
14646    fn perform_format(
14647        &mut self,
14648        project: Entity<Project>,
14649        trigger: FormatTrigger,
14650        target: FormatTarget,
14651        window: &mut Window,
14652        cx: &mut Context<Self>,
14653    ) -> Task<Result<()>> {
14654        let buffer = self.buffer.clone();
14655        let (buffers, target) = match target {
14656            FormatTarget::Buffers => {
14657                let mut buffers = buffer.read(cx).all_buffers();
14658                if trigger == FormatTrigger::Save {
14659                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14660                }
14661                (buffers, LspFormatTarget::Buffers)
14662            }
14663            FormatTarget::Ranges(selection_ranges) => {
14664                let multi_buffer = buffer.read(cx);
14665                let snapshot = multi_buffer.read(cx);
14666                let mut buffers = HashSet::default();
14667                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14668                    BTreeMap::new();
14669                for selection_range in selection_ranges {
14670                    for (buffer, buffer_range, _) in
14671                        snapshot.range_to_buffer_ranges(selection_range)
14672                    {
14673                        let buffer_id = buffer.remote_id();
14674                        let start = buffer.anchor_before(buffer_range.start);
14675                        let end = buffer.anchor_after(buffer_range.end);
14676                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14677                        buffer_id_to_ranges
14678                            .entry(buffer_id)
14679                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14680                            .or_insert_with(|| vec![start..end]);
14681                    }
14682                }
14683                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14684            }
14685        };
14686
14687        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14688        let selections_prev = transaction_id_prev
14689            .and_then(|transaction_id_prev| {
14690                // default to selections as they were after the last edit, if we have them,
14691                // instead of how they are now.
14692                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14693                // will take you back to where you made the last edit, instead of staying where you scrolled
14694                self.selection_history
14695                    .transaction(transaction_id_prev)
14696                    .map(|t| t.0.clone())
14697            })
14698            .unwrap_or_else(|| {
14699                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14700                self.selections.disjoint_anchors()
14701            });
14702
14703        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14704        let format = project.update(cx, |project, cx| {
14705            project.format(buffers, target, true, trigger, cx)
14706        });
14707
14708        cx.spawn_in(window, async move |editor, cx| {
14709            let transaction = futures::select_biased! {
14710                transaction = format.log_err().fuse() => transaction,
14711                () = timeout => {
14712                    log::warn!("timed out waiting for formatting");
14713                    None
14714                }
14715            };
14716
14717            buffer
14718                .update(cx, |buffer, cx| {
14719                    if let Some(transaction) = transaction {
14720                        if !buffer.is_singleton() {
14721                            buffer.push_transaction(&transaction.0, cx);
14722                        }
14723                    }
14724                    cx.notify();
14725                })
14726                .ok();
14727
14728            if let Some(transaction_id_now) =
14729                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14730            {
14731                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14732                if has_new_transaction {
14733                    _ = editor.update(cx, |editor, _| {
14734                        editor
14735                            .selection_history
14736                            .insert_transaction(transaction_id_now, selections_prev);
14737                    });
14738                }
14739            }
14740
14741            Ok(())
14742        })
14743    }
14744
14745    fn organize_imports(
14746        &mut self,
14747        _: &OrganizeImports,
14748        window: &mut Window,
14749        cx: &mut Context<Self>,
14750    ) -> Option<Task<Result<()>>> {
14751        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14752        let project = match &self.project {
14753            Some(project) => project.clone(),
14754            None => return None,
14755        };
14756        Some(self.perform_code_action_kind(
14757            project,
14758            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14759            window,
14760            cx,
14761        ))
14762    }
14763
14764    fn perform_code_action_kind(
14765        &mut self,
14766        project: Entity<Project>,
14767        kind: CodeActionKind,
14768        window: &mut Window,
14769        cx: &mut Context<Self>,
14770    ) -> Task<Result<()>> {
14771        let buffer = self.buffer.clone();
14772        let buffers = buffer.read(cx).all_buffers();
14773        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14774        let apply_action = project.update(cx, |project, cx| {
14775            project.apply_code_action_kind(buffers, kind, true, cx)
14776        });
14777        cx.spawn_in(window, async move |_, cx| {
14778            let transaction = futures::select_biased! {
14779                () = timeout => {
14780                    log::warn!("timed out waiting for executing code action");
14781                    None
14782                }
14783                transaction = apply_action.log_err().fuse() => transaction,
14784            };
14785            buffer
14786                .update(cx, |buffer, cx| {
14787                    // check if we need this
14788                    if let Some(transaction) = transaction {
14789                        if !buffer.is_singleton() {
14790                            buffer.push_transaction(&transaction.0, cx);
14791                        }
14792                    }
14793                    cx.notify();
14794                })
14795                .ok();
14796            Ok(())
14797        })
14798    }
14799
14800    fn restart_language_server(
14801        &mut self,
14802        _: &RestartLanguageServer,
14803        _: &mut Window,
14804        cx: &mut Context<Self>,
14805    ) {
14806        if let Some(project) = self.project.clone() {
14807            self.buffer.update(cx, |multi_buffer, cx| {
14808                project.update(cx, |project, cx| {
14809                    project.restart_language_servers_for_buffers(
14810                        multi_buffer.all_buffers().into_iter().collect(),
14811                        cx,
14812                    );
14813                });
14814            })
14815        }
14816    }
14817
14818    fn stop_language_server(
14819        &mut self,
14820        _: &StopLanguageServer,
14821        _: &mut Window,
14822        cx: &mut Context<Self>,
14823    ) {
14824        if let Some(project) = self.project.clone() {
14825            self.buffer.update(cx, |multi_buffer, cx| {
14826                project.update(cx, |project, cx| {
14827                    project.stop_language_servers_for_buffers(
14828                        multi_buffer.all_buffers().into_iter().collect(),
14829                        cx,
14830                    );
14831                    cx.emit(project::Event::RefreshInlayHints);
14832                });
14833            });
14834        }
14835    }
14836
14837    fn cancel_language_server_work(
14838        workspace: &mut Workspace,
14839        _: &actions::CancelLanguageServerWork,
14840        _: &mut Window,
14841        cx: &mut Context<Workspace>,
14842    ) {
14843        let project = workspace.project();
14844        let buffers = workspace
14845            .active_item(cx)
14846            .and_then(|item| item.act_as::<Editor>(cx))
14847            .map_or(HashSet::default(), |editor| {
14848                editor.read(cx).buffer.read(cx).all_buffers()
14849            });
14850        project.update(cx, |project, cx| {
14851            project.cancel_language_server_work_for_buffers(buffers, cx);
14852        });
14853    }
14854
14855    fn show_character_palette(
14856        &mut self,
14857        _: &ShowCharacterPalette,
14858        window: &mut Window,
14859        _: &mut Context<Self>,
14860    ) {
14861        window.show_character_palette();
14862    }
14863
14864    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14865        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14866            let buffer = self.buffer.read(cx).snapshot(cx);
14867            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14868            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14869            let is_valid = buffer
14870                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14871                .any(|entry| {
14872                    entry.diagnostic.is_primary
14873                        && !entry.range.is_empty()
14874                        && entry.range.start == primary_range_start
14875                        && entry.diagnostic.message == active_diagnostics.active_message
14876                });
14877
14878            if !is_valid {
14879                self.dismiss_diagnostics(cx);
14880            }
14881        }
14882    }
14883
14884    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14885        match &self.active_diagnostics {
14886            ActiveDiagnostic::Group(group) => Some(group),
14887            _ => None,
14888        }
14889    }
14890
14891    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14892        self.dismiss_diagnostics(cx);
14893        self.active_diagnostics = ActiveDiagnostic::All;
14894    }
14895
14896    fn activate_diagnostics(
14897        &mut self,
14898        buffer_id: BufferId,
14899        diagnostic: DiagnosticEntry<usize>,
14900        window: &mut Window,
14901        cx: &mut Context<Self>,
14902    ) {
14903        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14904            return;
14905        }
14906        self.dismiss_diagnostics(cx);
14907        let snapshot = self.snapshot(window, cx);
14908        let buffer = self.buffer.read(cx).snapshot(cx);
14909        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
14910            return;
14911        };
14912
14913        let diagnostic_group = buffer
14914            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14915            .collect::<Vec<_>>();
14916
14917        let blocks =
14918            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
14919
14920        let blocks = self.display_map.update(cx, |display_map, cx| {
14921            display_map.insert_blocks(blocks, cx).into_iter().collect()
14922        });
14923        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14924            active_range: buffer.anchor_before(diagnostic.range.start)
14925                ..buffer.anchor_after(diagnostic.range.end),
14926            active_message: diagnostic.diagnostic.message.clone(),
14927            group_id: diagnostic.diagnostic.group_id,
14928            blocks,
14929        });
14930        cx.notify();
14931    }
14932
14933    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14934        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14935            return;
14936        };
14937
14938        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14939        if let ActiveDiagnostic::Group(group) = prev {
14940            self.display_map.update(cx, |display_map, cx| {
14941                display_map.remove_blocks(group.blocks, cx);
14942            });
14943            cx.notify();
14944        }
14945    }
14946
14947    /// Disable inline diagnostics rendering for this editor.
14948    pub fn disable_inline_diagnostics(&mut self) {
14949        self.inline_diagnostics_enabled = false;
14950        self.inline_diagnostics_update = Task::ready(());
14951        self.inline_diagnostics.clear();
14952    }
14953
14954    pub fn inline_diagnostics_enabled(&self) -> bool {
14955        self.inline_diagnostics_enabled
14956    }
14957
14958    pub fn show_inline_diagnostics(&self) -> bool {
14959        self.show_inline_diagnostics
14960    }
14961
14962    pub fn toggle_inline_diagnostics(
14963        &mut self,
14964        _: &ToggleInlineDiagnostics,
14965        window: &mut Window,
14966        cx: &mut Context<Editor>,
14967    ) {
14968        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14969        self.refresh_inline_diagnostics(false, window, cx);
14970    }
14971
14972    fn refresh_inline_diagnostics(
14973        &mut self,
14974        debounce: bool,
14975        window: &mut Window,
14976        cx: &mut Context<Self>,
14977    ) {
14978        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14979            self.inline_diagnostics_update = Task::ready(());
14980            self.inline_diagnostics.clear();
14981            return;
14982        }
14983
14984        let debounce_ms = ProjectSettings::get_global(cx)
14985            .diagnostics
14986            .inline
14987            .update_debounce_ms;
14988        let debounce = if debounce && debounce_ms > 0 {
14989            Some(Duration::from_millis(debounce_ms))
14990        } else {
14991            None
14992        };
14993        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14994            let editor = editor.upgrade().unwrap();
14995
14996            if let Some(debounce) = debounce {
14997                cx.background_executor().timer(debounce).await;
14998            }
14999            let Some(snapshot) = editor
15000                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15001                .ok()
15002            else {
15003                return;
15004            };
15005
15006            let new_inline_diagnostics = cx
15007                .background_spawn(async move {
15008                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15009                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15010                        let message = diagnostic_entry
15011                            .diagnostic
15012                            .message
15013                            .split_once('\n')
15014                            .map(|(line, _)| line)
15015                            .map(SharedString::new)
15016                            .unwrap_or_else(|| {
15017                                SharedString::from(diagnostic_entry.diagnostic.message)
15018                            });
15019                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15020                        let (Ok(i) | Err(i)) = inline_diagnostics
15021                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15022                        inline_diagnostics.insert(
15023                            i,
15024                            (
15025                                start_anchor,
15026                                InlineDiagnostic {
15027                                    message,
15028                                    group_id: diagnostic_entry.diagnostic.group_id,
15029                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15030                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15031                                    severity: diagnostic_entry.diagnostic.severity,
15032                                },
15033                            ),
15034                        );
15035                    }
15036                    inline_diagnostics
15037                })
15038                .await;
15039
15040            editor
15041                .update(cx, |editor, cx| {
15042                    editor.inline_diagnostics = new_inline_diagnostics;
15043                    cx.notify();
15044                })
15045                .ok();
15046        });
15047    }
15048
15049    pub fn set_selections_from_remote(
15050        &mut self,
15051        selections: Vec<Selection<Anchor>>,
15052        pending_selection: Option<Selection<Anchor>>,
15053        window: &mut Window,
15054        cx: &mut Context<Self>,
15055    ) {
15056        let old_cursor_position = self.selections.newest_anchor().head();
15057        self.selections.change_with(cx, |s| {
15058            s.select_anchors(selections);
15059            if let Some(pending_selection) = pending_selection {
15060                s.set_pending(pending_selection, SelectMode::Character);
15061            } else {
15062                s.clear_pending();
15063            }
15064        });
15065        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15066    }
15067
15068    fn push_to_selection_history(&mut self) {
15069        self.selection_history.push(SelectionHistoryEntry {
15070            selections: self.selections.disjoint_anchors(),
15071            select_next_state: self.select_next_state.clone(),
15072            select_prev_state: self.select_prev_state.clone(),
15073            add_selections_state: self.add_selections_state.clone(),
15074        });
15075    }
15076
15077    pub fn transact(
15078        &mut self,
15079        window: &mut Window,
15080        cx: &mut Context<Self>,
15081        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15082    ) -> Option<TransactionId> {
15083        self.start_transaction_at(Instant::now(), window, cx);
15084        update(self, window, cx);
15085        self.end_transaction_at(Instant::now(), cx)
15086    }
15087
15088    pub fn start_transaction_at(
15089        &mut self,
15090        now: Instant,
15091        window: &mut Window,
15092        cx: &mut Context<Self>,
15093    ) {
15094        self.end_selection(window, cx);
15095        if let Some(tx_id) = self
15096            .buffer
15097            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15098        {
15099            self.selection_history
15100                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15101            cx.emit(EditorEvent::TransactionBegun {
15102                transaction_id: tx_id,
15103            })
15104        }
15105    }
15106
15107    pub fn end_transaction_at(
15108        &mut self,
15109        now: Instant,
15110        cx: &mut Context<Self>,
15111    ) -> Option<TransactionId> {
15112        if let Some(transaction_id) = self
15113            .buffer
15114            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15115        {
15116            if let Some((_, end_selections)) =
15117                self.selection_history.transaction_mut(transaction_id)
15118            {
15119                *end_selections = Some(self.selections.disjoint_anchors());
15120            } else {
15121                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15122            }
15123
15124            cx.emit(EditorEvent::Edited { transaction_id });
15125            Some(transaction_id)
15126        } else {
15127            None
15128        }
15129    }
15130
15131    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15132        if self.selection_mark_mode {
15133            self.change_selections(None, window, cx, |s| {
15134                s.move_with(|_, sel| {
15135                    sel.collapse_to(sel.head(), SelectionGoal::None);
15136                });
15137            })
15138        }
15139        self.selection_mark_mode = true;
15140        cx.notify();
15141    }
15142
15143    pub fn swap_selection_ends(
15144        &mut self,
15145        _: &actions::SwapSelectionEnds,
15146        window: &mut Window,
15147        cx: &mut Context<Self>,
15148    ) {
15149        self.change_selections(None, window, cx, |s| {
15150            s.move_with(|_, sel| {
15151                if sel.start != sel.end {
15152                    sel.reversed = !sel.reversed
15153                }
15154            });
15155        });
15156        self.request_autoscroll(Autoscroll::newest(), cx);
15157        cx.notify();
15158    }
15159
15160    pub fn toggle_fold(
15161        &mut self,
15162        _: &actions::ToggleFold,
15163        window: &mut Window,
15164        cx: &mut Context<Self>,
15165    ) {
15166        if self.is_singleton(cx) {
15167            let selection = self.selections.newest::<Point>(cx);
15168
15169            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15170            let range = if selection.is_empty() {
15171                let point = selection.head().to_display_point(&display_map);
15172                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15173                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15174                    .to_point(&display_map);
15175                start..end
15176            } else {
15177                selection.range()
15178            };
15179            if display_map.folds_in_range(range).next().is_some() {
15180                self.unfold_lines(&Default::default(), window, cx)
15181            } else {
15182                self.fold(&Default::default(), window, cx)
15183            }
15184        } else {
15185            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15186            let buffer_ids: HashSet<_> = self
15187                .selections
15188                .disjoint_anchor_ranges()
15189                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15190                .collect();
15191
15192            let should_unfold = buffer_ids
15193                .iter()
15194                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15195
15196            for buffer_id in buffer_ids {
15197                if should_unfold {
15198                    self.unfold_buffer(buffer_id, cx);
15199                } else {
15200                    self.fold_buffer(buffer_id, cx);
15201                }
15202            }
15203        }
15204    }
15205
15206    pub fn toggle_fold_recursive(
15207        &mut self,
15208        _: &actions::ToggleFoldRecursive,
15209        window: &mut Window,
15210        cx: &mut Context<Self>,
15211    ) {
15212        let selection = self.selections.newest::<Point>(cx);
15213
15214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15215        let range = if selection.is_empty() {
15216            let point = selection.head().to_display_point(&display_map);
15217            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15218            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15219                .to_point(&display_map);
15220            start..end
15221        } else {
15222            selection.range()
15223        };
15224        if display_map.folds_in_range(range).next().is_some() {
15225            self.unfold_recursive(&Default::default(), window, cx)
15226        } else {
15227            self.fold_recursive(&Default::default(), window, cx)
15228        }
15229    }
15230
15231    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15232        if self.is_singleton(cx) {
15233            let mut to_fold = Vec::new();
15234            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15235            let selections = self.selections.all_adjusted(cx);
15236
15237            for selection in selections {
15238                let range = selection.range().sorted();
15239                let buffer_start_row = range.start.row;
15240
15241                if range.start.row != range.end.row {
15242                    let mut found = false;
15243                    let mut row = range.start.row;
15244                    while row <= range.end.row {
15245                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15246                        {
15247                            found = true;
15248                            row = crease.range().end.row + 1;
15249                            to_fold.push(crease);
15250                        } else {
15251                            row += 1
15252                        }
15253                    }
15254                    if found {
15255                        continue;
15256                    }
15257                }
15258
15259                for row in (0..=range.start.row).rev() {
15260                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15261                        if crease.range().end.row >= buffer_start_row {
15262                            to_fold.push(crease);
15263                            if row <= range.start.row {
15264                                break;
15265                            }
15266                        }
15267                    }
15268                }
15269            }
15270
15271            self.fold_creases(to_fold, true, window, cx);
15272        } else {
15273            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15274            let buffer_ids = self
15275                .selections
15276                .disjoint_anchor_ranges()
15277                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15278                .collect::<HashSet<_>>();
15279            for buffer_id in buffer_ids {
15280                self.fold_buffer(buffer_id, cx);
15281            }
15282        }
15283    }
15284
15285    fn fold_at_level(
15286        &mut self,
15287        fold_at: &FoldAtLevel,
15288        window: &mut Window,
15289        cx: &mut Context<Self>,
15290    ) {
15291        if !self.buffer.read(cx).is_singleton() {
15292            return;
15293        }
15294
15295        let fold_at_level = fold_at.0;
15296        let snapshot = self.buffer.read(cx).snapshot(cx);
15297        let mut to_fold = Vec::new();
15298        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15299
15300        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15301            while start_row < end_row {
15302                match self
15303                    .snapshot(window, cx)
15304                    .crease_for_buffer_row(MultiBufferRow(start_row))
15305                {
15306                    Some(crease) => {
15307                        let nested_start_row = crease.range().start.row + 1;
15308                        let nested_end_row = crease.range().end.row;
15309
15310                        if current_level < fold_at_level {
15311                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15312                        } else if current_level == fold_at_level {
15313                            to_fold.push(crease);
15314                        }
15315
15316                        start_row = nested_end_row + 1;
15317                    }
15318                    None => start_row += 1,
15319                }
15320            }
15321        }
15322
15323        self.fold_creases(to_fold, true, window, cx);
15324    }
15325
15326    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15327        if self.buffer.read(cx).is_singleton() {
15328            let mut fold_ranges = Vec::new();
15329            let snapshot = self.buffer.read(cx).snapshot(cx);
15330
15331            for row in 0..snapshot.max_row().0 {
15332                if let Some(foldable_range) = self
15333                    .snapshot(window, cx)
15334                    .crease_for_buffer_row(MultiBufferRow(row))
15335                {
15336                    fold_ranges.push(foldable_range);
15337                }
15338            }
15339
15340            self.fold_creases(fold_ranges, true, window, cx);
15341        } else {
15342            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15343                editor
15344                    .update_in(cx, |editor, _, cx| {
15345                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15346                            editor.fold_buffer(buffer_id, cx);
15347                        }
15348                    })
15349                    .ok();
15350            });
15351        }
15352    }
15353
15354    pub fn fold_function_bodies(
15355        &mut self,
15356        _: &actions::FoldFunctionBodies,
15357        window: &mut Window,
15358        cx: &mut Context<Self>,
15359    ) {
15360        let snapshot = self.buffer.read(cx).snapshot(cx);
15361
15362        let ranges = snapshot
15363            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15364            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15365            .collect::<Vec<_>>();
15366
15367        let creases = ranges
15368            .into_iter()
15369            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15370            .collect();
15371
15372        self.fold_creases(creases, true, window, cx);
15373    }
15374
15375    pub fn fold_recursive(
15376        &mut self,
15377        _: &actions::FoldRecursive,
15378        window: &mut Window,
15379        cx: &mut Context<Self>,
15380    ) {
15381        let mut to_fold = Vec::new();
15382        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15383        let selections = self.selections.all_adjusted(cx);
15384
15385        for selection in selections {
15386            let range = selection.range().sorted();
15387            let buffer_start_row = range.start.row;
15388
15389            if range.start.row != range.end.row {
15390                let mut found = false;
15391                for row in range.start.row..=range.end.row {
15392                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15393                        found = true;
15394                        to_fold.push(crease);
15395                    }
15396                }
15397                if found {
15398                    continue;
15399                }
15400            }
15401
15402            for row in (0..=range.start.row).rev() {
15403                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15404                    if crease.range().end.row >= buffer_start_row {
15405                        to_fold.push(crease);
15406                    } else {
15407                        break;
15408                    }
15409                }
15410            }
15411        }
15412
15413        self.fold_creases(to_fold, true, window, cx);
15414    }
15415
15416    pub fn fold_at(
15417        &mut self,
15418        buffer_row: MultiBufferRow,
15419        window: &mut Window,
15420        cx: &mut Context<Self>,
15421    ) {
15422        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15423
15424        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15425            let autoscroll = self
15426                .selections
15427                .all::<Point>(cx)
15428                .iter()
15429                .any(|selection| crease.range().overlaps(&selection.range()));
15430
15431            self.fold_creases(vec![crease], autoscroll, window, cx);
15432        }
15433    }
15434
15435    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15436        if self.is_singleton(cx) {
15437            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15438            let buffer = &display_map.buffer_snapshot;
15439            let selections = self.selections.all::<Point>(cx);
15440            let ranges = selections
15441                .iter()
15442                .map(|s| {
15443                    let range = s.display_range(&display_map).sorted();
15444                    let mut start = range.start.to_point(&display_map);
15445                    let mut end = range.end.to_point(&display_map);
15446                    start.column = 0;
15447                    end.column = buffer.line_len(MultiBufferRow(end.row));
15448                    start..end
15449                })
15450                .collect::<Vec<_>>();
15451
15452            self.unfold_ranges(&ranges, true, true, cx);
15453        } else {
15454            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15455            let buffer_ids = self
15456                .selections
15457                .disjoint_anchor_ranges()
15458                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15459                .collect::<HashSet<_>>();
15460            for buffer_id in buffer_ids {
15461                self.unfold_buffer(buffer_id, cx);
15462            }
15463        }
15464    }
15465
15466    pub fn unfold_recursive(
15467        &mut self,
15468        _: &UnfoldRecursive,
15469        _window: &mut Window,
15470        cx: &mut Context<Self>,
15471    ) {
15472        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15473        let selections = self.selections.all::<Point>(cx);
15474        let ranges = selections
15475            .iter()
15476            .map(|s| {
15477                let mut range = s.display_range(&display_map).sorted();
15478                *range.start.column_mut() = 0;
15479                *range.end.column_mut() = display_map.line_len(range.end.row());
15480                let start = range.start.to_point(&display_map);
15481                let end = range.end.to_point(&display_map);
15482                start..end
15483            })
15484            .collect::<Vec<_>>();
15485
15486        self.unfold_ranges(&ranges, true, true, cx);
15487    }
15488
15489    pub fn unfold_at(
15490        &mut self,
15491        buffer_row: MultiBufferRow,
15492        _window: &mut Window,
15493        cx: &mut Context<Self>,
15494    ) {
15495        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15496
15497        let intersection_range = Point::new(buffer_row.0, 0)
15498            ..Point::new(
15499                buffer_row.0,
15500                display_map.buffer_snapshot.line_len(buffer_row),
15501            );
15502
15503        let autoscroll = self
15504            .selections
15505            .all::<Point>(cx)
15506            .iter()
15507            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15508
15509        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15510    }
15511
15512    pub fn unfold_all(
15513        &mut self,
15514        _: &actions::UnfoldAll,
15515        _window: &mut Window,
15516        cx: &mut Context<Self>,
15517    ) {
15518        if self.buffer.read(cx).is_singleton() {
15519            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15520            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15521        } else {
15522            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15523                editor
15524                    .update(cx, |editor, cx| {
15525                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15526                            editor.unfold_buffer(buffer_id, cx);
15527                        }
15528                    })
15529                    .ok();
15530            });
15531        }
15532    }
15533
15534    pub fn fold_selected_ranges(
15535        &mut self,
15536        _: &FoldSelectedRanges,
15537        window: &mut Window,
15538        cx: &mut Context<Self>,
15539    ) {
15540        let selections = self.selections.all_adjusted(cx);
15541        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15542        let ranges = selections
15543            .into_iter()
15544            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15545            .collect::<Vec<_>>();
15546        self.fold_creases(ranges, true, window, cx);
15547    }
15548
15549    pub fn fold_ranges<T: ToOffset + Clone>(
15550        &mut self,
15551        ranges: Vec<Range<T>>,
15552        auto_scroll: bool,
15553        window: &mut Window,
15554        cx: &mut Context<Self>,
15555    ) {
15556        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15557        let ranges = ranges
15558            .into_iter()
15559            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15560            .collect::<Vec<_>>();
15561        self.fold_creases(ranges, auto_scroll, window, cx);
15562    }
15563
15564    pub fn fold_creases<T: ToOffset + Clone>(
15565        &mut self,
15566        creases: Vec<Crease<T>>,
15567        auto_scroll: bool,
15568        _window: &mut Window,
15569        cx: &mut Context<Self>,
15570    ) {
15571        if creases.is_empty() {
15572            return;
15573        }
15574
15575        let mut buffers_affected = HashSet::default();
15576        let multi_buffer = self.buffer().read(cx);
15577        for crease in &creases {
15578            if let Some((_, buffer, _)) =
15579                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15580            {
15581                buffers_affected.insert(buffer.read(cx).remote_id());
15582            };
15583        }
15584
15585        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15586
15587        if auto_scroll {
15588            self.request_autoscroll(Autoscroll::fit(), cx);
15589        }
15590
15591        cx.notify();
15592
15593        self.scrollbar_marker_state.dirty = true;
15594        self.folds_did_change(cx);
15595    }
15596
15597    /// Removes any folds whose ranges intersect any of the given ranges.
15598    pub fn unfold_ranges<T: ToOffset + Clone>(
15599        &mut self,
15600        ranges: &[Range<T>],
15601        inclusive: bool,
15602        auto_scroll: bool,
15603        cx: &mut Context<Self>,
15604    ) {
15605        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15606            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15607        });
15608        self.folds_did_change(cx);
15609    }
15610
15611    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15612        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15613            return;
15614        }
15615        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15616        self.display_map.update(cx, |display_map, cx| {
15617            display_map.fold_buffers([buffer_id], cx)
15618        });
15619        cx.emit(EditorEvent::BufferFoldToggled {
15620            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15621            folded: true,
15622        });
15623        cx.notify();
15624    }
15625
15626    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15627        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15628            return;
15629        }
15630        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15631        self.display_map.update(cx, |display_map, cx| {
15632            display_map.unfold_buffers([buffer_id], cx);
15633        });
15634        cx.emit(EditorEvent::BufferFoldToggled {
15635            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15636            folded: false,
15637        });
15638        cx.notify();
15639    }
15640
15641    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15642        self.display_map.read(cx).is_buffer_folded(buffer)
15643    }
15644
15645    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15646        self.display_map.read(cx).folded_buffers()
15647    }
15648
15649    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15650        self.display_map.update(cx, |display_map, cx| {
15651            display_map.disable_header_for_buffer(buffer_id, cx);
15652        });
15653        cx.notify();
15654    }
15655
15656    /// Removes any folds with the given ranges.
15657    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15658        &mut self,
15659        ranges: &[Range<T>],
15660        type_id: TypeId,
15661        auto_scroll: bool,
15662        cx: &mut Context<Self>,
15663    ) {
15664        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15665            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15666        });
15667        self.folds_did_change(cx);
15668    }
15669
15670    fn remove_folds_with<T: ToOffset + Clone>(
15671        &mut self,
15672        ranges: &[Range<T>],
15673        auto_scroll: bool,
15674        cx: &mut Context<Self>,
15675        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15676    ) {
15677        if ranges.is_empty() {
15678            return;
15679        }
15680
15681        let mut buffers_affected = HashSet::default();
15682        let multi_buffer = self.buffer().read(cx);
15683        for range in ranges {
15684            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15685                buffers_affected.insert(buffer.read(cx).remote_id());
15686            };
15687        }
15688
15689        self.display_map.update(cx, update);
15690
15691        if auto_scroll {
15692            self.request_autoscroll(Autoscroll::fit(), cx);
15693        }
15694
15695        cx.notify();
15696        self.scrollbar_marker_state.dirty = true;
15697        self.active_indent_guides_state.dirty = true;
15698    }
15699
15700    pub fn update_fold_widths(
15701        &mut self,
15702        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15703        cx: &mut Context<Self>,
15704    ) -> bool {
15705        self.display_map
15706            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15707    }
15708
15709    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15710        self.display_map.read(cx).fold_placeholder.clone()
15711    }
15712
15713    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15714        self.buffer.update(cx, |buffer, cx| {
15715            buffer.set_all_diff_hunks_expanded(cx);
15716        });
15717    }
15718
15719    pub fn expand_all_diff_hunks(
15720        &mut self,
15721        _: &ExpandAllDiffHunks,
15722        _window: &mut Window,
15723        cx: &mut Context<Self>,
15724    ) {
15725        self.buffer.update(cx, |buffer, cx| {
15726            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15727        });
15728    }
15729
15730    pub fn toggle_selected_diff_hunks(
15731        &mut self,
15732        _: &ToggleSelectedDiffHunks,
15733        _window: &mut Window,
15734        cx: &mut Context<Self>,
15735    ) {
15736        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15737        self.toggle_diff_hunks_in_ranges(ranges, cx);
15738    }
15739
15740    pub fn diff_hunks_in_ranges<'a>(
15741        &'a self,
15742        ranges: &'a [Range<Anchor>],
15743        buffer: &'a MultiBufferSnapshot,
15744    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15745        ranges.iter().flat_map(move |range| {
15746            let end_excerpt_id = range.end.excerpt_id;
15747            let range = range.to_point(buffer);
15748            let mut peek_end = range.end;
15749            if range.end.row < buffer.max_row().0 {
15750                peek_end = Point::new(range.end.row + 1, 0);
15751            }
15752            buffer
15753                .diff_hunks_in_range(range.start..peek_end)
15754                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15755        })
15756    }
15757
15758    pub fn has_stageable_diff_hunks_in_ranges(
15759        &self,
15760        ranges: &[Range<Anchor>],
15761        snapshot: &MultiBufferSnapshot,
15762    ) -> bool {
15763        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15764        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15765    }
15766
15767    pub fn toggle_staged_selected_diff_hunks(
15768        &mut self,
15769        _: &::git::ToggleStaged,
15770        _: &mut Window,
15771        cx: &mut Context<Self>,
15772    ) {
15773        let snapshot = self.buffer.read(cx).snapshot(cx);
15774        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15775        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15776        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15777    }
15778
15779    pub fn set_render_diff_hunk_controls(
15780        &mut self,
15781        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15782        cx: &mut Context<Self>,
15783    ) {
15784        self.render_diff_hunk_controls = render_diff_hunk_controls;
15785        cx.notify();
15786    }
15787
15788    pub fn stage_and_next(
15789        &mut self,
15790        _: &::git::StageAndNext,
15791        window: &mut Window,
15792        cx: &mut Context<Self>,
15793    ) {
15794        self.do_stage_or_unstage_and_next(true, window, cx);
15795    }
15796
15797    pub fn unstage_and_next(
15798        &mut self,
15799        _: &::git::UnstageAndNext,
15800        window: &mut Window,
15801        cx: &mut Context<Self>,
15802    ) {
15803        self.do_stage_or_unstage_and_next(false, window, cx);
15804    }
15805
15806    pub fn stage_or_unstage_diff_hunks(
15807        &mut self,
15808        stage: bool,
15809        ranges: Vec<Range<Anchor>>,
15810        cx: &mut Context<Self>,
15811    ) {
15812        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15813        cx.spawn(async move |this, cx| {
15814            task.await?;
15815            this.update(cx, |this, cx| {
15816                let snapshot = this.buffer.read(cx).snapshot(cx);
15817                let chunk_by = this
15818                    .diff_hunks_in_ranges(&ranges, &snapshot)
15819                    .chunk_by(|hunk| hunk.buffer_id);
15820                for (buffer_id, hunks) in &chunk_by {
15821                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15822                }
15823            })
15824        })
15825        .detach_and_log_err(cx);
15826    }
15827
15828    fn save_buffers_for_ranges_if_needed(
15829        &mut self,
15830        ranges: &[Range<Anchor>],
15831        cx: &mut Context<Editor>,
15832    ) -> Task<Result<()>> {
15833        let multibuffer = self.buffer.read(cx);
15834        let snapshot = multibuffer.read(cx);
15835        let buffer_ids: HashSet<_> = ranges
15836            .iter()
15837            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15838            .collect();
15839        drop(snapshot);
15840
15841        let mut buffers = HashSet::default();
15842        for buffer_id in buffer_ids {
15843            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15844                let buffer = buffer_entity.read(cx);
15845                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15846                {
15847                    buffers.insert(buffer_entity);
15848                }
15849            }
15850        }
15851
15852        if let Some(project) = &self.project {
15853            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15854        } else {
15855            Task::ready(Ok(()))
15856        }
15857    }
15858
15859    fn do_stage_or_unstage_and_next(
15860        &mut self,
15861        stage: bool,
15862        window: &mut Window,
15863        cx: &mut Context<Self>,
15864    ) {
15865        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15866
15867        if ranges.iter().any(|range| range.start != range.end) {
15868            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15869            return;
15870        }
15871
15872        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15873        let snapshot = self.snapshot(window, cx);
15874        let position = self.selections.newest::<Point>(cx).head();
15875        let mut row = snapshot
15876            .buffer_snapshot
15877            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15878            .find(|hunk| hunk.row_range.start.0 > position.row)
15879            .map(|hunk| hunk.row_range.start);
15880
15881        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15882        // Outside of the project diff editor, wrap around to the beginning.
15883        if !all_diff_hunks_expanded {
15884            row = row.or_else(|| {
15885                snapshot
15886                    .buffer_snapshot
15887                    .diff_hunks_in_range(Point::zero()..position)
15888                    .find(|hunk| hunk.row_range.end.0 < position.row)
15889                    .map(|hunk| hunk.row_range.start)
15890            });
15891        }
15892
15893        if let Some(row) = row {
15894            let destination = Point::new(row.0, 0);
15895            let autoscroll = Autoscroll::center();
15896
15897            self.unfold_ranges(&[destination..destination], false, false, cx);
15898            self.change_selections(Some(autoscroll), window, cx, |s| {
15899                s.select_ranges([destination..destination]);
15900            });
15901        }
15902    }
15903
15904    fn do_stage_or_unstage(
15905        &self,
15906        stage: bool,
15907        buffer_id: BufferId,
15908        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15909        cx: &mut App,
15910    ) -> Option<()> {
15911        let project = self.project.as_ref()?;
15912        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15913        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15914        let buffer_snapshot = buffer.read(cx).snapshot();
15915        let file_exists = buffer_snapshot
15916            .file()
15917            .is_some_and(|file| file.disk_state().exists());
15918        diff.update(cx, |diff, cx| {
15919            diff.stage_or_unstage_hunks(
15920                stage,
15921                &hunks
15922                    .map(|hunk| buffer_diff::DiffHunk {
15923                        buffer_range: hunk.buffer_range,
15924                        diff_base_byte_range: hunk.diff_base_byte_range,
15925                        secondary_status: hunk.secondary_status,
15926                        range: Point::zero()..Point::zero(), // unused
15927                    })
15928                    .collect::<Vec<_>>(),
15929                &buffer_snapshot,
15930                file_exists,
15931                cx,
15932            )
15933        });
15934        None
15935    }
15936
15937    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15938        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15939        self.buffer
15940            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15941    }
15942
15943    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15944        self.buffer.update(cx, |buffer, cx| {
15945            let ranges = vec![Anchor::min()..Anchor::max()];
15946            if !buffer.all_diff_hunks_expanded()
15947                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15948            {
15949                buffer.collapse_diff_hunks(ranges, cx);
15950                true
15951            } else {
15952                false
15953            }
15954        })
15955    }
15956
15957    fn toggle_diff_hunks_in_ranges(
15958        &mut self,
15959        ranges: Vec<Range<Anchor>>,
15960        cx: &mut Context<Editor>,
15961    ) {
15962        self.buffer.update(cx, |buffer, cx| {
15963            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15964            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15965        })
15966    }
15967
15968    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15969        self.buffer.update(cx, |buffer, cx| {
15970            let snapshot = buffer.snapshot(cx);
15971            let excerpt_id = range.end.excerpt_id;
15972            let point_range = range.to_point(&snapshot);
15973            let expand = !buffer.single_hunk_is_expanded(range, cx);
15974            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15975        })
15976    }
15977
15978    pub(crate) fn apply_all_diff_hunks(
15979        &mut self,
15980        _: &ApplyAllDiffHunks,
15981        window: &mut Window,
15982        cx: &mut Context<Self>,
15983    ) {
15984        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15985
15986        let buffers = self.buffer.read(cx).all_buffers();
15987        for branch_buffer in buffers {
15988            branch_buffer.update(cx, |branch_buffer, cx| {
15989                branch_buffer.merge_into_base(Vec::new(), cx);
15990            });
15991        }
15992
15993        if let Some(project) = self.project.clone() {
15994            self.save(true, project, window, cx).detach_and_log_err(cx);
15995        }
15996    }
15997
15998    pub(crate) fn apply_selected_diff_hunks(
15999        &mut self,
16000        _: &ApplyDiffHunk,
16001        window: &mut Window,
16002        cx: &mut Context<Self>,
16003    ) {
16004        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16005        let snapshot = self.snapshot(window, cx);
16006        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16007        let mut ranges_by_buffer = HashMap::default();
16008        self.transact(window, cx, |editor, _window, cx| {
16009            for hunk in hunks {
16010                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16011                    ranges_by_buffer
16012                        .entry(buffer.clone())
16013                        .or_insert_with(Vec::new)
16014                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16015                }
16016            }
16017
16018            for (buffer, ranges) in ranges_by_buffer {
16019                buffer.update(cx, |buffer, cx| {
16020                    buffer.merge_into_base(ranges, cx);
16021                });
16022            }
16023        });
16024
16025        if let Some(project) = self.project.clone() {
16026            self.save(true, project, window, cx).detach_and_log_err(cx);
16027        }
16028    }
16029
16030    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16031        if hovered != self.gutter_hovered {
16032            self.gutter_hovered = hovered;
16033            cx.notify();
16034        }
16035    }
16036
16037    pub fn insert_blocks(
16038        &mut self,
16039        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16040        autoscroll: Option<Autoscroll>,
16041        cx: &mut Context<Self>,
16042    ) -> Vec<CustomBlockId> {
16043        let blocks = self
16044            .display_map
16045            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16046        if let Some(autoscroll) = autoscroll {
16047            self.request_autoscroll(autoscroll, cx);
16048        }
16049        cx.notify();
16050        blocks
16051    }
16052
16053    pub fn resize_blocks(
16054        &mut self,
16055        heights: HashMap<CustomBlockId, u32>,
16056        autoscroll: Option<Autoscroll>,
16057        cx: &mut Context<Self>,
16058    ) {
16059        self.display_map
16060            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16061        if let Some(autoscroll) = autoscroll {
16062            self.request_autoscroll(autoscroll, cx);
16063        }
16064        cx.notify();
16065    }
16066
16067    pub fn replace_blocks(
16068        &mut self,
16069        renderers: HashMap<CustomBlockId, RenderBlock>,
16070        autoscroll: Option<Autoscroll>,
16071        cx: &mut Context<Self>,
16072    ) {
16073        self.display_map
16074            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16075        if let Some(autoscroll) = autoscroll {
16076            self.request_autoscroll(autoscroll, cx);
16077        }
16078        cx.notify();
16079    }
16080
16081    pub fn remove_blocks(
16082        &mut self,
16083        block_ids: HashSet<CustomBlockId>,
16084        autoscroll: Option<Autoscroll>,
16085        cx: &mut Context<Self>,
16086    ) {
16087        self.display_map.update(cx, |display_map, cx| {
16088            display_map.remove_blocks(block_ids, cx)
16089        });
16090        if let Some(autoscroll) = autoscroll {
16091            self.request_autoscroll(autoscroll, cx);
16092        }
16093        cx.notify();
16094    }
16095
16096    pub fn row_for_block(
16097        &self,
16098        block_id: CustomBlockId,
16099        cx: &mut Context<Self>,
16100    ) -> Option<DisplayRow> {
16101        self.display_map
16102            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16103    }
16104
16105    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16106        self.focused_block = Some(focused_block);
16107    }
16108
16109    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16110        self.focused_block.take()
16111    }
16112
16113    pub fn insert_creases(
16114        &mut self,
16115        creases: impl IntoIterator<Item = Crease<Anchor>>,
16116        cx: &mut Context<Self>,
16117    ) -> Vec<CreaseId> {
16118        self.display_map
16119            .update(cx, |map, cx| map.insert_creases(creases, cx))
16120    }
16121
16122    pub fn remove_creases(
16123        &mut self,
16124        ids: impl IntoIterator<Item = CreaseId>,
16125        cx: &mut Context<Self>,
16126    ) {
16127        self.display_map
16128            .update(cx, |map, cx| map.remove_creases(ids, cx));
16129    }
16130
16131    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16132        self.display_map
16133            .update(cx, |map, cx| map.snapshot(cx))
16134            .longest_row()
16135    }
16136
16137    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16138        self.display_map
16139            .update(cx, |map, cx| map.snapshot(cx))
16140            .max_point()
16141    }
16142
16143    pub fn text(&self, cx: &App) -> String {
16144        self.buffer.read(cx).read(cx).text()
16145    }
16146
16147    pub fn is_empty(&self, cx: &App) -> bool {
16148        self.buffer.read(cx).read(cx).is_empty()
16149    }
16150
16151    pub fn text_option(&self, cx: &App) -> Option<String> {
16152        let text = self.text(cx);
16153        let text = text.trim();
16154
16155        if text.is_empty() {
16156            return None;
16157        }
16158
16159        Some(text.to_string())
16160    }
16161
16162    pub fn set_text(
16163        &mut self,
16164        text: impl Into<Arc<str>>,
16165        window: &mut Window,
16166        cx: &mut Context<Self>,
16167    ) {
16168        self.transact(window, cx, |this, _, cx| {
16169            this.buffer
16170                .read(cx)
16171                .as_singleton()
16172                .expect("you can only call set_text on editors for singleton buffers")
16173                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16174        });
16175    }
16176
16177    pub fn display_text(&self, cx: &mut App) -> String {
16178        self.display_map
16179            .update(cx, |map, cx| map.snapshot(cx))
16180            .text()
16181    }
16182
16183    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16184        let mut wrap_guides = smallvec::smallvec![];
16185
16186        if self.show_wrap_guides == Some(false) {
16187            return wrap_guides;
16188        }
16189
16190        let settings = self.buffer.read(cx).language_settings(cx);
16191        if settings.show_wrap_guides {
16192            match self.soft_wrap_mode(cx) {
16193                SoftWrap::Column(soft_wrap) => {
16194                    wrap_guides.push((soft_wrap as usize, true));
16195                }
16196                SoftWrap::Bounded(soft_wrap) => {
16197                    wrap_guides.push((soft_wrap as usize, true));
16198                }
16199                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16200            }
16201            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16202        }
16203
16204        wrap_guides
16205    }
16206
16207    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16208        let settings = self.buffer.read(cx).language_settings(cx);
16209        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16210        match mode {
16211            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16212                SoftWrap::None
16213            }
16214            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16215            language_settings::SoftWrap::PreferredLineLength => {
16216                SoftWrap::Column(settings.preferred_line_length)
16217            }
16218            language_settings::SoftWrap::Bounded => {
16219                SoftWrap::Bounded(settings.preferred_line_length)
16220            }
16221        }
16222    }
16223
16224    pub fn set_soft_wrap_mode(
16225        &mut self,
16226        mode: language_settings::SoftWrap,
16227
16228        cx: &mut Context<Self>,
16229    ) {
16230        self.soft_wrap_mode_override = Some(mode);
16231        cx.notify();
16232    }
16233
16234    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16235        self.hard_wrap = hard_wrap;
16236        cx.notify();
16237    }
16238
16239    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16240        self.text_style_refinement = Some(style);
16241    }
16242
16243    /// called by the Element so we know what style we were most recently rendered with.
16244    pub(crate) fn set_style(
16245        &mut self,
16246        style: EditorStyle,
16247        window: &mut Window,
16248        cx: &mut Context<Self>,
16249    ) {
16250        let rem_size = window.rem_size();
16251        self.display_map.update(cx, |map, cx| {
16252            map.set_font(
16253                style.text.font(),
16254                style.text.font_size.to_pixels(rem_size),
16255                cx,
16256            )
16257        });
16258        self.style = Some(style);
16259    }
16260
16261    pub fn style(&self) -> Option<&EditorStyle> {
16262        self.style.as_ref()
16263    }
16264
16265    // Called by the element. This method is not designed to be called outside of the editor
16266    // element's layout code because it does not notify when rewrapping is computed synchronously.
16267    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16268        self.display_map
16269            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16270    }
16271
16272    pub fn set_soft_wrap(&mut self) {
16273        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16274    }
16275
16276    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16277        if self.soft_wrap_mode_override.is_some() {
16278            self.soft_wrap_mode_override.take();
16279        } else {
16280            let soft_wrap = match self.soft_wrap_mode(cx) {
16281                SoftWrap::GitDiff => return,
16282                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16283                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16284                    language_settings::SoftWrap::None
16285                }
16286            };
16287            self.soft_wrap_mode_override = Some(soft_wrap);
16288        }
16289        cx.notify();
16290    }
16291
16292    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16293        let Some(workspace) = self.workspace() else {
16294            return;
16295        };
16296        let fs = workspace.read(cx).app_state().fs.clone();
16297        let current_show = TabBarSettings::get_global(cx).show;
16298        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16299            setting.show = Some(!current_show);
16300        });
16301    }
16302
16303    pub fn toggle_indent_guides(
16304        &mut self,
16305        _: &ToggleIndentGuides,
16306        _: &mut Window,
16307        cx: &mut Context<Self>,
16308    ) {
16309        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16310            self.buffer
16311                .read(cx)
16312                .language_settings(cx)
16313                .indent_guides
16314                .enabled
16315        });
16316        self.show_indent_guides = Some(!currently_enabled);
16317        cx.notify();
16318    }
16319
16320    fn should_show_indent_guides(&self) -> Option<bool> {
16321        self.show_indent_guides
16322    }
16323
16324    pub fn toggle_line_numbers(
16325        &mut self,
16326        _: &ToggleLineNumbers,
16327        _: &mut Window,
16328        cx: &mut Context<Self>,
16329    ) {
16330        let mut editor_settings = EditorSettings::get_global(cx).clone();
16331        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16332        EditorSettings::override_global(editor_settings, cx);
16333    }
16334
16335    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16336        if let Some(show_line_numbers) = self.show_line_numbers {
16337            return show_line_numbers;
16338        }
16339        EditorSettings::get_global(cx).gutter.line_numbers
16340    }
16341
16342    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16343        self.use_relative_line_numbers
16344            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16345    }
16346
16347    pub fn toggle_relative_line_numbers(
16348        &mut self,
16349        _: &ToggleRelativeLineNumbers,
16350        _: &mut Window,
16351        cx: &mut Context<Self>,
16352    ) {
16353        let is_relative = self.should_use_relative_line_numbers(cx);
16354        self.set_relative_line_number(Some(!is_relative), cx)
16355    }
16356
16357    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16358        self.use_relative_line_numbers = is_relative;
16359        cx.notify();
16360    }
16361
16362    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16363        self.show_gutter = show_gutter;
16364        cx.notify();
16365    }
16366
16367    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16368        self.show_scrollbars = show_scrollbars;
16369        cx.notify();
16370    }
16371
16372    pub fn disable_scrolling(&mut self, cx: &mut Context<Self>) {
16373        self.disable_scrolling = true;
16374        cx.notify();
16375    }
16376
16377    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16378        self.show_line_numbers = Some(show_line_numbers);
16379        cx.notify();
16380    }
16381
16382    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16383        self.disable_expand_excerpt_buttons = true;
16384        cx.notify();
16385    }
16386
16387    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16388        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16389        cx.notify();
16390    }
16391
16392    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16393        self.show_code_actions = Some(show_code_actions);
16394        cx.notify();
16395    }
16396
16397    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16398        self.show_runnables = Some(show_runnables);
16399        cx.notify();
16400    }
16401
16402    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16403        self.show_breakpoints = Some(show_breakpoints);
16404        cx.notify();
16405    }
16406
16407    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16408        if self.display_map.read(cx).masked != masked {
16409            self.display_map.update(cx, |map, _| map.masked = masked);
16410        }
16411        cx.notify()
16412    }
16413
16414    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16415        self.show_wrap_guides = Some(show_wrap_guides);
16416        cx.notify();
16417    }
16418
16419    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16420        self.show_indent_guides = Some(show_indent_guides);
16421        cx.notify();
16422    }
16423
16424    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16425        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16426            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16427                if let Some(dir) = file.abs_path(cx).parent() {
16428                    return Some(dir.to_owned());
16429                }
16430            }
16431
16432            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16433                return Some(project_path.path.to_path_buf());
16434            }
16435        }
16436
16437        None
16438    }
16439
16440    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16441        self.active_excerpt(cx)?
16442            .1
16443            .read(cx)
16444            .file()
16445            .and_then(|f| f.as_local())
16446    }
16447
16448    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16449        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16450            let buffer = buffer.read(cx);
16451            if let Some(project_path) = buffer.project_path(cx) {
16452                let project = self.project.as_ref()?.read(cx);
16453                project.absolute_path(&project_path, cx)
16454            } else {
16455                buffer
16456                    .file()
16457                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16458            }
16459        })
16460    }
16461
16462    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16463        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16464            let project_path = buffer.read(cx).project_path(cx)?;
16465            let project = self.project.as_ref()?.read(cx);
16466            let entry = project.entry_for_path(&project_path, cx)?;
16467            let path = entry.path.to_path_buf();
16468            Some(path)
16469        })
16470    }
16471
16472    pub fn reveal_in_finder(
16473        &mut self,
16474        _: &RevealInFileManager,
16475        _window: &mut Window,
16476        cx: &mut Context<Self>,
16477    ) {
16478        if let Some(target) = self.target_file(cx) {
16479            cx.reveal_path(&target.abs_path(cx));
16480        }
16481    }
16482
16483    pub fn copy_path(
16484        &mut self,
16485        _: &zed_actions::workspace::CopyPath,
16486        _window: &mut Window,
16487        cx: &mut Context<Self>,
16488    ) {
16489        if let Some(path) = self.target_file_abs_path(cx) {
16490            if let Some(path) = path.to_str() {
16491                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16492            }
16493        }
16494    }
16495
16496    pub fn copy_relative_path(
16497        &mut self,
16498        _: &zed_actions::workspace::CopyRelativePath,
16499        _window: &mut Window,
16500        cx: &mut Context<Self>,
16501    ) {
16502        if let Some(path) = self.target_file_path(cx) {
16503            if let Some(path) = path.to_str() {
16504                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16505            }
16506        }
16507    }
16508
16509    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16510        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16511            buffer.read(cx).project_path(cx)
16512        } else {
16513            None
16514        }
16515    }
16516
16517    // Returns true if the editor handled a go-to-line request
16518    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16519        maybe!({
16520            let breakpoint_store = self.breakpoint_store.as_ref()?;
16521
16522            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16523            else {
16524                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16525                return None;
16526            };
16527
16528            let position = active_stack_frame.position;
16529            let buffer_id = position.buffer_id?;
16530            let snapshot = self
16531                .project
16532                .as_ref()?
16533                .read(cx)
16534                .buffer_for_id(buffer_id, cx)?
16535                .read(cx)
16536                .snapshot();
16537
16538            let mut handled = false;
16539            for (id, ExcerptRange { context, .. }) in
16540                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16541            {
16542                if context.start.cmp(&position, &snapshot).is_ge()
16543                    || context.end.cmp(&position, &snapshot).is_lt()
16544                {
16545                    continue;
16546                }
16547                let snapshot = self.buffer.read(cx).snapshot(cx);
16548                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16549
16550                handled = true;
16551                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16552                self.go_to_line::<DebugCurrentRowHighlight>(
16553                    multibuffer_anchor,
16554                    Some(cx.theme().colors().editor_debugger_active_line_background),
16555                    window,
16556                    cx,
16557                );
16558
16559                cx.notify();
16560            }
16561
16562            handled.then_some(())
16563        })
16564        .is_some()
16565    }
16566
16567    pub fn copy_file_name_without_extension(
16568        &mut self,
16569        _: &CopyFileNameWithoutExtension,
16570        _: &mut Window,
16571        cx: &mut Context<Self>,
16572    ) {
16573        if let Some(file) = self.target_file(cx) {
16574            if let Some(file_stem) = file.path().file_stem() {
16575                if let Some(name) = file_stem.to_str() {
16576                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16577                }
16578            }
16579        }
16580    }
16581
16582    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16583        if let Some(file) = self.target_file(cx) {
16584            if let Some(file_name) = file.path().file_name() {
16585                if let Some(name) = file_name.to_str() {
16586                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16587                }
16588            }
16589        }
16590    }
16591
16592    pub fn toggle_git_blame(
16593        &mut self,
16594        _: &::git::Blame,
16595        window: &mut Window,
16596        cx: &mut Context<Self>,
16597    ) {
16598        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16599
16600        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16601            self.start_git_blame(true, window, cx);
16602        }
16603
16604        cx.notify();
16605    }
16606
16607    pub fn toggle_git_blame_inline(
16608        &mut self,
16609        _: &ToggleGitBlameInline,
16610        window: &mut Window,
16611        cx: &mut Context<Self>,
16612    ) {
16613        self.toggle_git_blame_inline_internal(true, window, cx);
16614        cx.notify();
16615    }
16616
16617    pub fn open_git_blame_commit(
16618        &mut self,
16619        _: &OpenGitBlameCommit,
16620        window: &mut Window,
16621        cx: &mut Context<Self>,
16622    ) {
16623        self.open_git_blame_commit_internal(window, cx);
16624    }
16625
16626    fn open_git_blame_commit_internal(
16627        &mut self,
16628        window: &mut Window,
16629        cx: &mut Context<Self>,
16630    ) -> Option<()> {
16631        let blame = self.blame.as_ref()?;
16632        let snapshot = self.snapshot(window, cx);
16633        let cursor = self.selections.newest::<Point>(cx).head();
16634        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16635        let blame_entry = blame
16636            .update(cx, |blame, cx| {
16637                blame
16638                    .blame_for_rows(
16639                        &[RowInfo {
16640                            buffer_id: Some(buffer.remote_id()),
16641                            buffer_row: Some(point.row),
16642                            ..Default::default()
16643                        }],
16644                        cx,
16645                    )
16646                    .next()
16647            })
16648            .flatten()?;
16649        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16650        let repo = blame.read(cx).repository(cx)?;
16651        let workspace = self.workspace()?.downgrade();
16652        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16653        None
16654    }
16655
16656    pub fn git_blame_inline_enabled(&self) -> bool {
16657        self.git_blame_inline_enabled
16658    }
16659
16660    pub fn toggle_selection_menu(
16661        &mut self,
16662        _: &ToggleSelectionMenu,
16663        _: &mut Window,
16664        cx: &mut Context<Self>,
16665    ) {
16666        self.show_selection_menu = self
16667            .show_selection_menu
16668            .map(|show_selections_menu| !show_selections_menu)
16669            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16670
16671        cx.notify();
16672    }
16673
16674    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16675        self.show_selection_menu
16676            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16677    }
16678
16679    fn start_git_blame(
16680        &mut self,
16681        user_triggered: bool,
16682        window: &mut Window,
16683        cx: &mut Context<Self>,
16684    ) {
16685        if let Some(project) = self.project.as_ref() {
16686            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16687                return;
16688            };
16689
16690            if buffer.read(cx).file().is_none() {
16691                return;
16692            }
16693
16694            let focused = self.focus_handle(cx).contains_focused(window, cx);
16695
16696            let project = project.clone();
16697            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16698            self.blame_subscription =
16699                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16700            self.blame = Some(blame);
16701        }
16702    }
16703
16704    fn toggle_git_blame_inline_internal(
16705        &mut self,
16706        user_triggered: bool,
16707        window: &mut Window,
16708        cx: &mut Context<Self>,
16709    ) {
16710        if self.git_blame_inline_enabled {
16711            self.git_blame_inline_enabled = false;
16712            self.show_git_blame_inline = false;
16713            self.show_git_blame_inline_delay_task.take();
16714        } else {
16715            self.git_blame_inline_enabled = true;
16716            self.start_git_blame_inline(user_triggered, window, cx);
16717        }
16718
16719        cx.notify();
16720    }
16721
16722    fn start_git_blame_inline(
16723        &mut self,
16724        user_triggered: bool,
16725        window: &mut Window,
16726        cx: &mut Context<Self>,
16727    ) {
16728        self.start_git_blame(user_triggered, window, cx);
16729
16730        if ProjectSettings::get_global(cx)
16731            .git
16732            .inline_blame_delay()
16733            .is_some()
16734        {
16735            self.start_inline_blame_timer(window, cx);
16736        } else {
16737            self.show_git_blame_inline = true
16738        }
16739    }
16740
16741    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16742        self.blame.as_ref()
16743    }
16744
16745    pub fn show_git_blame_gutter(&self) -> bool {
16746        self.show_git_blame_gutter
16747    }
16748
16749    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16750        self.show_git_blame_gutter && self.has_blame_entries(cx)
16751    }
16752
16753    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16754        self.show_git_blame_inline
16755            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16756            && !self.newest_selection_head_on_empty_line(cx)
16757            && self.has_blame_entries(cx)
16758    }
16759
16760    fn has_blame_entries(&self, cx: &App) -> bool {
16761        self.blame()
16762            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16763    }
16764
16765    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16766        let cursor_anchor = self.selections.newest_anchor().head();
16767
16768        let snapshot = self.buffer.read(cx).snapshot(cx);
16769        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16770
16771        snapshot.line_len(buffer_row) == 0
16772    }
16773
16774    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16775        let buffer_and_selection = maybe!({
16776            let selection = self.selections.newest::<Point>(cx);
16777            let selection_range = selection.range();
16778
16779            let multi_buffer = self.buffer().read(cx);
16780            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16781            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16782
16783            let (buffer, range, _) = if selection.reversed {
16784                buffer_ranges.first()
16785            } else {
16786                buffer_ranges.last()
16787            }?;
16788
16789            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16790                ..text::ToPoint::to_point(&range.end, &buffer).row;
16791            Some((
16792                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16793                selection,
16794            ))
16795        });
16796
16797        let Some((buffer, selection)) = buffer_and_selection else {
16798            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16799        };
16800
16801        let Some(project) = self.project.as_ref() else {
16802            return Task::ready(Err(anyhow!("editor does not have project")));
16803        };
16804
16805        project.update(cx, |project, cx| {
16806            project.get_permalink_to_line(&buffer, selection, cx)
16807        })
16808    }
16809
16810    pub fn copy_permalink_to_line(
16811        &mut self,
16812        _: &CopyPermalinkToLine,
16813        window: &mut Window,
16814        cx: &mut Context<Self>,
16815    ) {
16816        let permalink_task = self.get_permalink_to_line(cx);
16817        let workspace = self.workspace();
16818
16819        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16820            Ok(permalink) => {
16821                cx.update(|_, cx| {
16822                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16823                })
16824                .ok();
16825            }
16826            Err(err) => {
16827                let message = format!("Failed to copy permalink: {err}");
16828
16829                Err::<(), anyhow::Error>(err).log_err();
16830
16831                if let Some(workspace) = workspace {
16832                    workspace
16833                        .update_in(cx, |workspace, _, cx| {
16834                            struct CopyPermalinkToLine;
16835
16836                            workspace.show_toast(
16837                                Toast::new(
16838                                    NotificationId::unique::<CopyPermalinkToLine>(),
16839                                    message,
16840                                ),
16841                                cx,
16842                            )
16843                        })
16844                        .ok();
16845                }
16846            }
16847        })
16848        .detach();
16849    }
16850
16851    pub fn copy_file_location(
16852        &mut self,
16853        _: &CopyFileLocation,
16854        _: &mut Window,
16855        cx: &mut Context<Self>,
16856    ) {
16857        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16858        if let Some(file) = self.target_file(cx) {
16859            if let Some(path) = file.path().to_str() {
16860                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16861            }
16862        }
16863    }
16864
16865    pub fn open_permalink_to_line(
16866        &mut self,
16867        _: &OpenPermalinkToLine,
16868        window: &mut Window,
16869        cx: &mut Context<Self>,
16870    ) {
16871        let permalink_task = self.get_permalink_to_line(cx);
16872        let workspace = self.workspace();
16873
16874        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16875            Ok(permalink) => {
16876                cx.update(|_, cx| {
16877                    cx.open_url(permalink.as_ref());
16878                })
16879                .ok();
16880            }
16881            Err(err) => {
16882                let message = format!("Failed to open permalink: {err}");
16883
16884                Err::<(), anyhow::Error>(err).log_err();
16885
16886                if let Some(workspace) = workspace {
16887                    workspace
16888                        .update(cx, |workspace, cx| {
16889                            struct OpenPermalinkToLine;
16890
16891                            workspace.show_toast(
16892                                Toast::new(
16893                                    NotificationId::unique::<OpenPermalinkToLine>(),
16894                                    message,
16895                                ),
16896                                cx,
16897                            )
16898                        })
16899                        .ok();
16900                }
16901            }
16902        })
16903        .detach();
16904    }
16905
16906    pub fn insert_uuid_v4(
16907        &mut self,
16908        _: &InsertUuidV4,
16909        window: &mut Window,
16910        cx: &mut Context<Self>,
16911    ) {
16912        self.insert_uuid(UuidVersion::V4, window, cx);
16913    }
16914
16915    pub fn insert_uuid_v7(
16916        &mut self,
16917        _: &InsertUuidV7,
16918        window: &mut Window,
16919        cx: &mut Context<Self>,
16920    ) {
16921        self.insert_uuid(UuidVersion::V7, window, cx);
16922    }
16923
16924    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16925        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16926        self.transact(window, cx, |this, window, cx| {
16927            let edits = this
16928                .selections
16929                .all::<Point>(cx)
16930                .into_iter()
16931                .map(|selection| {
16932                    let uuid = match version {
16933                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16934                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16935                    };
16936
16937                    (selection.range(), uuid.to_string())
16938                });
16939            this.edit(edits, cx);
16940            this.refresh_inline_completion(true, false, window, cx);
16941        });
16942    }
16943
16944    pub fn open_selections_in_multibuffer(
16945        &mut self,
16946        _: &OpenSelectionsInMultibuffer,
16947        window: &mut Window,
16948        cx: &mut Context<Self>,
16949    ) {
16950        let multibuffer = self.buffer.read(cx);
16951
16952        let Some(buffer) = multibuffer.as_singleton() else {
16953            return;
16954        };
16955
16956        let Some(workspace) = self.workspace() else {
16957            return;
16958        };
16959
16960        let locations = self
16961            .selections
16962            .disjoint_anchors()
16963            .iter()
16964            .map(|range| Location {
16965                buffer: buffer.clone(),
16966                range: range.start.text_anchor..range.end.text_anchor,
16967            })
16968            .collect::<Vec<_>>();
16969
16970        let title = multibuffer.title(cx).to_string();
16971
16972        cx.spawn_in(window, async move |_, cx| {
16973            workspace.update_in(cx, |workspace, window, cx| {
16974                Self::open_locations_in_multibuffer(
16975                    workspace,
16976                    locations,
16977                    format!("Selections for '{title}'"),
16978                    false,
16979                    MultibufferSelectionMode::All,
16980                    window,
16981                    cx,
16982                );
16983            })
16984        })
16985        .detach();
16986    }
16987
16988    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16989    /// last highlight added will be used.
16990    ///
16991    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16992    pub fn highlight_rows<T: 'static>(
16993        &mut self,
16994        range: Range<Anchor>,
16995        color: Hsla,
16996        options: RowHighlightOptions,
16997        cx: &mut Context<Self>,
16998    ) {
16999        let snapshot = self.buffer().read(cx).snapshot(cx);
17000        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17001        let ix = row_highlights.binary_search_by(|highlight| {
17002            Ordering::Equal
17003                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17004                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17005        });
17006
17007        if let Err(mut ix) = ix {
17008            let index = post_inc(&mut self.highlight_order);
17009
17010            // If this range intersects with the preceding highlight, then merge it with
17011            // the preceding highlight. Otherwise insert a new highlight.
17012            let mut merged = false;
17013            if ix > 0 {
17014                let prev_highlight = &mut row_highlights[ix - 1];
17015                if prev_highlight
17016                    .range
17017                    .end
17018                    .cmp(&range.start, &snapshot)
17019                    .is_ge()
17020                {
17021                    ix -= 1;
17022                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17023                        prev_highlight.range.end = range.end;
17024                    }
17025                    merged = true;
17026                    prev_highlight.index = index;
17027                    prev_highlight.color = color;
17028                    prev_highlight.options = options;
17029                }
17030            }
17031
17032            if !merged {
17033                row_highlights.insert(
17034                    ix,
17035                    RowHighlight {
17036                        range: range.clone(),
17037                        index,
17038                        color,
17039                        options,
17040                        type_id: TypeId::of::<T>(),
17041                    },
17042                );
17043            }
17044
17045            // If any of the following highlights intersect with this one, merge them.
17046            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17047                let highlight = &row_highlights[ix];
17048                if next_highlight
17049                    .range
17050                    .start
17051                    .cmp(&highlight.range.end, &snapshot)
17052                    .is_le()
17053                {
17054                    if next_highlight
17055                        .range
17056                        .end
17057                        .cmp(&highlight.range.end, &snapshot)
17058                        .is_gt()
17059                    {
17060                        row_highlights[ix].range.end = next_highlight.range.end;
17061                    }
17062                    row_highlights.remove(ix + 1);
17063                } else {
17064                    break;
17065                }
17066            }
17067        }
17068    }
17069
17070    /// Remove any highlighted row ranges of the given type that intersect the
17071    /// given ranges.
17072    pub fn remove_highlighted_rows<T: 'static>(
17073        &mut self,
17074        ranges_to_remove: Vec<Range<Anchor>>,
17075        cx: &mut Context<Self>,
17076    ) {
17077        let snapshot = self.buffer().read(cx).snapshot(cx);
17078        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17079        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17080        row_highlights.retain(|highlight| {
17081            while let Some(range_to_remove) = ranges_to_remove.peek() {
17082                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17083                    Ordering::Less | Ordering::Equal => {
17084                        ranges_to_remove.next();
17085                    }
17086                    Ordering::Greater => {
17087                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17088                            Ordering::Less | Ordering::Equal => {
17089                                return false;
17090                            }
17091                            Ordering::Greater => break,
17092                        }
17093                    }
17094                }
17095            }
17096
17097            true
17098        })
17099    }
17100
17101    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17102    pub fn clear_row_highlights<T: 'static>(&mut self) {
17103        self.highlighted_rows.remove(&TypeId::of::<T>());
17104    }
17105
17106    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17107    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17108        self.highlighted_rows
17109            .get(&TypeId::of::<T>())
17110            .map_or(&[] as &[_], |vec| vec.as_slice())
17111            .iter()
17112            .map(|highlight| (highlight.range.clone(), highlight.color))
17113    }
17114
17115    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17116    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17117    /// Allows to ignore certain kinds of highlights.
17118    pub fn highlighted_display_rows(
17119        &self,
17120        window: &mut Window,
17121        cx: &mut App,
17122    ) -> BTreeMap<DisplayRow, LineHighlight> {
17123        let snapshot = self.snapshot(window, cx);
17124        let mut used_highlight_orders = HashMap::default();
17125        self.highlighted_rows
17126            .iter()
17127            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17128            .fold(
17129                BTreeMap::<DisplayRow, LineHighlight>::new(),
17130                |mut unique_rows, highlight| {
17131                    let start = highlight.range.start.to_display_point(&snapshot);
17132                    let end = highlight.range.end.to_display_point(&snapshot);
17133                    let start_row = start.row().0;
17134                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17135                        && end.column() == 0
17136                    {
17137                        end.row().0.saturating_sub(1)
17138                    } else {
17139                        end.row().0
17140                    };
17141                    for row in start_row..=end_row {
17142                        let used_index =
17143                            used_highlight_orders.entry(row).or_insert(highlight.index);
17144                        if highlight.index >= *used_index {
17145                            *used_index = highlight.index;
17146                            unique_rows.insert(
17147                                DisplayRow(row),
17148                                LineHighlight {
17149                                    include_gutter: highlight.options.include_gutter,
17150                                    border: None,
17151                                    background: highlight.color.into(),
17152                                    type_id: Some(highlight.type_id),
17153                                },
17154                            );
17155                        }
17156                    }
17157                    unique_rows
17158                },
17159            )
17160    }
17161
17162    pub fn highlighted_display_row_for_autoscroll(
17163        &self,
17164        snapshot: &DisplaySnapshot,
17165    ) -> Option<DisplayRow> {
17166        self.highlighted_rows
17167            .values()
17168            .flat_map(|highlighted_rows| highlighted_rows.iter())
17169            .filter_map(|highlight| {
17170                if highlight.options.autoscroll {
17171                    Some(highlight.range.start.to_display_point(snapshot).row())
17172                } else {
17173                    None
17174                }
17175            })
17176            .min()
17177    }
17178
17179    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17180        self.highlight_background::<SearchWithinRange>(
17181            ranges,
17182            |colors| colors.editor_document_highlight_read_background,
17183            cx,
17184        )
17185    }
17186
17187    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17188        self.breadcrumb_header = Some(new_header);
17189    }
17190
17191    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17192        self.clear_background_highlights::<SearchWithinRange>(cx);
17193    }
17194
17195    pub fn highlight_background<T: 'static>(
17196        &mut self,
17197        ranges: &[Range<Anchor>],
17198        color_fetcher: fn(&ThemeColors) -> Hsla,
17199        cx: &mut Context<Self>,
17200    ) {
17201        self.background_highlights
17202            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17203        self.scrollbar_marker_state.dirty = true;
17204        cx.notify();
17205    }
17206
17207    pub fn clear_background_highlights<T: 'static>(
17208        &mut self,
17209        cx: &mut Context<Self>,
17210    ) -> Option<BackgroundHighlight> {
17211        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17212        if !text_highlights.1.is_empty() {
17213            self.scrollbar_marker_state.dirty = true;
17214            cx.notify();
17215        }
17216        Some(text_highlights)
17217    }
17218
17219    pub fn highlight_gutter<T: 'static>(
17220        &mut self,
17221        ranges: &[Range<Anchor>],
17222        color_fetcher: fn(&App) -> Hsla,
17223        cx: &mut Context<Self>,
17224    ) {
17225        self.gutter_highlights
17226            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17227        cx.notify();
17228    }
17229
17230    pub fn clear_gutter_highlights<T: 'static>(
17231        &mut self,
17232        cx: &mut Context<Self>,
17233    ) -> Option<GutterHighlight> {
17234        cx.notify();
17235        self.gutter_highlights.remove(&TypeId::of::<T>())
17236    }
17237
17238    #[cfg(feature = "test-support")]
17239    pub fn all_text_background_highlights(
17240        &self,
17241        window: &mut Window,
17242        cx: &mut Context<Self>,
17243    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17244        let snapshot = self.snapshot(window, cx);
17245        let buffer = &snapshot.buffer_snapshot;
17246        let start = buffer.anchor_before(0);
17247        let end = buffer.anchor_after(buffer.len());
17248        let theme = cx.theme().colors();
17249        self.background_highlights_in_range(start..end, &snapshot, theme)
17250    }
17251
17252    #[cfg(feature = "test-support")]
17253    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17254        let snapshot = self.buffer().read(cx).snapshot(cx);
17255
17256        let highlights = self
17257            .background_highlights
17258            .get(&TypeId::of::<items::BufferSearchHighlights>());
17259
17260        if let Some((_color, ranges)) = highlights {
17261            ranges
17262                .iter()
17263                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17264                .collect_vec()
17265        } else {
17266            vec![]
17267        }
17268    }
17269
17270    fn document_highlights_for_position<'a>(
17271        &'a self,
17272        position: Anchor,
17273        buffer: &'a MultiBufferSnapshot,
17274    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17275        let read_highlights = self
17276            .background_highlights
17277            .get(&TypeId::of::<DocumentHighlightRead>())
17278            .map(|h| &h.1);
17279        let write_highlights = self
17280            .background_highlights
17281            .get(&TypeId::of::<DocumentHighlightWrite>())
17282            .map(|h| &h.1);
17283        let left_position = position.bias_left(buffer);
17284        let right_position = position.bias_right(buffer);
17285        read_highlights
17286            .into_iter()
17287            .chain(write_highlights)
17288            .flat_map(move |ranges| {
17289                let start_ix = match ranges.binary_search_by(|probe| {
17290                    let cmp = probe.end.cmp(&left_position, buffer);
17291                    if cmp.is_ge() {
17292                        Ordering::Greater
17293                    } else {
17294                        Ordering::Less
17295                    }
17296                }) {
17297                    Ok(i) | Err(i) => i,
17298                };
17299
17300                ranges[start_ix..]
17301                    .iter()
17302                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17303            })
17304    }
17305
17306    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17307        self.background_highlights
17308            .get(&TypeId::of::<T>())
17309            .map_or(false, |(_, highlights)| !highlights.is_empty())
17310    }
17311
17312    pub fn background_highlights_in_range(
17313        &self,
17314        search_range: Range<Anchor>,
17315        display_snapshot: &DisplaySnapshot,
17316        theme: &ThemeColors,
17317    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17318        let mut results = Vec::new();
17319        for (color_fetcher, ranges) in self.background_highlights.values() {
17320            let color = color_fetcher(theme);
17321            let start_ix = match ranges.binary_search_by(|probe| {
17322                let cmp = probe
17323                    .end
17324                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17325                if cmp.is_gt() {
17326                    Ordering::Greater
17327                } else {
17328                    Ordering::Less
17329                }
17330            }) {
17331                Ok(i) | Err(i) => i,
17332            };
17333            for range in &ranges[start_ix..] {
17334                if range
17335                    .start
17336                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17337                    .is_ge()
17338                {
17339                    break;
17340                }
17341
17342                let start = range.start.to_display_point(display_snapshot);
17343                let end = range.end.to_display_point(display_snapshot);
17344                results.push((start..end, color))
17345            }
17346        }
17347        results
17348    }
17349
17350    pub fn background_highlight_row_ranges<T: 'static>(
17351        &self,
17352        search_range: Range<Anchor>,
17353        display_snapshot: &DisplaySnapshot,
17354        count: usize,
17355    ) -> Vec<RangeInclusive<DisplayPoint>> {
17356        let mut results = Vec::new();
17357        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17358            return vec![];
17359        };
17360
17361        let start_ix = match ranges.binary_search_by(|probe| {
17362            let cmp = probe
17363                .end
17364                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17365            if cmp.is_gt() {
17366                Ordering::Greater
17367            } else {
17368                Ordering::Less
17369            }
17370        }) {
17371            Ok(i) | Err(i) => i,
17372        };
17373        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17374            if let (Some(start_display), Some(end_display)) = (start, end) {
17375                results.push(
17376                    start_display.to_display_point(display_snapshot)
17377                        ..=end_display.to_display_point(display_snapshot),
17378                );
17379            }
17380        };
17381        let mut start_row: Option<Point> = None;
17382        let mut end_row: Option<Point> = None;
17383        if ranges.len() > count {
17384            return Vec::new();
17385        }
17386        for range in &ranges[start_ix..] {
17387            if range
17388                .start
17389                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17390                .is_ge()
17391            {
17392                break;
17393            }
17394            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17395            if let Some(current_row) = &end_row {
17396                if end.row == current_row.row {
17397                    continue;
17398                }
17399            }
17400            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17401            if start_row.is_none() {
17402                assert_eq!(end_row, None);
17403                start_row = Some(start);
17404                end_row = Some(end);
17405                continue;
17406            }
17407            if let Some(current_end) = end_row.as_mut() {
17408                if start.row > current_end.row + 1 {
17409                    push_region(start_row, end_row);
17410                    start_row = Some(start);
17411                    end_row = Some(end);
17412                } else {
17413                    // Merge two hunks.
17414                    *current_end = end;
17415                }
17416            } else {
17417                unreachable!();
17418            }
17419        }
17420        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17421        push_region(start_row, end_row);
17422        results
17423    }
17424
17425    pub fn gutter_highlights_in_range(
17426        &self,
17427        search_range: Range<Anchor>,
17428        display_snapshot: &DisplaySnapshot,
17429        cx: &App,
17430    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17431        let mut results = Vec::new();
17432        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17433            let color = color_fetcher(cx);
17434            let start_ix = match ranges.binary_search_by(|probe| {
17435                let cmp = probe
17436                    .end
17437                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17438                if cmp.is_gt() {
17439                    Ordering::Greater
17440                } else {
17441                    Ordering::Less
17442                }
17443            }) {
17444                Ok(i) | Err(i) => i,
17445            };
17446            for range in &ranges[start_ix..] {
17447                if range
17448                    .start
17449                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17450                    .is_ge()
17451                {
17452                    break;
17453                }
17454
17455                let start = range.start.to_display_point(display_snapshot);
17456                let end = range.end.to_display_point(display_snapshot);
17457                results.push((start..end, color))
17458            }
17459        }
17460        results
17461    }
17462
17463    /// Get the text ranges corresponding to the redaction query
17464    pub fn redacted_ranges(
17465        &self,
17466        search_range: Range<Anchor>,
17467        display_snapshot: &DisplaySnapshot,
17468        cx: &App,
17469    ) -> Vec<Range<DisplayPoint>> {
17470        display_snapshot
17471            .buffer_snapshot
17472            .redacted_ranges(search_range, |file| {
17473                if let Some(file) = file {
17474                    file.is_private()
17475                        && EditorSettings::get(
17476                            Some(SettingsLocation {
17477                                worktree_id: file.worktree_id(cx),
17478                                path: file.path().as_ref(),
17479                            }),
17480                            cx,
17481                        )
17482                        .redact_private_values
17483                } else {
17484                    false
17485                }
17486            })
17487            .map(|range| {
17488                range.start.to_display_point(display_snapshot)
17489                    ..range.end.to_display_point(display_snapshot)
17490            })
17491            .collect()
17492    }
17493
17494    pub fn highlight_text<T: 'static>(
17495        &mut self,
17496        ranges: Vec<Range<Anchor>>,
17497        style: HighlightStyle,
17498        cx: &mut Context<Self>,
17499    ) {
17500        self.display_map.update(cx, |map, _| {
17501            map.highlight_text(TypeId::of::<T>(), ranges, style)
17502        });
17503        cx.notify();
17504    }
17505
17506    pub(crate) fn highlight_inlays<T: 'static>(
17507        &mut self,
17508        highlights: Vec<InlayHighlight>,
17509        style: HighlightStyle,
17510        cx: &mut Context<Self>,
17511    ) {
17512        self.display_map.update(cx, |map, _| {
17513            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17514        });
17515        cx.notify();
17516    }
17517
17518    pub fn text_highlights<'a, T: 'static>(
17519        &'a self,
17520        cx: &'a App,
17521    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17522        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17523    }
17524
17525    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17526        let cleared = self
17527            .display_map
17528            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17529        if cleared {
17530            cx.notify();
17531        }
17532    }
17533
17534    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17535        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17536            && self.focus_handle.is_focused(window)
17537    }
17538
17539    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17540        self.show_cursor_when_unfocused = is_enabled;
17541        cx.notify();
17542    }
17543
17544    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17545        cx.notify();
17546    }
17547
17548    fn on_debug_session_event(
17549        &mut self,
17550        _session: Entity<Session>,
17551        event: &SessionEvent,
17552        cx: &mut Context<Self>,
17553    ) {
17554        match event {
17555            SessionEvent::InvalidateInlineValue => {
17556                self.refresh_inline_values(cx);
17557            }
17558            _ => {}
17559        }
17560    }
17561
17562    fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17563        let Some(project) = self.project.clone() else {
17564            return;
17565        };
17566        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17567            return;
17568        };
17569        if !self.inline_value_cache.enabled {
17570            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17571            self.splice_inlays(&inlays, Vec::new(), cx);
17572            return;
17573        }
17574
17575        let current_execution_position = self
17576            .highlighted_rows
17577            .get(&TypeId::of::<DebugCurrentRowHighlight>())
17578            .and_then(|lines| lines.last().map(|line| line.range.start));
17579
17580        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17581            let snapshot = editor
17582                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17583                .ok()?;
17584
17585            let inline_values = editor
17586                .update(cx, |_, cx| {
17587                    let Some(current_execution_position) = current_execution_position else {
17588                        return Some(Task::ready(Ok(Vec::new())));
17589                    };
17590
17591                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17592                    // anchor is in the same buffer
17593                    let range =
17594                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17595                    project.inline_values(buffer, range, cx)
17596                })
17597                .ok()
17598                .flatten()?
17599                .await
17600                .context("refreshing debugger inlays")
17601                .log_err()?;
17602
17603            let (excerpt_id, buffer_id) = snapshot
17604                .excerpts()
17605                .next()
17606                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17607            editor
17608                .update(cx, |editor, cx| {
17609                    let new_inlays = inline_values
17610                        .into_iter()
17611                        .map(|debugger_value| {
17612                            Inlay::debugger_hint(
17613                                post_inc(&mut editor.next_inlay_id),
17614                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17615                                debugger_value.text(),
17616                            )
17617                        })
17618                        .collect::<Vec<_>>();
17619                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17620                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17621
17622                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17623                })
17624                .ok()?;
17625            Some(())
17626        });
17627    }
17628
17629    fn on_buffer_event(
17630        &mut self,
17631        multibuffer: &Entity<MultiBuffer>,
17632        event: &multi_buffer::Event,
17633        window: &mut Window,
17634        cx: &mut Context<Self>,
17635    ) {
17636        match event {
17637            multi_buffer::Event::Edited {
17638                singleton_buffer_edited,
17639                edited_buffer: buffer_edited,
17640            } => {
17641                self.scrollbar_marker_state.dirty = true;
17642                self.active_indent_guides_state.dirty = true;
17643                self.refresh_active_diagnostics(cx);
17644                self.refresh_code_actions(window, cx);
17645                if self.has_active_inline_completion() {
17646                    self.update_visible_inline_completion(window, cx);
17647                }
17648                if let Some(buffer) = buffer_edited {
17649                    let buffer_id = buffer.read(cx).remote_id();
17650                    if !self.registered_buffers.contains_key(&buffer_id) {
17651                        if let Some(project) = self.project.as_ref() {
17652                            project.update(cx, |project, cx| {
17653                                self.registered_buffers.insert(
17654                                    buffer_id,
17655                                    project.register_buffer_with_language_servers(&buffer, cx),
17656                                );
17657                            })
17658                        }
17659                    }
17660                }
17661                cx.emit(EditorEvent::BufferEdited);
17662                cx.emit(SearchEvent::MatchesInvalidated);
17663                if *singleton_buffer_edited {
17664                    if let Some(project) = &self.project {
17665                        #[allow(clippy::mutable_key_type)]
17666                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17667                            multibuffer
17668                                .all_buffers()
17669                                .into_iter()
17670                                .filter_map(|buffer| {
17671                                    buffer.update(cx, |buffer, cx| {
17672                                        let language = buffer.language()?;
17673                                        let should_discard = project.update(cx, |project, cx| {
17674                                            project.is_local()
17675                                                && !project.has_language_servers_for(buffer, cx)
17676                                        });
17677                                        should_discard.not().then_some(language.clone())
17678                                    })
17679                                })
17680                                .collect::<HashSet<_>>()
17681                        });
17682                        if !languages_affected.is_empty() {
17683                            self.refresh_inlay_hints(
17684                                InlayHintRefreshReason::BufferEdited(languages_affected),
17685                                cx,
17686                            );
17687                        }
17688                    }
17689                }
17690
17691                let Some(project) = &self.project else { return };
17692                let (telemetry, is_via_ssh) = {
17693                    let project = project.read(cx);
17694                    let telemetry = project.client().telemetry().clone();
17695                    let is_via_ssh = project.is_via_ssh();
17696                    (telemetry, is_via_ssh)
17697                };
17698                refresh_linked_ranges(self, window, cx);
17699                telemetry.log_edit_event("editor", is_via_ssh);
17700            }
17701            multi_buffer::Event::ExcerptsAdded {
17702                buffer,
17703                predecessor,
17704                excerpts,
17705            } => {
17706                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17707                let buffer_id = buffer.read(cx).remote_id();
17708                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17709                    if let Some(project) = &self.project {
17710                        get_uncommitted_diff_for_buffer(
17711                            project,
17712                            [buffer.clone()],
17713                            self.buffer.clone(),
17714                            cx,
17715                        )
17716                        .detach();
17717                    }
17718                }
17719                cx.emit(EditorEvent::ExcerptsAdded {
17720                    buffer: buffer.clone(),
17721                    predecessor: *predecessor,
17722                    excerpts: excerpts.clone(),
17723                });
17724                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17725            }
17726            multi_buffer::Event::ExcerptsRemoved {
17727                ids,
17728                removed_buffer_ids,
17729            } => {
17730                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17731                let buffer = self.buffer.read(cx);
17732                self.registered_buffers
17733                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17734                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17735                cx.emit(EditorEvent::ExcerptsRemoved {
17736                    ids: ids.clone(),
17737                    removed_buffer_ids: removed_buffer_ids.clone(),
17738                })
17739            }
17740            multi_buffer::Event::ExcerptsEdited {
17741                excerpt_ids,
17742                buffer_ids,
17743            } => {
17744                self.display_map.update(cx, |map, cx| {
17745                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17746                });
17747                cx.emit(EditorEvent::ExcerptsEdited {
17748                    ids: excerpt_ids.clone(),
17749                })
17750            }
17751            multi_buffer::Event::ExcerptsExpanded { ids } => {
17752                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17753                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17754            }
17755            multi_buffer::Event::Reparsed(buffer_id) => {
17756                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17757                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17758
17759                cx.emit(EditorEvent::Reparsed(*buffer_id));
17760            }
17761            multi_buffer::Event::DiffHunksToggled => {
17762                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17763            }
17764            multi_buffer::Event::LanguageChanged(buffer_id) => {
17765                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17766                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17767                cx.emit(EditorEvent::Reparsed(*buffer_id));
17768                cx.notify();
17769            }
17770            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17771            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17772            multi_buffer::Event::FileHandleChanged
17773            | multi_buffer::Event::Reloaded
17774            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17775            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17776            multi_buffer::Event::DiagnosticsUpdated => {
17777                self.refresh_active_diagnostics(cx);
17778                self.refresh_inline_diagnostics(true, window, cx);
17779                self.scrollbar_marker_state.dirty = true;
17780                cx.notify();
17781            }
17782            _ => {}
17783        };
17784    }
17785
17786    fn on_display_map_changed(
17787        &mut self,
17788        _: Entity<DisplayMap>,
17789        _: &mut Window,
17790        cx: &mut Context<Self>,
17791    ) {
17792        cx.notify();
17793    }
17794
17795    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17796        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17797        self.update_edit_prediction_settings(cx);
17798        self.refresh_inline_completion(true, false, window, cx);
17799        self.refresh_inlay_hints(
17800            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17801                self.selections.newest_anchor().head(),
17802                &self.buffer.read(cx).snapshot(cx),
17803                cx,
17804            )),
17805            cx,
17806        );
17807
17808        let old_cursor_shape = self.cursor_shape;
17809
17810        {
17811            let editor_settings = EditorSettings::get_global(cx);
17812            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17813            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17814            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17815            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17816        }
17817
17818        if old_cursor_shape != self.cursor_shape {
17819            cx.emit(EditorEvent::CursorShapeChanged);
17820        }
17821
17822        let project_settings = ProjectSettings::get_global(cx);
17823        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17824
17825        if self.mode.is_full() {
17826            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17827            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17828            if self.show_inline_diagnostics != show_inline_diagnostics {
17829                self.show_inline_diagnostics = show_inline_diagnostics;
17830                self.refresh_inline_diagnostics(false, window, cx);
17831            }
17832
17833            if self.git_blame_inline_enabled != inline_blame_enabled {
17834                self.toggle_git_blame_inline_internal(false, window, cx);
17835            }
17836        }
17837
17838        cx.notify();
17839    }
17840
17841    pub fn set_searchable(&mut self, searchable: bool) {
17842        self.searchable = searchable;
17843    }
17844
17845    pub fn searchable(&self) -> bool {
17846        self.searchable
17847    }
17848
17849    fn open_proposed_changes_editor(
17850        &mut self,
17851        _: &OpenProposedChangesEditor,
17852        window: &mut Window,
17853        cx: &mut Context<Self>,
17854    ) {
17855        let Some(workspace) = self.workspace() else {
17856            cx.propagate();
17857            return;
17858        };
17859
17860        let selections = self.selections.all::<usize>(cx);
17861        let multi_buffer = self.buffer.read(cx);
17862        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17863        let mut new_selections_by_buffer = HashMap::default();
17864        for selection in selections {
17865            for (buffer, range, _) in
17866                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17867            {
17868                let mut range = range.to_point(buffer);
17869                range.start.column = 0;
17870                range.end.column = buffer.line_len(range.end.row);
17871                new_selections_by_buffer
17872                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17873                    .or_insert(Vec::new())
17874                    .push(range)
17875            }
17876        }
17877
17878        let proposed_changes_buffers = new_selections_by_buffer
17879            .into_iter()
17880            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17881            .collect::<Vec<_>>();
17882        let proposed_changes_editor = cx.new(|cx| {
17883            ProposedChangesEditor::new(
17884                "Proposed changes",
17885                proposed_changes_buffers,
17886                self.project.clone(),
17887                window,
17888                cx,
17889            )
17890        });
17891
17892        window.defer(cx, move |window, cx| {
17893            workspace.update(cx, |workspace, cx| {
17894                workspace.active_pane().update(cx, |pane, cx| {
17895                    pane.add_item(
17896                        Box::new(proposed_changes_editor),
17897                        true,
17898                        true,
17899                        None,
17900                        window,
17901                        cx,
17902                    );
17903                });
17904            });
17905        });
17906    }
17907
17908    pub fn open_excerpts_in_split(
17909        &mut self,
17910        _: &OpenExcerptsSplit,
17911        window: &mut Window,
17912        cx: &mut Context<Self>,
17913    ) {
17914        self.open_excerpts_common(None, true, window, cx)
17915    }
17916
17917    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17918        self.open_excerpts_common(None, false, window, cx)
17919    }
17920
17921    fn open_excerpts_common(
17922        &mut self,
17923        jump_data: Option<JumpData>,
17924        split: bool,
17925        window: &mut Window,
17926        cx: &mut Context<Self>,
17927    ) {
17928        let Some(workspace) = self.workspace() else {
17929            cx.propagate();
17930            return;
17931        };
17932
17933        if self.buffer.read(cx).is_singleton() {
17934            cx.propagate();
17935            return;
17936        }
17937
17938        let mut new_selections_by_buffer = HashMap::default();
17939        match &jump_data {
17940            Some(JumpData::MultiBufferPoint {
17941                excerpt_id,
17942                position,
17943                anchor,
17944                line_offset_from_top,
17945            }) => {
17946                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17947                if let Some(buffer) = multi_buffer_snapshot
17948                    .buffer_id_for_excerpt(*excerpt_id)
17949                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17950                {
17951                    let buffer_snapshot = buffer.read(cx).snapshot();
17952                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17953                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17954                    } else {
17955                        buffer_snapshot.clip_point(*position, Bias::Left)
17956                    };
17957                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17958                    new_selections_by_buffer.insert(
17959                        buffer,
17960                        (
17961                            vec![jump_to_offset..jump_to_offset],
17962                            Some(*line_offset_from_top),
17963                        ),
17964                    );
17965                }
17966            }
17967            Some(JumpData::MultiBufferRow {
17968                row,
17969                line_offset_from_top,
17970            }) => {
17971                let point = MultiBufferPoint::new(row.0, 0);
17972                if let Some((buffer, buffer_point, _)) =
17973                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17974                {
17975                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17976                    new_selections_by_buffer
17977                        .entry(buffer)
17978                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17979                        .0
17980                        .push(buffer_offset..buffer_offset)
17981                }
17982            }
17983            None => {
17984                let selections = self.selections.all::<usize>(cx);
17985                let multi_buffer = self.buffer.read(cx);
17986                for selection in selections {
17987                    for (snapshot, range, _, anchor) in multi_buffer
17988                        .snapshot(cx)
17989                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17990                    {
17991                        if let Some(anchor) = anchor {
17992                            // selection is in a deleted hunk
17993                            let Some(buffer_id) = anchor.buffer_id else {
17994                                continue;
17995                            };
17996                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17997                                continue;
17998                            };
17999                            let offset = text::ToOffset::to_offset(
18000                                &anchor.text_anchor,
18001                                &buffer_handle.read(cx).snapshot(),
18002                            );
18003                            let range = offset..offset;
18004                            new_selections_by_buffer
18005                                .entry(buffer_handle)
18006                                .or_insert((Vec::new(), None))
18007                                .0
18008                                .push(range)
18009                        } else {
18010                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18011                            else {
18012                                continue;
18013                            };
18014                            new_selections_by_buffer
18015                                .entry(buffer_handle)
18016                                .or_insert((Vec::new(), None))
18017                                .0
18018                                .push(range)
18019                        }
18020                    }
18021                }
18022            }
18023        }
18024
18025        new_selections_by_buffer
18026            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18027
18028        if new_selections_by_buffer.is_empty() {
18029            return;
18030        }
18031
18032        // We defer the pane interaction because we ourselves are a workspace item
18033        // and activating a new item causes the pane to call a method on us reentrantly,
18034        // which panics if we're on the stack.
18035        window.defer(cx, move |window, cx| {
18036            workspace.update(cx, |workspace, cx| {
18037                let pane = if split {
18038                    workspace.adjacent_pane(window, cx)
18039                } else {
18040                    workspace.active_pane().clone()
18041                };
18042
18043                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18044                    let editor = buffer
18045                        .read(cx)
18046                        .file()
18047                        .is_none()
18048                        .then(|| {
18049                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18050                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18051                            // Instead, we try to activate the existing editor in the pane first.
18052                            let (editor, pane_item_index) =
18053                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18054                                    let editor = item.downcast::<Editor>()?;
18055                                    let singleton_buffer =
18056                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18057                                    if singleton_buffer == buffer {
18058                                        Some((editor, i))
18059                                    } else {
18060                                        None
18061                                    }
18062                                })?;
18063                            pane.update(cx, |pane, cx| {
18064                                pane.activate_item(pane_item_index, true, true, window, cx)
18065                            });
18066                            Some(editor)
18067                        })
18068                        .flatten()
18069                        .unwrap_or_else(|| {
18070                            workspace.open_project_item::<Self>(
18071                                pane.clone(),
18072                                buffer,
18073                                true,
18074                                true,
18075                                window,
18076                                cx,
18077                            )
18078                        });
18079
18080                    editor.update(cx, |editor, cx| {
18081                        let autoscroll = match scroll_offset {
18082                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18083                            None => Autoscroll::newest(),
18084                        };
18085                        let nav_history = editor.nav_history.take();
18086                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18087                            s.select_ranges(ranges);
18088                        });
18089                        editor.nav_history = nav_history;
18090                    });
18091                }
18092            })
18093        });
18094    }
18095
18096    // For now, don't allow opening excerpts in buffers that aren't backed by
18097    // regular project files.
18098    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18099        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18100    }
18101
18102    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18103        let snapshot = self.buffer.read(cx).read(cx);
18104        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18105        Some(
18106            ranges
18107                .iter()
18108                .map(move |range| {
18109                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18110                })
18111                .collect(),
18112        )
18113    }
18114
18115    fn selection_replacement_ranges(
18116        &self,
18117        range: Range<OffsetUtf16>,
18118        cx: &mut App,
18119    ) -> Vec<Range<OffsetUtf16>> {
18120        let selections = self.selections.all::<OffsetUtf16>(cx);
18121        let newest_selection = selections
18122            .iter()
18123            .max_by_key(|selection| selection.id)
18124            .unwrap();
18125        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18126        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18127        let snapshot = self.buffer.read(cx).read(cx);
18128        selections
18129            .into_iter()
18130            .map(|mut selection| {
18131                selection.start.0 =
18132                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18133                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18134                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18135                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18136            })
18137            .collect()
18138    }
18139
18140    fn report_editor_event(
18141        &self,
18142        event_type: &'static str,
18143        file_extension: Option<String>,
18144        cx: &App,
18145    ) {
18146        if cfg!(any(test, feature = "test-support")) {
18147            return;
18148        }
18149
18150        let Some(project) = &self.project else { return };
18151
18152        // If None, we are in a file without an extension
18153        let file = self
18154            .buffer
18155            .read(cx)
18156            .as_singleton()
18157            .and_then(|b| b.read(cx).file());
18158        let file_extension = file_extension.or(file
18159            .as_ref()
18160            .and_then(|file| Path::new(file.file_name(cx)).extension())
18161            .and_then(|e| e.to_str())
18162            .map(|a| a.to_string()));
18163
18164        let vim_mode = vim_enabled(cx);
18165
18166        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18167        let copilot_enabled = edit_predictions_provider
18168            == language::language_settings::EditPredictionProvider::Copilot;
18169        let copilot_enabled_for_language = self
18170            .buffer
18171            .read(cx)
18172            .language_settings(cx)
18173            .show_edit_predictions;
18174
18175        let project = project.read(cx);
18176        telemetry::event!(
18177            event_type,
18178            file_extension,
18179            vim_mode,
18180            copilot_enabled,
18181            copilot_enabled_for_language,
18182            edit_predictions_provider,
18183            is_via_ssh = project.is_via_ssh(),
18184        );
18185    }
18186
18187    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18188    /// with each line being an array of {text, highlight} objects.
18189    fn copy_highlight_json(
18190        &mut self,
18191        _: &CopyHighlightJson,
18192        window: &mut Window,
18193        cx: &mut Context<Self>,
18194    ) {
18195        #[derive(Serialize)]
18196        struct Chunk<'a> {
18197            text: String,
18198            highlight: Option<&'a str>,
18199        }
18200
18201        let snapshot = self.buffer.read(cx).snapshot(cx);
18202        let range = self
18203            .selected_text_range(false, window, cx)
18204            .and_then(|selection| {
18205                if selection.range.is_empty() {
18206                    None
18207                } else {
18208                    Some(selection.range)
18209                }
18210            })
18211            .unwrap_or_else(|| 0..snapshot.len());
18212
18213        let chunks = snapshot.chunks(range, true);
18214        let mut lines = Vec::new();
18215        let mut line: VecDeque<Chunk> = VecDeque::new();
18216
18217        let Some(style) = self.style.as_ref() else {
18218            return;
18219        };
18220
18221        for chunk in chunks {
18222            let highlight = chunk
18223                .syntax_highlight_id
18224                .and_then(|id| id.name(&style.syntax));
18225            let mut chunk_lines = chunk.text.split('\n').peekable();
18226            while let Some(text) = chunk_lines.next() {
18227                let mut merged_with_last_token = false;
18228                if let Some(last_token) = line.back_mut() {
18229                    if last_token.highlight == highlight {
18230                        last_token.text.push_str(text);
18231                        merged_with_last_token = true;
18232                    }
18233                }
18234
18235                if !merged_with_last_token {
18236                    line.push_back(Chunk {
18237                        text: text.into(),
18238                        highlight,
18239                    });
18240                }
18241
18242                if chunk_lines.peek().is_some() {
18243                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18244                        line.pop_front();
18245                    }
18246                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18247                        line.pop_back();
18248                    }
18249
18250                    lines.push(mem::take(&mut line));
18251                }
18252            }
18253        }
18254
18255        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18256            return;
18257        };
18258        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18259    }
18260
18261    pub fn open_context_menu(
18262        &mut self,
18263        _: &OpenContextMenu,
18264        window: &mut Window,
18265        cx: &mut Context<Self>,
18266    ) {
18267        self.request_autoscroll(Autoscroll::newest(), cx);
18268        let position = self.selections.newest_display(cx).start;
18269        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18270    }
18271
18272    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18273        &self.inlay_hint_cache
18274    }
18275
18276    pub fn replay_insert_event(
18277        &mut self,
18278        text: &str,
18279        relative_utf16_range: Option<Range<isize>>,
18280        window: &mut Window,
18281        cx: &mut Context<Self>,
18282    ) {
18283        if !self.input_enabled {
18284            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18285            return;
18286        }
18287        if let Some(relative_utf16_range) = relative_utf16_range {
18288            let selections = self.selections.all::<OffsetUtf16>(cx);
18289            self.change_selections(None, window, cx, |s| {
18290                let new_ranges = selections.into_iter().map(|range| {
18291                    let start = OffsetUtf16(
18292                        range
18293                            .head()
18294                            .0
18295                            .saturating_add_signed(relative_utf16_range.start),
18296                    );
18297                    let end = OffsetUtf16(
18298                        range
18299                            .head()
18300                            .0
18301                            .saturating_add_signed(relative_utf16_range.end),
18302                    );
18303                    start..end
18304                });
18305                s.select_ranges(new_ranges);
18306            });
18307        }
18308
18309        self.handle_input(text, window, cx);
18310    }
18311
18312    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18313        let Some(provider) = self.semantics_provider.as_ref() else {
18314            return false;
18315        };
18316
18317        let mut supports = false;
18318        self.buffer().update(cx, |this, cx| {
18319            this.for_each_buffer(|buffer| {
18320                supports |= provider.supports_inlay_hints(buffer, cx);
18321            });
18322        });
18323
18324        supports
18325    }
18326
18327    pub fn is_focused(&self, window: &Window) -> bool {
18328        self.focus_handle.is_focused(window)
18329    }
18330
18331    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18332        cx.emit(EditorEvent::Focused);
18333
18334        if let Some(descendant) = self
18335            .last_focused_descendant
18336            .take()
18337            .and_then(|descendant| descendant.upgrade())
18338        {
18339            window.focus(&descendant);
18340        } else {
18341            if let Some(blame) = self.blame.as_ref() {
18342                blame.update(cx, GitBlame::focus)
18343            }
18344
18345            self.blink_manager.update(cx, BlinkManager::enable);
18346            self.show_cursor_names(window, cx);
18347            self.buffer.update(cx, |buffer, cx| {
18348                buffer.finalize_last_transaction(cx);
18349                if self.leader_peer_id.is_none() {
18350                    buffer.set_active_selections(
18351                        &self.selections.disjoint_anchors(),
18352                        self.selections.line_mode,
18353                        self.cursor_shape,
18354                        cx,
18355                    );
18356                }
18357            });
18358        }
18359    }
18360
18361    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18362        cx.emit(EditorEvent::FocusedIn)
18363    }
18364
18365    fn handle_focus_out(
18366        &mut self,
18367        event: FocusOutEvent,
18368        _window: &mut Window,
18369        cx: &mut Context<Self>,
18370    ) {
18371        if event.blurred != self.focus_handle {
18372            self.last_focused_descendant = Some(event.blurred);
18373        }
18374        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18375    }
18376
18377    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18378        self.blink_manager.update(cx, BlinkManager::disable);
18379        self.buffer
18380            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18381
18382        if let Some(blame) = self.blame.as_ref() {
18383            blame.update(cx, GitBlame::blur)
18384        }
18385        if !self.hover_state.focused(window, cx) {
18386            hide_hover(self, cx);
18387        }
18388        if !self
18389            .context_menu
18390            .borrow()
18391            .as_ref()
18392            .is_some_and(|context_menu| context_menu.focused(window, cx))
18393        {
18394            self.hide_context_menu(window, cx);
18395        }
18396        self.discard_inline_completion(false, cx);
18397        cx.emit(EditorEvent::Blurred);
18398        cx.notify();
18399    }
18400
18401    pub fn register_action<A: Action>(
18402        &mut self,
18403        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18404    ) -> Subscription {
18405        let id = self.next_editor_action_id.post_inc();
18406        let listener = Arc::new(listener);
18407        self.editor_actions.borrow_mut().insert(
18408            id,
18409            Box::new(move |window, _| {
18410                let listener = listener.clone();
18411                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18412                    let action = action.downcast_ref().unwrap();
18413                    if phase == DispatchPhase::Bubble {
18414                        listener(action, window, cx)
18415                    }
18416                })
18417            }),
18418        );
18419
18420        let editor_actions = self.editor_actions.clone();
18421        Subscription::new(move || {
18422            editor_actions.borrow_mut().remove(&id);
18423        })
18424    }
18425
18426    pub fn file_header_size(&self) -> u32 {
18427        FILE_HEADER_HEIGHT
18428    }
18429
18430    pub fn restore(
18431        &mut self,
18432        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18433        window: &mut Window,
18434        cx: &mut Context<Self>,
18435    ) {
18436        let workspace = self.workspace();
18437        let project = self.project.as_ref();
18438        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18439            let mut tasks = Vec::new();
18440            for (buffer_id, changes) in revert_changes {
18441                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18442                    buffer.update(cx, |buffer, cx| {
18443                        buffer.edit(
18444                            changes
18445                                .into_iter()
18446                                .map(|(range, text)| (range, text.to_string())),
18447                            None,
18448                            cx,
18449                        );
18450                    });
18451
18452                    if let Some(project) =
18453                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18454                    {
18455                        project.update(cx, |project, cx| {
18456                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18457                        })
18458                    }
18459                }
18460            }
18461            tasks
18462        });
18463        cx.spawn_in(window, async move |_, cx| {
18464            for (buffer, task) in save_tasks {
18465                let result = task.await;
18466                if result.is_err() {
18467                    let Some(path) = buffer
18468                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18469                        .ok()
18470                    else {
18471                        continue;
18472                    };
18473                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18474                        let Some(task) = cx
18475                            .update_window_entity(&workspace, |workspace, window, cx| {
18476                                workspace
18477                                    .open_path_preview(path, None, false, false, false, window, cx)
18478                            })
18479                            .ok()
18480                        else {
18481                            continue;
18482                        };
18483                        task.await.log_err();
18484                    }
18485                }
18486            }
18487        })
18488        .detach();
18489        self.change_selections(None, window, cx, |selections| selections.refresh());
18490    }
18491
18492    pub fn to_pixel_point(
18493        &self,
18494        source: multi_buffer::Anchor,
18495        editor_snapshot: &EditorSnapshot,
18496        window: &mut Window,
18497    ) -> Option<gpui::Point<Pixels>> {
18498        let source_point = source.to_display_point(editor_snapshot);
18499        self.display_to_pixel_point(source_point, editor_snapshot, window)
18500    }
18501
18502    pub fn display_to_pixel_point(
18503        &self,
18504        source: DisplayPoint,
18505        editor_snapshot: &EditorSnapshot,
18506        window: &mut Window,
18507    ) -> Option<gpui::Point<Pixels>> {
18508        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18509        let text_layout_details = self.text_layout_details(window);
18510        let scroll_top = text_layout_details
18511            .scroll_anchor
18512            .scroll_position(editor_snapshot)
18513            .y;
18514
18515        if source.row().as_f32() < scroll_top.floor() {
18516            return None;
18517        }
18518        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18519        let source_y = line_height * (source.row().as_f32() - scroll_top);
18520        Some(gpui::Point::new(source_x, source_y))
18521    }
18522
18523    pub fn has_visible_completions_menu(&self) -> bool {
18524        !self.edit_prediction_preview_is_active()
18525            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18526                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18527            })
18528    }
18529
18530    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18531        self.addons
18532            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18533    }
18534
18535    pub fn unregister_addon<T: Addon>(&mut self) {
18536        self.addons.remove(&std::any::TypeId::of::<T>());
18537    }
18538
18539    pub fn addon<T: Addon>(&self) -> Option<&T> {
18540        let type_id = std::any::TypeId::of::<T>();
18541        self.addons
18542            .get(&type_id)
18543            .and_then(|item| item.to_any().downcast_ref::<T>())
18544    }
18545
18546    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18547        let type_id = std::any::TypeId::of::<T>();
18548        self.addons
18549            .get_mut(&type_id)
18550            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18551    }
18552
18553    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18554        let text_layout_details = self.text_layout_details(window);
18555        let style = &text_layout_details.editor_style;
18556        let font_id = window.text_system().resolve_font(&style.text.font());
18557        let font_size = style.text.font_size.to_pixels(window.rem_size());
18558        let line_height = style.text.line_height_in_pixels(window.rem_size());
18559        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18560
18561        gpui::Size::new(em_width, line_height)
18562    }
18563
18564    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18565        self.load_diff_task.clone()
18566    }
18567
18568    fn read_metadata_from_db(
18569        &mut self,
18570        item_id: u64,
18571        workspace_id: WorkspaceId,
18572        window: &mut Window,
18573        cx: &mut Context<Editor>,
18574    ) {
18575        if self.is_singleton(cx)
18576            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18577        {
18578            let buffer_snapshot = OnceCell::new();
18579
18580            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18581                if !folds.is_empty() {
18582                    let snapshot =
18583                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18584                    self.fold_ranges(
18585                        folds
18586                            .into_iter()
18587                            .map(|(start, end)| {
18588                                snapshot.clip_offset(start, Bias::Left)
18589                                    ..snapshot.clip_offset(end, Bias::Right)
18590                            })
18591                            .collect(),
18592                        false,
18593                        window,
18594                        cx,
18595                    );
18596                }
18597            }
18598
18599            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18600                if !selections.is_empty() {
18601                    let snapshot =
18602                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18603                    self.change_selections(None, window, cx, |s| {
18604                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18605                            snapshot.clip_offset(start, Bias::Left)
18606                                ..snapshot.clip_offset(end, Bias::Right)
18607                        }));
18608                    });
18609                }
18610            };
18611        }
18612
18613        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18614    }
18615}
18616
18617fn vim_enabled(cx: &App) -> bool {
18618    cx.global::<SettingsStore>()
18619        .raw_user_settings()
18620        .get("vim_mode")
18621        == Some(&serde_json::Value::Bool(true))
18622}
18623
18624// Consider user intent and default settings
18625fn choose_completion_range(
18626    completion: &Completion,
18627    intent: CompletionIntent,
18628    buffer: &Entity<Buffer>,
18629    cx: &mut Context<Editor>,
18630) -> Range<usize> {
18631    fn should_replace(
18632        completion: &Completion,
18633        insert_range: &Range<text::Anchor>,
18634        intent: CompletionIntent,
18635        completion_mode_setting: LspInsertMode,
18636        buffer: &Buffer,
18637    ) -> bool {
18638        // specific actions take precedence over settings
18639        match intent {
18640            CompletionIntent::CompleteWithInsert => return false,
18641            CompletionIntent::CompleteWithReplace => return true,
18642            CompletionIntent::Complete | CompletionIntent::Compose => {}
18643        }
18644
18645        match completion_mode_setting {
18646            LspInsertMode::Insert => false,
18647            LspInsertMode::Replace => true,
18648            LspInsertMode::ReplaceSubsequence => {
18649                let mut text_to_replace = buffer.chars_for_range(
18650                    buffer.anchor_before(completion.replace_range.start)
18651                        ..buffer.anchor_after(completion.replace_range.end),
18652                );
18653                let mut completion_text = completion.new_text.chars();
18654
18655                // is `text_to_replace` a subsequence of `completion_text`
18656                text_to_replace
18657                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18658            }
18659            LspInsertMode::ReplaceSuffix => {
18660                let range_after_cursor = insert_range.end..completion.replace_range.end;
18661
18662                let text_after_cursor = buffer
18663                    .text_for_range(
18664                        buffer.anchor_before(range_after_cursor.start)
18665                            ..buffer.anchor_after(range_after_cursor.end),
18666                    )
18667                    .collect::<String>();
18668                completion.new_text.ends_with(&text_after_cursor)
18669            }
18670        }
18671    }
18672
18673    let buffer = buffer.read(cx);
18674
18675    if let CompletionSource::Lsp {
18676        insert_range: Some(insert_range),
18677        ..
18678    } = &completion.source
18679    {
18680        let completion_mode_setting =
18681            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18682                .completions
18683                .lsp_insert_mode;
18684
18685        if !should_replace(
18686            completion,
18687            &insert_range,
18688            intent,
18689            completion_mode_setting,
18690            buffer,
18691        ) {
18692            return insert_range.to_offset(buffer);
18693        }
18694    }
18695
18696    completion.replace_range.to_offset(buffer)
18697}
18698
18699fn insert_extra_newline_brackets(
18700    buffer: &MultiBufferSnapshot,
18701    range: Range<usize>,
18702    language: &language::LanguageScope,
18703) -> bool {
18704    let leading_whitespace_len = buffer
18705        .reversed_chars_at(range.start)
18706        .take_while(|c| c.is_whitespace() && *c != '\n')
18707        .map(|c| c.len_utf8())
18708        .sum::<usize>();
18709    let trailing_whitespace_len = buffer
18710        .chars_at(range.end)
18711        .take_while(|c| c.is_whitespace() && *c != '\n')
18712        .map(|c| c.len_utf8())
18713        .sum::<usize>();
18714    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18715
18716    language.brackets().any(|(pair, enabled)| {
18717        let pair_start = pair.start.trim_end();
18718        let pair_end = pair.end.trim_start();
18719
18720        enabled
18721            && pair.newline
18722            && buffer.contains_str_at(range.end, pair_end)
18723            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18724    })
18725}
18726
18727fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18728    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18729        [(buffer, range, _)] => (*buffer, range.clone()),
18730        _ => return false,
18731    };
18732    let pair = {
18733        let mut result: Option<BracketMatch> = None;
18734
18735        for pair in buffer
18736            .all_bracket_ranges(range.clone())
18737            .filter(move |pair| {
18738                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18739            })
18740        {
18741            let len = pair.close_range.end - pair.open_range.start;
18742
18743            if let Some(existing) = &result {
18744                let existing_len = existing.close_range.end - existing.open_range.start;
18745                if len > existing_len {
18746                    continue;
18747                }
18748            }
18749
18750            result = Some(pair);
18751        }
18752
18753        result
18754    };
18755    let Some(pair) = pair else {
18756        return false;
18757    };
18758    pair.newline_only
18759        && buffer
18760            .chars_for_range(pair.open_range.end..range.start)
18761            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18762            .all(|c| c.is_whitespace() && c != '\n')
18763}
18764
18765fn get_uncommitted_diff_for_buffer(
18766    project: &Entity<Project>,
18767    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18768    buffer: Entity<MultiBuffer>,
18769    cx: &mut App,
18770) -> Task<()> {
18771    let mut tasks = Vec::new();
18772    project.update(cx, |project, cx| {
18773        for buffer in buffers {
18774            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18775                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18776            }
18777        }
18778    });
18779    cx.spawn(async move |cx| {
18780        let diffs = future::join_all(tasks).await;
18781        buffer
18782            .update(cx, |buffer, cx| {
18783                for diff in diffs.into_iter().flatten() {
18784                    buffer.add_diff(diff, cx);
18785                }
18786            })
18787            .ok();
18788    })
18789}
18790
18791fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18792    let tab_size = tab_size.get() as usize;
18793    let mut width = offset;
18794
18795    for ch in text.chars() {
18796        width += if ch == '\t' {
18797            tab_size - (width % tab_size)
18798        } else {
18799            1
18800        };
18801    }
18802
18803    width - offset
18804}
18805
18806#[cfg(test)]
18807mod tests {
18808    use super::*;
18809
18810    #[test]
18811    fn test_string_size_with_expanded_tabs() {
18812        let nz = |val| NonZeroU32::new(val).unwrap();
18813        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18814        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18815        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18816        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18817        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18818        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18819        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18820        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18821    }
18822}
18823
18824/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18825struct WordBreakingTokenizer<'a> {
18826    input: &'a str,
18827}
18828
18829impl<'a> WordBreakingTokenizer<'a> {
18830    fn new(input: &'a str) -> Self {
18831        Self { input }
18832    }
18833}
18834
18835fn is_char_ideographic(ch: char) -> bool {
18836    use unicode_script::Script::*;
18837    use unicode_script::UnicodeScript;
18838    matches!(ch.script(), Han | Tangut | Yi)
18839}
18840
18841fn is_grapheme_ideographic(text: &str) -> bool {
18842    text.chars().any(is_char_ideographic)
18843}
18844
18845fn is_grapheme_whitespace(text: &str) -> bool {
18846    text.chars().any(|x| x.is_whitespace())
18847}
18848
18849fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18850    text.chars().next().map_or(false, |ch| {
18851        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18852    })
18853}
18854
18855#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18856enum WordBreakToken<'a> {
18857    Word { token: &'a str, grapheme_len: usize },
18858    InlineWhitespace { token: &'a str, grapheme_len: usize },
18859    Newline,
18860}
18861
18862impl<'a> Iterator for WordBreakingTokenizer<'a> {
18863    /// Yields a span, the count of graphemes in the token, and whether it was
18864    /// whitespace. Note that it also breaks at word boundaries.
18865    type Item = WordBreakToken<'a>;
18866
18867    fn next(&mut self) -> Option<Self::Item> {
18868        use unicode_segmentation::UnicodeSegmentation;
18869        if self.input.is_empty() {
18870            return None;
18871        }
18872
18873        let mut iter = self.input.graphemes(true).peekable();
18874        let mut offset = 0;
18875        let mut grapheme_len = 0;
18876        if let Some(first_grapheme) = iter.next() {
18877            let is_newline = first_grapheme == "\n";
18878            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18879            offset += first_grapheme.len();
18880            grapheme_len += 1;
18881            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18882                if let Some(grapheme) = iter.peek().copied() {
18883                    if should_stay_with_preceding_ideograph(grapheme) {
18884                        offset += grapheme.len();
18885                        grapheme_len += 1;
18886                    }
18887                }
18888            } else {
18889                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18890                let mut next_word_bound = words.peek().copied();
18891                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18892                    next_word_bound = words.next();
18893                }
18894                while let Some(grapheme) = iter.peek().copied() {
18895                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18896                        break;
18897                    };
18898                    if is_grapheme_whitespace(grapheme) != is_whitespace
18899                        || (grapheme == "\n") != is_newline
18900                    {
18901                        break;
18902                    };
18903                    offset += grapheme.len();
18904                    grapheme_len += 1;
18905                    iter.next();
18906                }
18907            }
18908            let token = &self.input[..offset];
18909            self.input = &self.input[offset..];
18910            if token == "\n" {
18911                Some(WordBreakToken::Newline)
18912            } else if is_whitespace {
18913                Some(WordBreakToken::InlineWhitespace {
18914                    token,
18915                    grapheme_len,
18916                })
18917            } else {
18918                Some(WordBreakToken::Word {
18919                    token,
18920                    grapheme_len,
18921                })
18922            }
18923        } else {
18924            None
18925        }
18926    }
18927}
18928
18929#[test]
18930fn test_word_breaking_tokenizer() {
18931    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18932        ("", &[]),
18933        ("  ", &[whitespace("  ", 2)]),
18934        ("Ʒ", &[word("Ʒ", 1)]),
18935        ("Ǽ", &[word("Ǽ", 1)]),
18936        ("", &[word("", 1)]),
18937        ("⋑⋑", &[word("⋑⋑", 2)]),
18938        (
18939            "原理,进而",
18940            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18941        ),
18942        (
18943            "hello world",
18944            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18945        ),
18946        (
18947            "hello, world",
18948            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18949        ),
18950        (
18951            "  hello world",
18952            &[
18953                whitespace("  ", 2),
18954                word("hello", 5),
18955                whitespace(" ", 1),
18956                word("world", 5),
18957            ],
18958        ),
18959        (
18960            "这是什么 \n 钢笔",
18961            &[
18962                word("", 1),
18963                word("", 1),
18964                word("", 1),
18965                word("", 1),
18966                whitespace(" ", 1),
18967                newline(),
18968                whitespace(" ", 1),
18969                word("", 1),
18970                word("", 1),
18971            ],
18972        ),
18973        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18974    ];
18975
18976    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18977        WordBreakToken::Word {
18978            token,
18979            grapheme_len,
18980        }
18981    }
18982
18983    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18984        WordBreakToken::InlineWhitespace {
18985            token,
18986            grapheme_len,
18987        }
18988    }
18989
18990    fn newline() -> WordBreakToken<'static> {
18991        WordBreakToken::Newline
18992    }
18993
18994    for (input, result) in tests {
18995        assert_eq!(
18996            WordBreakingTokenizer::new(input)
18997                .collect::<Vec<_>>()
18998                .as_slice(),
18999            *result,
19000        );
19001    }
19002}
19003
19004fn wrap_with_prefix(
19005    line_prefix: String,
19006    unwrapped_text: String,
19007    wrap_column: usize,
19008    tab_size: NonZeroU32,
19009    preserve_existing_whitespace: bool,
19010) -> String {
19011    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19012    let mut wrapped_text = String::new();
19013    let mut current_line = line_prefix.clone();
19014
19015    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19016    let mut current_line_len = line_prefix_len;
19017    let mut in_whitespace = false;
19018    for token in tokenizer {
19019        let have_preceding_whitespace = in_whitespace;
19020        match token {
19021            WordBreakToken::Word {
19022                token,
19023                grapheme_len,
19024            } => {
19025                in_whitespace = false;
19026                if current_line_len + grapheme_len > wrap_column
19027                    && current_line_len != line_prefix_len
19028                {
19029                    wrapped_text.push_str(current_line.trim_end());
19030                    wrapped_text.push('\n');
19031                    current_line.truncate(line_prefix.len());
19032                    current_line_len = line_prefix_len;
19033                }
19034                current_line.push_str(token);
19035                current_line_len += grapheme_len;
19036            }
19037            WordBreakToken::InlineWhitespace {
19038                mut token,
19039                mut grapheme_len,
19040            } => {
19041                in_whitespace = true;
19042                if have_preceding_whitespace && !preserve_existing_whitespace {
19043                    continue;
19044                }
19045                if !preserve_existing_whitespace {
19046                    token = " ";
19047                    grapheme_len = 1;
19048                }
19049                if current_line_len + grapheme_len > wrap_column {
19050                    wrapped_text.push_str(current_line.trim_end());
19051                    wrapped_text.push('\n');
19052                    current_line.truncate(line_prefix.len());
19053                    current_line_len = line_prefix_len;
19054                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19055                    current_line.push_str(token);
19056                    current_line_len += grapheme_len;
19057                }
19058            }
19059            WordBreakToken::Newline => {
19060                in_whitespace = true;
19061                if preserve_existing_whitespace {
19062                    wrapped_text.push_str(current_line.trim_end());
19063                    wrapped_text.push('\n');
19064                    current_line.truncate(line_prefix.len());
19065                    current_line_len = line_prefix_len;
19066                } else if have_preceding_whitespace {
19067                    continue;
19068                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19069                {
19070                    wrapped_text.push_str(current_line.trim_end());
19071                    wrapped_text.push('\n');
19072                    current_line.truncate(line_prefix.len());
19073                    current_line_len = line_prefix_len;
19074                } else if current_line_len != line_prefix_len {
19075                    current_line.push(' ');
19076                    current_line_len += 1;
19077                }
19078            }
19079        }
19080    }
19081
19082    if !current_line.is_empty() {
19083        wrapped_text.push_str(&current_line);
19084    }
19085    wrapped_text
19086}
19087
19088#[test]
19089fn test_wrap_with_prefix() {
19090    assert_eq!(
19091        wrap_with_prefix(
19092            "# ".to_string(),
19093            "abcdefg".to_string(),
19094            4,
19095            NonZeroU32::new(4).unwrap(),
19096            false,
19097        ),
19098        "# abcdefg"
19099    );
19100    assert_eq!(
19101        wrap_with_prefix(
19102            "".to_string(),
19103            "\thello world".to_string(),
19104            8,
19105            NonZeroU32::new(4).unwrap(),
19106            false,
19107        ),
19108        "hello\nworld"
19109    );
19110    assert_eq!(
19111        wrap_with_prefix(
19112            "// ".to_string(),
19113            "xx \nyy zz aa bb cc".to_string(),
19114            12,
19115            NonZeroU32::new(4).unwrap(),
19116            false,
19117        ),
19118        "// xx yy zz\n// aa bb cc"
19119    );
19120    assert_eq!(
19121        wrap_with_prefix(
19122            String::new(),
19123            "这是什么 \n 钢笔".to_string(),
19124            3,
19125            NonZeroU32::new(4).unwrap(),
19126            false,
19127        ),
19128        "这是什\n么 钢\n"
19129    );
19130}
19131
19132pub trait CollaborationHub {
19133    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19134    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19135    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19136}
19137
19138impl CollaborationHub for Entity<Project> {
19139    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19140        self.read(cx).collaborators()
19141    }
19142
19143    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19144        self.read(cx).user_store().read(cx).participant_indices()
19145    }
19146
19147    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19148        let this = self.read(cx);
19149        let user_ids = this.collaborators().values().map(|c| c.user_id);
19150        this.user_store().read_with(cx, |user_store, cx| {
19151            user_store.participant_names(user_ids, cx)
19152        })
19153    }
19154}
19155
19156pub trait SemanticsProvider {
19157    fn hover(
19158        &self,
19159        buffer: &Entity<Buffer>,
19160        position: text::Anchor,
19161        cx: &mut App,
19162    ) -> Option<Task<Vec<project::Hover>>>;
19163
19164    fn inline_values(
19165        &self,
19166        buffer_handle: Entity<Buffer>,
19167        range: Range<text::Anchor>,
19168        cx: &mut App,
19169    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19170
19171    fn inlay_hints(
19172        &self,
19173        buffer_handle: Entity<Buffer>,
19174        range: Range<text::Anchor>,
19175        cx: &mut App,
19176    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19177
19178    fn resolve_inlay_hint(
19179        &self,
19180        hint: InlayHint,
19181        buffer_handle: Entity<Buffer>,
19182        server_id: LanguageServerId,
19183        cx: &mut App,
19184    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19185
19186    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19187
19188    fn document_highlights(
19189        &self,
19190        buffer: &Entity<Buffer>,
19191        position: text::Anchor,
19192        cx: &mut App,
19193    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19194
19195    fn definitions(
19196        &self,
19197        buffer: &Entity<Buffer>,
19198        position: text::Anchor,
19199        kind: GotoDefinitionKind,
19200        cx: &mut App,
19201    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19202
19203    fn range_for_rename(
19204        &self,
19205        buffer: &Entity<Buffer>,
19206        position: text::Anchor,
19207        cx: &mut App,
19208    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19209
19210    fn perform_rename(
19211        &self,
19212        buffer: &Entity<Buffer>,
19213        position: text::Anchor,
19214        new_name: String,
19215        cx: &mut App,
19216    ) -> Option<Task<Result<ProjectTransaction>>>;
19217}
19218
19219pub trait CompletionProvider {
19220    fn completions(
19221        &self,
19222        excerpt_id: ExcerptId,
19223        buffer: &Entity<Buffer>,
19224        buffer_position: text::Anchor,
19225        trigger: CompletionContext,
19226        window: &mut Window,
19227        cx: &mut Context<Editor>,
19228    ) -> Task<Result<Option<Vec<Completion>>>>;
19229
19230    fn resolve_completions(
19231        &self,
19232        buffer: Entity<Buffer>,
19233        completion_indices: Vec<usize>,
19234        completions: Rc<RefCell<Box<[Completion]>>>,
19235        cx: &mut Context<Editor>,
19236    ) -> Task<Result<bool>>;
19237
19238    fn apply_additional_edits_for_completion(
19239        &self,
19240        _buffer: Entity<Buffer>,
19241        _completions: Rc<RefCell<Box<[Completion]>>>,
19242        _completion_index: usize,
19243        _push_to_history: bool,
19244        _cx: &mut Context<Editor>,
19245    ) -> Task<Result<Option<language::Transaction>>> {
19246        Task::ready(Ok(None))
19247    }
19248
19249    fn is_completion_trigger(
19250        &self,
19251        buffer: &Entity<Buffer>,
19252        position: language::Anchor,
19253        text: &str,
19254        trigger_in_words: bool,
19255        cx: &mut Context<Editor>,
19256    ) -> bool;
19257
19258    fn sort_completions(&self) -> bool {
19259        true
19260    }
19261
19262    fn filter_completions(&self) -> bool {
19263        true
19264    }
19265}
19266
19267pub trait CodeActionProvider {
19268    fn id(&self) -> Arc<str>;
19269
19270    fn code_actions(
19271        &self,
19272        buffer: &Entity<Buffer>,
19273        range: Range<text::Anchor>,
19274        window: &mut Window,
19275        cx: &mut App,
19276    ) -> Task<Result<Vec<CodeAction>>>;
19277
19278    fn apply_code_action(
19279        &self,
19280        buffer_handle: Entity<Buffer>,
19281        action: CodeAction,
19282        excerpt_id: ExcerptId,
19283        push_to_history: bool,
19284        window: &mut Window,
19285        cx: &mut App,
19286    ) -> Task<Result<ProjectTransaction>>;
19287}
19288
19289impl CodeActionProvider for Entity<Project> {
19290    fn id(&self) -> Arc<str> {
19291        "project".into()
19292    }
19293
19294    fn code_actions(
19295        &self,
19296        buffer: &Entity<Buffer>,
19297        range: Range<text::Anchor>,
19298        _window: &mut Window,
19299        cx: &mut App,
19300    ) -> Task<Result<Vec<CodeAction>>> {
19301        self.update(cx, |project, cx| {
19302            let code_lens = project.code_lens(buffer, range.clone(), cx);
19303            let code_actions = project.code_actions(buffer, range, None, cx);
19304            cx.background_spawn(async move {
19305                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19306                Ok(code_lens
19307                    .context("code lens fetch")?
19308                    .into_iter()
19309                    .chain(code_actions.context("code action fetch")?)
19310                    .collect())
19311            })
19312        })
19313    }
19314
19315    fn apply_code_action(
19316        &self,
19317        buffer_handle: Entity<Buffer>,
19318        action: CodeAction,
19319        _excerpt_id: ExcerptId,
19320        push_to_history: bool,
19321        _window: &mut Window,
19322        cx: &mut App,
19323    ) -> Task<Result<ProjectTransaction>> {
19324        self.update(cx, |project, cx| {
19325            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19326        })
19327    }
19328}
19329
19330fn snippet_completions(
19331    project: &Project,
19332    buffer: &Entity<Buffer>,
19333    buffer_position: text::Anchor,
19334    cx: &mut App,
19335) -> Task<Result<Vec<Completion>>> {
19336    let languages = buffer.read(cx).languages_at(buffer_position);
19337    let snippet_store = project.snippets().read(cx);
19338
19339    let scopes: Vec<_> = languages
19340        .iter()
19341        .filter_map(|language| {
19342            let language_name = language.lsp_id();
19343            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19344
19345            if snippets.is_empty() {
19346                None
19347            } else {
19348                Some((language.default_scope(), snippets))
19349            }
19350        })
19351        .collect();
19352
19353    if scopes.is_empty() {
19354        return Task::ready(Ok(vec![]));
19355    }
19356
19357    let snapshot = buffer.read(cx).text_snapshot();
19358    let chars: String = snapshot
19359        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19360        .collect();
19361    let executor = cx.background_executor().clone();
19362
19363    cx.background_spawn(async move {
19364        let mut all_results: Vec<Completion> = Vec::new();
19365        for (scope, snippets) in scopes.into_iter() {
19366            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19367            let mut last_word = chars
19368                .chars()
19369                .take_while(|c| classifier.is_word(*c))
19370                .collect::<String>();
19371            last_word = last_word.chars().rev().collect();
19372
19373            if last_word.is_empty() {
19374                return Ok(vec![]);
19375            }
19376
19377            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19378            let to_lsp = |point: &text::Anchor| {
19379                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19380                point_to_lsp(end)
19381            };
19382            let lsp_end = to_lsp(&buffer_position);
19383
19384            let candidates = snippets
19385                .iter()
19386                .enumerate()
19387                .flat_map(|(ix, snippet)| {
19388                    snippet
19389                        .prefix
19390                        .iter()
19391                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19392                })
19393                .collect::<Vec<StringMatchCandidate>>();
19394
19395            let mut matches = fuzzy::match_strings(
19396                &candidates,
19397                &last_word,
19398                last_word.chars().any(|c| c.is_uppercase()),
19399                100,
19400                &Default::default(),
19401                executor.clone(),
19402            )
19403            .await;
19404
19405            // Remove all candidates where the query's start does not match the start of any word in the candidate
19406            if let Some(query_start) = last_word.chars().next() {
19407                matches.retain(|string_match| {
19408                    split_words(&string_match.string).any(|word| {
19409                        // Check that the first codepoint of the word as lowercase matches the first
19410                        // codepoint of the query as lowercase
19411                        word.chars()
19412                            .flat_map(|codepoint| codepoint.to_lowercase())
19413                            .zip(query_start.to_lowercase())
19414                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19415                    })
19416                });
19417            }
19418
19419            let matched_strings = matches
19420                .into_iter()
19421                .map(|m| m.string)
19422                .collect::<HashSet<_>>();
19423
19424            let mut result: Vec<Completion> = snippets
19425                .iter()
19426                .filter_map(|snippet| {
19427                    let matching_prefix = snippet
19428                        .prefix
19429                        .iter()
19430                        .find(|prefix| matched_strings.contains(*prefix))?;
19431                    let start = as_offset - last_word.len();
19432                    let start = snapshot.anchor_before(start);
19433                    let range = start..buffer_position;
19434                    let lsp_start = to_lsp(&start);
19435                    let lsp_range = lsp::Range {
19436                        start: lsp_start,
19437                        end: lsp_end,
19438                    };
19439                    Some(Completion {
19440                        replace_range: range,
19441                        new_text: snippet.body.clone(),
19442                        source: CompletionSource::Lsp {
19443                            insert_range: None,
19444                            server_id: LanguageServerId(usize::MAX),
19445                            resolved: true,
19446                            lsp_completion: Box::new(lsp::CompletionItem {
19447                                label: snippet.prefix.first().unwrap().clone(),
19448                                kind: Some(CompletionItemKind::SNIPPET),
19449                                label_details: snippet.description.as_ref().map(|description| {
19450                                    lsp::CompletionItemLabelDetails {
19451                                        detail: Some(description.clone()),
19452                                        description: None,
19453                                    }
19454                                }),
19455                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19456                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19457                                    lsp::InsertReplaceEdit {
19458                                        new_text: snippet.body.clone(),
19459                                        insert: lsp_range,
19460                                        replace: lsp_range,
19461                                    },
19462                                )),
19463                                filter_text: Some(snippet.body.clone()),
19464                                sort_text: Some(char::MAX.to_string()),
19465                                ..lsp::CompletionItem::default()
19466                            }),
19467                            lsp_defaults: None,
19468                        },
19469                        label: CodeLabel {
19470                            text: matching_prefix.clone(),
19471                            runs: Vec::new(),
19472                            filter_range: 0..matching_prefix.len(),
19473                        },
19474                        icon_path: None,
19475                        documentation: snippet.description.clone().map(|description| {
19476                            CompletionDocumentation::SingleLine(description.into())
19477                        }),
19478                        insert_text_mode: None,
19479                        confirm: None,
19480                    })
19481                })
19482                .collect();
19483
19484            all_results.append(&mut result);
19485        }
19486
19487        Ok(all_results)
19488    })
19489}
19490
19491impl CompletionProvider for Entity<Project> {
19492    fn completions(
19493        &self,
19494        _excerpt_id: ExcerptId,
19495        buffer: &Entity<Buffer>,
19496        buffer_position: text::Anchor,
19497        options: CompletionContext,
19498        _window: &mut Window,
19499        cx: &mut Context<Editor>,
19500    ) -> Task<Result<Option<Vec<Completion>>>> {
19501        self.update(cx, |project, cx| {
19502            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19503            let project_completions = project.completions(buffer, buffer_position, options, cx);
19504            cx.background_spawn(async move {
19505                let snippets_completions = snippets.await?;
19506                match project_completions.await? {
19507                    Some(mut completions) => {
19508                        completions.extend(snippets_completions);
19509                        Ok(Some(completions))
19510                    }
19511                    None => {
19512                        if snippets_completions.is_empty() {
19513                            Ok(None)
19514                        } else {
19515                            Ok(Some(snippets_completions))
19516                        }
19517                    }
19518                }
19519            })
19520        })
19521    }
19522
19523    fn resolve_completions(
19524        &self,
19525        buffer: Entity<Buffer>,
19526        completion_indices: Vec<usize>,
19527        completions: Rc<RefCell<Box<[Completion]>>>,
19528        cx: &mut Context<Editor>,
19529    ) -> Task<Result<bool>> {
19530        self.update(cx, |project, cx| {
19531            project.lsp_store().update(cx, |lsp_store, cx| {
19532                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19533            })
19534        })
19535    }
19536
19537    fn apply_additional_edits_for_completion(
19538        &self,
19539        buffer: Entity<Buffer>,
19540        completions: Rc<RefCell<Box<[Completion]>>>,
19541        completion_index: usize,
19542        push_to_history: bool,
19543        cx: &mut Context<Editor>,
19544    ) -> Task<Result<Option<language::Transaction>>> {
19545        self.update(cx, |project, cx| {
19546            project.lsp_store().update(cx, |lsp_store, cx| {
19547                lsp_store.apply_additional_edits_for_completion(
19548                    buffer,
19549                    completions,
19550                    completion_index,
19551                    push_to_history,
19552                    cx,
19553                )
19554            })
19555        })
19556    }
19557
19558    fn is_completion_trigger(
19559        &self,
19560        buffer: &Entity<Buffer>,
19561        position: language::Anchor,
19562        text: &str,
19563        trigger_in_words: bool,
19564        cx: &mut Context<Editor>,
19565    ) -> bool {
19566        let mut chars = text.chars();
19567        let char = if let Some(char) = chars.next() {
19568            char
19569        } else {
19570            return false;
19571        };
19572        if chars.next().is_some() {
19573            return false;
19574        }
19575
19576        let buffer = buffer.read(cx);
19577        let snapshot = buffer.snapshot();
19578        if !snapshot.settings_at(position, cx).show_completions_on_input {
19579            return false;
19580        }
19581        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19582        if trigger_in_words && classifier.is_word(char) {
19583            return true;
19584        }
19585
19586        buffer.completion_triggers().contains(text)
19587    }
19588}
19589
19590impl SemanticsProvider for Entity<Project> {
19591    fn hover(
19592        &self,
19593        buffer: &Entity<Buffer>,
19594        position: text::Anchor,
19595        cx: &mut App,
19596    ) -> Option<Task<Vec<project::Hover>>> {
19597        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19598    }
19599
19600    fn document_highlights(
19601        &self,
19602        buffer: &Entity<Buffer>,
19603        position: text::Anchor,
19604        cx: &mut App,
19605    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19606        Some(self.update(cx, |project, cx| {
19607            project.document_highlights(buffer, position, cx)
19608        }))
19609    }
19610
19611    fn definitions(
19612        &self,
19613        buffer: &Entity<Buffer>,
19614        position: text::Anchor,
19615        kind: GotoDefinitionKind,
19616        cx: &mut App,
19617    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19618        Some(self.update(cx, |project, cx| match kind {
19619            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19620            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19621            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19622            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19623        }))
19624    }
19625
19626    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19627        // TODO: make this work for remote projects
19628        self.update(cx, |project, cx| {
19629            if project
19630                .active_debug_session(cx)
19631                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19632            {
19633                return true;
19634            }
19635
19636            buffer.update(cx, |buffer, cx| {
19637                project.any_language_server_supports_inlay_hints(buffer, cx)
19638            })
19639        })
19640    }
19641
19642    fn inline_values(
19643        &self,
19644        buffer_handle: Entity<Buffer>,
19645        range: Range<text::Anchor>,
19646        cx: &mut App,
19647    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19648        self.update(cx, |project, cx| {
19649            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19650
19651            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19652        })
19653    }
19654
19655    fn inlay_hints(
19656        &self,
19657        buffer_handle: Entity<Buffer>,
19658        range: Range<text::Anchor>,
19659        cx: &mut App,
19660    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19661        Some(self.update(cx, |project, cx| {
19662            project.inlay_hints(buffer_handle, range, cx)
19663        }))
19664    }
19665
19666    fn resolve_inlay_hint(
19667        &self,
19668        hint: InlayHint,
19669        buffer_handle: Entity<Buffer>,
19670        server_id: LanguageServerId,
19671        cx: &mut App,
19672    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19673        Some(self.update(cx, |project, cx| {
19674            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19675        }))
19676    }
19677
19678    fn range_for_rename(
19679        &self,
19680        buffer: &Entity<Buffer>,
19681        position: text::Anchor,
19682        cx: &mut App,
19683    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19684        Some(self.update(cx, |project, cx| {
19685            let buffer = buffer.clone();
19686            let task = project.prepare_rename(buffer.clone(), position, cx);
19687            cx.spawn(async move |_, cx| {
19688                Ok(match task.await? {
19689                    PrepareRenameResponse::Success(range) => Some(range),
19690                    PrepareRenameResponse::InvalidPosition => None,
19691                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19692                        // Fallback on using TreeSitter info to determine identifier range
19693                        buffer.update(cx, |buffer, _| {
19694                            let snapshot = buffer.snapshot();
19695                            let (range, kind) = snapshot.surrounding_word(position);
19696                            if kind != Some(CharKind::Word) {
19697                                return None;
19698                            }
19699                            Some(
19700                                snapshot.anchor_before(range.start)
19701                                    ..snapshot.anchor_after(range.end),
19702                            )
19703                        })?
19704                    }
19705                })
19706            })
19707        }))
19708    }
19709
19710    fn perform_rename(
19711        &self,
19712        buffer: &Entity<Buffer>,
19713        position: text::Anchor,
19714        new_name: String,
19715        cx: &mut App,
19716    ) -> Option<Task<Result<ProjectTransaction>>> {
19717        Some(self.update(cx, |project, cx| {
19718            project.perform_rename(buffer.clone(), position, new_name, cx)
19719        }))
19720    }
19721}
19722
19723fn inlay_hint_settings(
19724    location: Anchor,
19725    snapshot: &MultiBufferSnapshot,
19726    cx: &mut Context<Editor>,
19727) -> InlayHintSettings {
19728    let file = snapshot.file_at(location);
19729    let language = snapshot.language_at(location).map(|l| l.name());
19730    language_settings(language, file, cx).inlay_hints
19731}
19732
19733fn consume_contiguous_rows(
19734    contiguous_row_selections: &mut Vec<Selection<Point>>,
19735    selection: &Selection<Point>,
19736    display_map: &DisplaySnapshot,
19737    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19738) -> (MultiBufferRow, MultiBufferRow) {
19739    contiguous_row_selections.push(selection.clone());
19740    let start_row = MultiBufferRow(selection.start.row);
19741    let mut end_row = ending_row(selection, display_map);
19742
19743    while let Some(next_selection) = selections.peek() {
19744        if next_selection.start.row <= end_row.0 {
19745            end_row = ending_row(next_selection, display_map);
19746            contiguous_row_selections.push(selections.next().unwrap().clone());
19747        } else {
19748            break;
19749        }
19750    }
19751    (start_row, end_row)
19752}
19753
19754fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19755    if next_selection.end.column > 0 || next_selection.is_empty() {
19756        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19757    } else {
19758        MultiBufferRow(next_selection.end.row)
19759    }
19760}
19761
19762impl EditorSnapshot {
19763    pub fn remote_selections_in_range<'a>(
19764        &'a self,
19765        range: &'a Range<Anchor>,
19766        collaboration_hub: &dyn CollaborationHub,
19767        cx: &'a App,
19768    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19769        let participant_names = collaboration_hub.user_names(cx);
19770        let participant_indices = collaboration_hub.user_participant_indices(cx);
19771        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19772        let collaborators_by_replica_id = collaborators_by_peer_id
19773            .iter()
19774            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19775            .collect::<HashMap<_, _>>();
19776        self.buffer_snapshot
19777            .selections_in_range(range, false)
19778            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19779                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19780                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19781                let user_name = participant_names.get(&collaborator.user_id).cloned();
19782                Some(RemoteSelection {
19783                    replica_id,
19784                    selection,
19785                    cursor_shape,
19786                    line_mode,
19787                    participant_index,
19788                    peer_id: collaborator.peer_id,
19789                    user_name,
19790                })
19791            })
19792    }
19793
19794    pub fn hunks_for_ranges(
19795        &self,
19796        ranges: impl IntoIterator<Item = Range<Point>>,
19797    ) -> Vec<MultiBufferDiffHunk> {
19798        let mut hunks = Vec::new();
19799        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19800            HashMap::default();
19801        for query_range in ranges {
19802            let query_rows =
19803                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19804            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19805                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19806            ) {
19807                // Include deleted hunks that are adjacent to the query range, because
19808                // otherwise they would be missed.
19809                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19810                if hunk.status().is_deleted() {
19811                    intersects_range |= hunk.row_range.start == query_rows.end;
19812                    intersects_range |= hunk.row_range.end == query_rows.start;
19813                }
19814                if intersects_range {
19815                    if !processed_buffer_rows
19816                        .entry(hunk.buffer_id)
19817                        .or_default()
19818                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19819                    {
19820                        continue;
19821                    }
19822                    hunks.push(hunk);
19823                }
19824            }
19825        }
19826
19827        hunks
19828    }
19829
19830    fn display_diff_hunks_for_rows<'a>(
19831        &'a self,
19832        display_rows: Range<DisplayRow>,
19833        folded_buffers: &'a HashSet<BufferId>,
19834    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19835        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19836        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19837
19838        self.buffer_snapshot
19839            .diff_hunks_in_range(buffer_start..buffer_end)
19840            .filter_map(|hunk| {
19841                if folded_buffers.contains(&hunk.buffer_id) {
19842                    return None;
19843                }
19844
19845                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19846                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19847
19848                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19849                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19850
19851                let display_hunk = if hunk_display_start.column() != 0 {
19852                    DisplayDiffHunk::Folded {
19853                        display_row: hunk_display_start.row(),
19854                    }
19855                } else {
19856                    let mut end_row = hunk_display_end.row();
19857                    if hunk_display_end.column() > 0 {
19858                        end_row.0 += 1;
19859                    }
19860                    let is_created_file = hunk.is_created_file();
19861                    DisplayDiffHunk::Unfolded {
19862                        status: hunk.status(),
19863                        diff_base_byte_range: hunk.diff_base_byte_range,
19864                        display_row_range: hunk_display_start.row()..end_row,
19865                        multi_buffer_range: Anchor::range_in_buffer(
19866                            hunk.excerpt_id,
19867                            hunk.buffer_id,
19868                            hunk.buffer_range,
19869                        ),
19870                        is_created_file,
19871                    }
19872                };
19873
19874                Some(display_hunk)
19875            })
19876    }
19877
19878    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19879        self.display_snapshot.buffer_snapshot.language_at(position)
19880    }
19881
19882    pub fn is_focused(&self) -> bool {
19883        self.is_focused
19884    }
19885
19886    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19887        self.placeholder_text.as_ref()
19888    }
19889
19890    pub fn scroll_position(&self) -> gpui::Point<f32> {
19891        self.scroll_anchor.scroll_position(&self.display_snapshot)
19892    }
19893
19894    fn gutter_dimensions(
19895        &self,
19896        font_id: FontId,
19897        font_size: Pixels,
19898        max_line_number_width: Pixels,
19899        cx: &App,
19900    ) -> Option<GutterDimensions> {
19901        if !self.show_gutter {
19902            return None;
19903        }
19904
19905        let descent = cx.text_system().descent(font_id, font_size);
19906        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19907        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19908
19909        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19910            matches!(
19911                ProjectSettings::get_global(cx).git.git_gutter,
19912                Some(GitGutterSetting::TrackedFiles)
19913            )
19914        });
19915        let gutter_settings = EditorSettings::get_global(cx).gutter;
19916        let show_line_numbers = self
19917            .show_line_numbers
19918            .unwrap_or(gutter_settings.line_numbers);
19919        let line_gutter_width = if show_line_numbers {
19920            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19921            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19922            max_line_number_width.max(min_width_for_number_on_gutter)
19923        } else {
19924            0.0.into()
19925        };
19926
19927        let show_code_actions = self
19928            .show_code_actions
19929            .unwrap_or(gutter_settings.code_actions);
19930
19931        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19932        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19933
19934        let git_blame_entries_width =
19935            self.git_blame_gutter_max_author_length
19936                .map(|max_author_length| {
19937                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19938                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19939
19940                    /// The number of characters to dedicate to gaps and margins.
19941                    const SPACING_WIDTH: usize = 4;
19942
19943                    let max_char_count = max_author_length.min(renderer.max_author_length())
19944                        + ::git::SHORT_SHA_LENGTH
19945                        + MAX_RELATIVE_TIMESTAMP.len()
19946                        + SPACING_WIDTH;
19947
19948                    em_advance * max_char_count
19949                });
19950
19951        let is_singleton = self.buffer_snapshot.is_singleton();
19952
19953        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19954        left_padding += if !is_singleton {
19955            em_width * 4.0
19956        } else if show_code_actions || show_runnables || show_breakpoints {
19957            em_width * 3.0
19958        } else if show_git_gutter && show_line_numbers {
19959            em_width * 2.0
19960        } else if show_git_gutter || show_line_numbers {
19961            em_width
19962        } else {
19963            px(0.)
19964        };
19965
19966        let shows_folds = is_singleton && gutter_settings.folds;
19967
19968        let right_padding = if shows_folds && show_line_numbers {
19969            em_width * 4.0
19970        } else if shows_folds || (!is_singleton && show_line_numbers) {
19971            em_width * 3.0
19972        } else if show_line_numbers {
19973            em_width
19974        } else {
19975            px(0.)
19976        };
19977
19978        Some(GutterDimensions {
19979            left_padding,
19980            right_padding,
19981            width: line_gutter_width + left_padding + right_padding,
19982            margin: -descent,
19983            git_blame_entries_width,
19984        })
19985    }
19986
19987    pub fn render_crease_toggle(
19988        &self,
19989        buffer_row: MultiBufferRow,
19990        row_contains_cursor: bool,
19991        editor: Entity<Editor>,
19992        window: &mut Window,
19993        cx: &mut App,
19994    ) -> Option<AnyElement> {
19995        let folded = self.is_line_folded(buffer_row);
19996        let mut is_foldable = false;
19997
19998        if let Some(crease) = self
19999            .crease_snapshot
20000            .query_row(buffer_row, &self.buffer_snapshot)
20001        {
20002            is_foldable = true;
20003            match crease {
20004                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20005                    if let Some(render_toggle) = render_toggle {
20006                        let toggle_callback =
20007                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20008                                if folded {
20009                                    editor.update(cx, |editor, cx| {
20010                                        editor.fold_at(buffer_row, window, cx)
20011                                    });
20012                                } else {
20013                                    editor.update(cx, |editor, cx| {
20014                                        editor.unfold_at(buffer_row, window, cx)
20015                                    });
20016                                }
20017                            });
20018                        return Some((render_toggle)(
20019                            buffer_row,
20020                            folded,
20021                            toggle_callback,
20022                            window,
20023                            cx,
20024                        ));
20025                    }
20026                }
20027            }
20028        }
20029
20030        is_foldable |= self.starts_indent(buffer_row);
20031
20032        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20033            Some(
20034                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20035                    .toggle_state(folded)
20036                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20037                        if folded {
20038                            this.unfold_at(buffer_row, window, cx);
20039                        } else {
20040                            this.fold_at(buffer_row, window, cx);
20041                        }
20042                    }))
20043                    .into_any_element(),
20044            )
20045        } else {
20046            None
20047        }
20048    }
20049
20050    pub fn render_crease_trailer(
20051        &self,
20052        buffer_row: MultiBufferRow,
20053        window: &mut Window,
20054        cx: &mut App,
20055    ) -> Option<AnyElement> {
20056        let folded = self.is_line_folded(buffer_row);
20057        if let Crease::Inline { render_trailer, .. } = self
20058            .crease_snapshot
20059            .query_row(buffer_row, &self.buffer_snapshot)?
20060        {
20061            let render_trailer = render_trailer.as_ref()?;
20062            Some(render_trailer(buffer_row, folded, window, cx))
20063        } else {
20064            None
20065        }
20066    }
20067}
20068
20069impl Deref for EditorSnapshot {
20070    type Target = DisplaySnapshot;
20071
20072    fn deref(&self) -> &Self::Target {
20073        &self.display_snapshot
20074    }
20075}
20076
20077#[derive(Clone, Debug, PartialEq, Eq)]
20078pub enum EditorEvent {
20079    InputIgnored {
20080        text: Arc<str>,
20081    },
20082    InputHandled {
20083        utf16_range_to_replace: Option<Range<isize>>,
20084        text: Arc<str>,
20085    },
20086    ExcerptsAdded {
20087        buffer: Entity<Buffer>,
20088        predecessor: ExcerptId,
20089        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20090    },
20091    ExcerptsRemoved {
20092        ids: Vec<ExcerptId>,
20093        removed_buffer_ids: Vec<BufferId>,
20094    },
20095    BufferFoldToggled {
20096        ids: Vec<ExcerptId>,
20097        folded: bool,
20098    },
20099    ExcerptsEdited {
20100        ids: Vec<ExcerptId>,
20101    },
20102    ExcerptsExpanded {
20103        ids: Vec<ExcerptId>,
20104    },
20105    BufferEdited,
20106    Edited {
20107        transaction_id: clock::Lamport,
20108    },
20109    Reparsed(BufferId),
20110    Focused,
20111    FocusedIn,
20112    Blurred,
20113    DirtyChanged,
20114    Saved,
20115    TitleChanged,
20116    DiffBaseChanged,
20117    SelectionsChanged {
20118        local: bool,
20119    },
20120    ScrollPositionChanged {
20121        local: bool,
20122        autoscroll: bool,
20123    },
20124    Closed,
20125    TransactionUndone {
20126        transaction_id: clock::Lamport,
20127    },
20128    TransactionBegun {
20129        transaction_id: clock::Lamport,
20130    },
20131    Reloaded,
20132    CursorShapeChanged,
20133    PushedToNavHistory {
20134        anchor: Anchor,
20135        is_deactivate: bool,
20136    },
20137}
20138
20139impl EventEmitter<EditorEvent> for Editor {}
20140
20141impl Focusable for Editor {
20142    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20143        self.focus_handle.clone()
20144    }
20145}
20146
20147impl Render for Editor {
20148    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20149        let settings = ThemeSettings::get_global(cx);
20150
20151        let mut text_style = match self.mode {
20152            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20153                color: cx.theme().colors().editor_foreground,
20154                font_family: settings.ui_font.family.clone(),
20155                font_features: settings.ui_font.features.clone(),
20156                font_fallbacks: settings.ui_font.fallbacks.clone(),
20157                font_size: rems(0.875).into(),
20158                font_weight: settings.ui_font.weight,
20159                line_height: relative(settings.buffer_line_height.value()),
20160                ..Default::default()
20161            },
20162            EditorMode::Full { .. } => TextStyle {
20163                color: cx.theme().colors().editor_foreground,
20164                font_family: settings.buffer_font.family.clone(),
20165                font_features: settings.buffer_font.features.clone(),
20166                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20167                font_size: settings.buffer_font_size(cx).into(),
20168                font_weight: settings.buffer_font.weight,
20169                line_height: relative(settings.buffer_line_height.value()),
20170                ..Default::default()
20171            },
20172        };
20173        if let Some(text_style_refinement) = &self.text_style_refinement {
20174            text_style.refine(text_style_refinement)
20175        }
20176
20177        let background = match self.mode {
20178            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20179            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20180            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20181        };
20182
20183        EditorElement::new(
20184            &cx.entity(),
20185            EditorStyle {
20186                background,
20187                local_player: cx.theme().players().local(),
20188                text: text_style,
20189                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20190                syntax: cx.theme().syntax().clone(),
20191                status: cx.theme().status().clone(),
20192                inlay_hints_style: make_inlay_hints_style(cx),
20193                inline_completion_styles: make_suggestion_styles(cx),
20194                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20195            },
20196        )
20197    }
20198}
20199
20200impl EntityInputHandler for Editor {
20201    fn text_for_range(
20202        &mut self,
20203        range_utf16: Range<usize>,
20204        adjusted_range: &mut Option<Range<usize>>,
20205        _: &mut Window,
20206        cx: &mut Context<Self>,
20207    ) -> Option<String> {
20208        let snapshot = self.buffer.read(cx).read(cx);
20209        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20210        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20211        if (start.0..end.0) != range_utf16 {
20212            adjusted_range.replace(start.0..end.0);
20213        }
20214        Some(snapshot.text_for_range(start..end).collect())
20215    }
20216
20217    fn selected_text_range(
20218        &mut self,
20219        ignore_disabled_input: bool,
20220        _: &mut Window,
20221        cx: &mut Context<Self>,
20222    ) -> Option<UTF16Selection> {
20223        // Prevent the IME menu from appearing when holding down an alphabetic key
20224        // while input is disabled.
20225        if !ignore_disabled_input && !self.input_enabled {
20226            return None;
20227        }
20228
20229        let selection = self.selections.newest::<OffsetUtf16>(cx);
20230        let range = selection.range();
20231
20232        Some(UTF16Selection {
20233            range: range.start.0..range.end.0,
20234            reversed: selection.reversed,
20235        })
20236    }
20237
20238    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20239        let snapshot = self.buffer.read(cx).read(cx);
20240        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20241        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20242    }
20243
20244    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20245        self.clear_highlights::<InputComposition>(cx);
20246        self.ime_transaction.take();
20247    }
20248
20249    fn replace_text_in_range(
20250        &mut self,
20251        range_utf16: Option<Range<usize>>,
20252        text: &str,
20253        window: &mut Window,
20254        cx: &mut Context<Self>,
20255    ) {
20256        if !self.input_enabled {
20257            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20258            return;
20259        }
20260
20261        self.transact(window, cx, |this, window, cx| {
20262            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20263                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20264                Some(this.selection_replacement_ranges(range_utf16, cx))
20265            } else {
20266                this.marked_text_ranges(cx)
20267            };
20268
20269            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20270                let newest_selection_id = this.selections.newest_anchor().id;
20271                this.selections
20272                    .all::<OffsetUtf16>(cx)
20273                    .iter()
20274                    .zip(ranges_to_replace.iter())
20275                    .find_map(|(selection, range)| {
20276                        if selection.id == newest_selection_id {
20277                            Some(
20278                                (range.start.0 as isize - selection.head().0 as isize)
20279                                    ..(range.end.0 as isize - selection.head().0 as isize),
20280                            )
20281                        } else {
20282                            None
20283                        }
20284                    })
20285            });
20286
20287            cx.emit(EditorEvent::InputHandled {
20288                utf16_range_to_replace: range_to_replace,
20289                text: text.into(),
20290            });
20291
20292            if let Some(new_selected_ranges) = new_selected_ranges {
20293                this.change_selections(None, window, cx, |selections| {
20294                    selections.select_ranges(new_selected_ranges)
20295                });
20296                this.backspace(&Default::default(), window, cx);
20297            }
20298
20299            this.handle_input(text, window, cx);
20300        });
20301
20302        if let Some(transaction) = self.ime_transaction {
20303            self.buffer.update(cx, |buffer, cx| {
20304                buffer.group_until_transaction(transaction, cx);
20305            });
20306        }
20307
20308        self.unmark_text(window, cx);
20309    }
20310
20311    fn replace_and_mark_text_in_range(
20312        &mut self,
20313        range_utf16: Option<Range<usize>>,
20314        text: &str,
20315        new_selected_range_utf16: Option<Range<usize>>,
20316        window: &mut Window,
20317        cx: &mut Context<Self>,
20318    ) {
20319        if !self.input_enabled {
20320            return;
20321        }
20322
20323        let transaction = self.transact(window, cx, |this, window, cx| {
20324            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20325                let snapshot = this.buffer.read(cx).read(cx);
20326                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20327                    for marked_range in &mut marked_ranges {
20328                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20329                        marked_range.start.0 += relative_range_utf16.start;
20330                        marked_range.start =
20331                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20332                        marked_range.end =
20333                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20334                    }
20335                }
20336                Some(marked_ranges)
20337            } else if let Some(range_utf16) = range_utf16 {
20338                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20339                Some(this.selection_replacement_ranges(range_utf16, cx))
20340            } else {
20341                None
20342            };
20343
20344            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20345                let newest_selection_id = this.selections.newest_anchor().id;
20346                this.selections
20347                    .all::<OffsetUtf16>(cx)
20348                    .iter()
20349                    .zip(ranges_to_replace.iter())
20350                    .find_map(|(selection, range)| {
20351                        if selection.id == newest_selection_id {
20352                            Some(
20353                                (range.start.0 as isize - selection.head().0 as isize)
20354                                    ..(range.end.0 as isize - selection.head().0 as isize),
20355                            )
20356                        } else {
20357                            None
20358                        }
20359                    })
20360            });
20361
20362            cx.emit(EditorEvent::InputHandled {
20363                utf16_range_to_replace: range_to_replace,
20364                text: text.into(),
20365            });
20366
20367            if let Some(ranges) = ranges_to_replace {
20368                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20369            }
20370
20371            let marked_ranges = {
20372                let snapshot = this.buffer.read(cx).read(cx);
20373                this.selections
20374                    .disjoint_anchors()
20375                    .iter()
20376                    .map(|selection| {
20377                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20378                    })
20379                    .collect::<Vec<_>>()
20380            };
20381
20382            if text.is_empty() {
20383                this.unmark_text(window, cx);
20384            } else {
20385                this.highlight_text::<InputComposition>(
20386                    marked_ranges.clone(),
20387                    HighlightStyle {
20388                        underline: Some(UnderlineStyle {
20389                            thickness: px(1.),
20390                            color: None,
20391                            wavy: false,
20392                        }),
20393                        ..Default::default()
20394                    },
20395                    cx,
20396                );
20397            }
20398
20399            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20400            let use_autoclose = this.use_autoclose;
20401            let use_auto_surround = this.use_auto_surround;
20402            this.set_use_autoclose(false);
20403            this.set_use_auto_surround(false);
20404            this.handle_input(text, window, cx);
20405            this.set_use_autoclose(use_autoclose);
20406            this.set_use_auto_surround(use_auto_surround);
20407
20408            if let Some(new_selected_range) = new_selected_range_utf16 {
20409                let snapshot = this.buffer.read(cx).read(cx);
20410                let new_selected_ranges = marked_ranges
20411                    .into_iter()
20412                    .map(|marked_range| {
20413                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20414                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20415                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20416                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20417                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20418                    })
20419                    .collect::<Vec<_>>();
20420
20421                drop(snapshot);
20422                this.change_selections(None, window, cx, |selections| {
20423                    selections.select_ranges(new_selected_ranges)
20424                });
20425            }
20426        });
20427
20428        self.ime_transaction = self.ime_transaction.or(transaction);
20429        if let Some(transaction) = self.ime_transaction {
20430            self.buffer.update(cx, |buffer, cx| {
20431                buffer.group_until_transaction(transaction, cx);
20432            });
20433        }
20434
20435        if self.text_highlights::<InputComposition>(cx).is_none() {
20436            self.ime_transaction.take();
20437        }
20438    }
20439
20440    fn bounds_for_range(
20441        &mut self,
20442        range_utf16: Range<usize>,
20443        element_bounds: gpui::Bounds<Pixels>,
20444        window: &mut Window,
20445        cx: &mut Context<Self>,
20446    ) -> Option<gpui::Bounds<Pixels>> {
20447        let text_layout_details = self.text_layout_details(window);
20448        let gpui::Size {
20449            width: em_width,
20450            height: line_height,
20451        } = self.character_size(window);
20452
20453        let snapshot = self.snapshot(window, cx);
20454        let scroll_position = snapshot.scroll_position();
20455        let scroll_left = scroll_position.x * em_width;
20456
20457        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20458        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20459            + self.gutter_dimensions.width
20460            + self.gutter_dimensions.margin;
20461        let y = line_height * (start.row().as_f32() - scroll_position.y);
20462
20463        Some(Bounds {
20464            origin: element_bounds.origin + point(x, y),
20465            size: size(em_width, line_height),
20466        })
20467    }
20468
20469    fn character_index_for_point(
20470        &mut self,
20471        point: gpui::Point<Pixels>,
20472        _window: &mut Window,
20473        _cx: &mut Context<Self>,
20474    ) -> Option<usize> {
20475        let position_map = self.last_position_map.as_ref()?;
20476        if !position_map.text_hitbox.contains(&point) {
20477            return None;
20478        }
20479        let display_point = position_map.point_for_position(point).previous_valid;
20480        let anchor = position_map
20481            .snapshot
20482            .display_point_to_anchor(display_point, Bias::Left);
20483        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20484        Some(utf16_offset.0)
20485    }
20486}
20487
20488trait SelectionExt {
20489    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20490    fn spanned_rows(
20491        &self,
20492        include_end_if_at_line_start: bool,
20493        map: &DisplaySnapshot,
20494    ) -> Range<MultiBufferRow>;
20495}
20496
20497impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20498    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20499        let start = self
20500            .start
20501            .to_point(&map.buffer_snapshot)
20502            .to_display_point(map);
20503        let end = self
20504            .end
20505            .to_point(&map.buffer_snapshot)
20506            .to_display_point(map);
20507        if self.reversed {
20508            end..start
20509        } else {
20510            start..end
20511        }
20512    }
20513
20514    fn spanned_rows(
20515        &self,
20516        include_end_if_at_line_start: bool,
20517        map: &DisplaySnapshot,
20518    ) -> Range<MultiBufferRow> {
20519        let start = self.start.to_point(&map.buffer_snapshot);
20520        let mut end = self.end.to_point(&map.buffer_snapshot);
20521        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20522            end.row -= 1;
20523        }
20524
20525        let buffer_start = map.prev_line_boundary(start).0;
20526        let buffer_end = map.next_line_boundary(end).0;
20527        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20528    }
20529}
20530
20531impl<T: InvalidationRegion> InvalidationStack<T> {
20532    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20533    where
20534        S: Clone + ToOffset,
20535    {
20536        while let Some(region) = self.last() {
20537            let all_selections_inside_invalidation_ranges =
20538                if selections.len() == region.ranges().len() {
20539                    selections
20540                        .iter()
20541                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20542                        .all(|(selection, invalidation_range)| {
20543                            let head = selection.head().to_offset(buffer);
20544                            invalidation_range.start <= head && invalidation_range.end >= head
20545                        })
20546                } else {
20547                    false
20548                };
20549
20550            if all_selections_inside_invalidation_ranges {
20551                break;
20552            } else {
20553                self.pop();
20554            }
20555        }
20556    }
20557}
20558
20559impl<T> Default for InvalidationStack<T> {
20560    fn default() -> Self {
20561        Self(Default::default())
20562    }
20563}
20564
20565impl<T> Deref for InvalidationStack<T> {
20566    type Target = Vec<T>;
20567
20568    fn deref(&self) -> &Self::Target {
20569        &self.0
20570    }
20571}
20572
20573impl<T> DerefMut for InvalidationStack<T> {
20574    fn deref_mut(&mut self) -> &mut Self::Target {
20575        &mut self.0
20576    }
20577}
20578
20579impl InvalidationRegion for SnippetState {
20580    fn ranges(&self) -> &[Range<Anchor>] {
20581        &self.ranges[self.active_index]
20582    }
20583}
20584
20585fn inline_completion_edit_text(
20586    current_snapshot: &BufferSnapshot,
20587    edits: &[(Range<Anchor>, String)],
20588    edit_preview: &EditPreview,
20589    include_deletions: bool,
20590    cx: &App,
20591) -> HighlightedText {
20592    let edits = edits
20593        .iter()
20594        .map(|(anchor, text)| {
20595            (
20596                anchor.start.text_anchor..anchor.end.text_anchor,
20597                text.clone(),
20598            )
20599        })
20600        .collect::<Vec<_>>();
20601
20602    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20603}
20604
20605pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20606    match severity {
20607        DiagnosticSeverity::ERROR => colors.error,
20608        DiagnosticSeverity::WARNING => colors.warning,
20609        DiagnosticSeverity::INFORMATION => colors.info,
20610        DiagnosticSeverity::HINT => colors.info,
20611        _ => colors.ignored,
20612    }
20613}
20614
20615pub fn styled_runs_for_code_label<'a>(
20616    label: &'a CodeLabel,
20617    syntax_theme: &'a theme::SyntaxTheme,
20618) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20619    let fade_out = HighlightStyle {
20620        fade_out: Some(0.35),
20621        ..Default::default()
20622    };
20623
20624    let mut prev_end = label.filter_range.end;
20625    label
20626        .runs
20627        .iter()
20628        .enumerate()
20629        .flat_map(move |(ix, (range, highlight_id))| {
20630            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20631                style
20632            } else {
20633                return Default::default();
20634            };
20635            let mut muted_style = style;
20636            muted_style.highlight(fade_out);
20637
20638            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20639            if range.start >= label.filter_range.end {
20640                if range.start > prev_end {
20641                    runs.push((prev_end..range.start, fade_out));
20642                }
20643                runs.push((range.clone(), muted_style));
20644            } else if range.end <= label.filter_range.end {
20645                runs.push((range.clone(), style));
20646            } else {
20647                runs.push((range.start..label.filter_range.end, style));
20648                runs.push((label.filter_range.end..range.end, muted_style));
20649            }
20650            prev_end = cmp::max(prev_end, range.end);
20651
20652            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20653                runs.push((prev_end..label.text.len(), fade_out));
20654            }
20655
20656            runs
20657        })
20658}
20659
20660pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20661    let mut prev_index = 0;
20662    let mut prev_codepoint: Option<char> = None;
20663    text.char_indices()
20664        .chain([(text.len(), '\0')])
20665        .filter_map(move |(index, codepoint)| {
20666            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20667            let is_boundary = index == text.len()
20668                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20669                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20670            if is_boundary {
20671                let chunk = &text[prev_index..index];
20672                prev_index = index;
20673                Some(chunk)
20674            } else {
20675                None
20676            }
20677        })
20678}
20679
20680pub trait RangeToAnchorExt: Sized {
20681    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20682
20683    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20684        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20685        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20686    }
20687}
20688
20689impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20690    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20691        let start_offset = self.start.to_offset(snapshot);
20692        let end_offset = self.end.to_offset(snapshot);
20693        if start_offset == end_offset {
20694            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20695        } else {
20696            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20697        }
20698    }
20699}
20700
20701pub trait RowExt {
20702    fn as_f32(&self) -> f32;
20703
20704    fn next_row(&self) -> Self;
20705
20706    fn previous_row(&self) -> Self;
20707
20708    fn minus(&self, other: Self) -> u32;
20709}
20710
20711impl RowExt for DisplayRow {
20712    fn as_f32(&self) -> f32 {
20713        self.0 as f32
20714    }
20715
20716    fn next_row(&self) -> Self {
20717        Self(self.0 + 1)
20718    }
20719
20720    fn previous_row(&self) -> Self {
20721        Self(self.0.saturating_sub(1))
20722    }
20723
20724    fn minus(&self, other: Self) -> u32 {
20725        self.0 - other.0
20726    }
20727}
20728
20729impl RowExt for MultiBufferRow {
20730    fn as_f32(&self) -> f32 {
20731        self.0 as f32
20732    }
20733
20734    fn next_row(&self) -> Self {
20735        Self(self.0 + 1)
20736    }
20737
20738    fn previous_row(&self) -> Self {
20739        Self(self.0.saturating_sub(1))
20740    }
20741
20742    fn minus(&self, other: Self) -> u32 {
20743        self.0 - other.0
20744    }
20745}
20746
20747trait RowRangeExt {
20748    type Row;
20749
20750    fn len(&self) -> usize;
20751
20752    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20753}
20754
20755impl RowRangeExt for Range<MultiBufferRow> {
20756    type Row = MultiBufferRow;
20757
20758    fn len(&self) -> usize {
20759        (self.end.0 - self.start.0) as usize
20760    }
20761
20762    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20763        (self.start.0..self.end.0).map(MultiBufferRow)
20764    }
20765}
20766
20767impl RowRangeExt for Range<DisplayRow> {
20768    type Row = DisplayRow;
20769
20770    fn len(&self) -> usize {
20771        (self.end.0 - self.start.0) as usize
20772    }
20773
20774    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20775        (self.start.0..self.end.0).map(DisplayRow)
20776    }
20777}
20778
20779/// If select range has more than one line, we
20780/// just point the cursor to range.start.
20781fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20782    if range.start.row == range.end.row {
20783        range
20784    } else {
20785        range.start..range.start
20786    }
20787}
20788pub struct KillRing(ClipboardItem);
20789impl Global for KillRing {}
20790
20791const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20792
20793enum BreakpointPromptEditAction {
20794    Log,
20795    Condition,
20796    HitCondition,
20797}
20798
20799struct BreakpointPromptEditor {
20800    pub(crate) prompt: Entity<Editor>,
20801    editor: WeakEntity<Editor>,
20802    breakpoint_anchor: Anchor,
20803    breakpoint: Breakpoint,
20804    edit_action: BreakpointPromptEditAction,
20805    block_ids: HashSet<CustomBlockId>,
20806    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20807    _subscriptions: Vec<Subscription>,
20808}
20809
20810impl BreakpointPromptEditor {
20811    const MAX_LINES: u8 = 4;
20812
20813    fn new(
20814        editor: WeakEntity<Editor>,
20815        breakpoint_anchor: Anchor,
20816        breakpoint: Breakpoint,
20817        edit_action: BreakpointPromptEditAction,
20818        window: &mut Window,
20819        cx: &mut Context<Self>,
20820    ) -> Self {
20821        let base_text = match edit_action {
20822            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20823            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20824            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20825        }
20826        .map(|msg| msg.to_string())
20827        .unwrap_or_default();
20828
20829        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20830        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20831
20832        let prompt = cx.new(|cx| {
20833            let mut prompt = Editor::new(
20834                EditorMode::AutoHeight {
20835                    max_lines: Self::MAX_LINES as usize,
20836                },
20837                buffer,
20838                None,
20839                window,
20840                cx,
20841            );
20842            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20843            prompt.set_show_cursor_when_unfocused(false, cx);
20844            prompt.set_placeholder_text(
20845                match edit_action {
20846                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20847                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20848                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20849                },
20850                cx,
20851            );
20852
20853            prompt
20854        });
20855
20856        Self {
20857            prompt,
20858            editor,
20859            breakpoint_anchor,
20860            breakpoint,
20861            edit_action,
20862            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20863            block_ids: Default::default(),
20864            _subscriptions: vec![],
20865        }
20866    }
20867
20868    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20869        self.block_ids.extend(block_ids)
20870    }
20871
20872    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20873        if let Some(editor) = self.editor.upgrade() {
20874            let message = self
20875                .prompt
20876                .read(cx)
20877                .buffer
20878                .read(cx)
20879                .as_singleton()
20880                .expect("A multi buffer in breakpoint prompt isn't possible")
20881                .read(cx)
20882                .as_rope()
20883                .to_string();
20884
20885            editor.update(cx, |editor, cx| {
20886                editor.edit_breakpoint_at_anchor(
20887                    self.breakpoint_anchor,
20888                    self.breakpoint.clone(),
20889                    match self.edit_action {
20890                        BreakpointPromptEditAction::Log => {
20891                            BreakpointEditAction::EditLogMessage(message.into())
20892                        }
20893                        BreakpointPromptEditAction::Condition => {
20894                            BreakpointEditAction::EditCondition(message.into())
20895                        }
20896                        BreakpointPromptEditAction::HitCondition => {
20897                            BreakpointEditAction::EditHitCondition(message.into())
20898                        }
20899                    },
20900                    cx,
20901                );
20902
20903                editor.remove_blocks(self.block_ids.clone(), None, cx);
20904                cx.focus_self(window);
20905            });
20906        }
20907    }
20908
20909    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20910        self.editor
20911            .update(cx, |editor, cx| {
20912                editor.remove_blocks(self.block_ids.clone(), None, cx);
20913                window.focus(&editor.focus_handle);
20914            })
20915            .log_err();
20916    }
20917
20918    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20919        let settings = ThemeSettings::get_global(cx);
20920        let text_style = TextStyle {
20921            color: if self.prompt.read(cx).read_only(cx) {
20922                cx.theme().colors().text_disabled
20923            } else {
20924                cx.theme().colors().text
20925            },
20926            font_family: settings.buffer_font.family.clone(),
20927            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20928            font_size: settings.buffer_font_size(cx).into(),
20929            font_weight: settings.buffer_font.weight,
20930            line_height: relative(settings.buffer_line_height.value()),
20931            ..Default::default()
20932        };
20933        EditorElement::new(
20934            &self.prompt,
20935            EditorStyle {
20936                background: cx.theme().colors().editor_background,
20937                local_player: cx.theme().players().local(),
20938                text: text_style,
20939                ..Default::default()
20940            },
20941        )
20942    }
20943}
20944
20945impl Render for BreakpointPromptEditor {
20946    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20947        let gutter_dimensions = *self.gutter_dimensions.lock();
20948        h_flex()
20949            .key_context("Editor")
20950            .bg(cx.theme().colors().editor_background)
20951            .border_y_1()
20952            .border_color(cx.theme().status().info_border)
20953            .size_full()
20954            .py(window.line_height() / 2.5)
20955            .on_action(cx.listener(Self::confirm))
20956            .on_action(cx.listener(Self::cancel))
20957            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20958            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20959    }
20960}
20961
20962impl Focusable for BreakpointPromptEditor {
20963    fn focus_handle(&self, cx: &App) -> FocusHandle {
20964        self.prompt.focus_handle(cx)
20965    }
20966}
20967
20968fn all_edits_insertions_or_deletions(
20969    edits: &Vec<(Range<Anchor>, String)>,
20970    snapshot: &MultiBufferSnapshot,
20971) -> bool {
20972    let mut all_insertions = true;
20973    let mut all_deletions = true;
20974
20975    for (range, new_text) in edits.iter() {
20976        let range_is_empty = range.to_offset(&snapshot).is_empty();
20977        let text_is_empty = new_text.is_empty();
20978
20979        if range_is_empty != text_is_empty {
20980            if range_is_empty {
20981                all_deletions = false;
20982            } else {
20983                all_insertions = false;
20984            }
20985        } else {
20986            return false;
20987        }
20988
20989        if !all_insertions && !all_deletions {
20990            return false;
20991        }
20992    }
20993    all_insertions || all_deletions
20994}
20995
20996struct MissingEditPredictionKeybindingTooltip;
20997
20998impl Render for MissingEditPredictionKeybindingTooltip {
20999    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21000        ui::tooltip_container(window, cx, |container, _, cx| {
21001            container
21002                .flex_shrink_0()
21003                .max_w_80()
21004                .min_h(rems_from_px(124.))
21005                .justify_between()
21006                .child(
21007                    v_flex()
21008                        .flex_1()
21009                        .text_ui_sm(cx)
21010                        .child(Label::new("Conflict with Accept Keybinding"))
21011                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21012                )
21013                .child(
21014                    h_flex()
21015                        .pb_1()
21016                        .gap_1()
21017                        .items_end()
21018                        .w_full()
21019                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21020                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21021                        }))
21022                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21023                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21024                        })),
21025                )
21026        })
21027    }
21028}
21029
21030#[derive(Debug, Clone, Copy, PartialEq)]
21031pub struct LineHighlight {
21032    pub background: Background,
21033    pub border: Option<gpui::Hsla>,
21034    pub include_gutter: bool,
21035    pub type_id: Option<TypeId>,
21036}
21037
21038fn render_diff_hunk_controls(
21039    row: u32,
21040    status: &DiffHunkStatus,
21041    hunk_range: Range<Anchor>,
21042    is_created_file: bool,
21043    line_height: Pixels,
21044    editor: &Entity<Editor>,
21045    _window: &mut Window,
21046    cx: &mut App,
21047) -> AnyElement {
21048    h_flex()
21049        .h(line_height)
21050        .mr_1()
21051        .gap_1()
21052        .px_0p5()
21053        .pb_1()
21054        .border_x_1()
21055        .border_b_1()
21056        .border_color(cx.theme().colors().border_variant)
21057        .rounded_b_lg()
21058        .bg(cx.theme().colors().editor_background)
21059        .gap_1()
21060        .occlude()
21061        .shadow_md()
21062        .child(if status.has_secondary_hunk() {
21063            Button::new(("stage", row as u64), "Stage")
21064                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21065                .tooltip({
21066                    let focus_handle = editor.focus_handle(cx);
21067                    move |window, cx| {
21068                        Tooltip::for_action_in(
21069                            "Stage Hunk",
21070                            &::git::ToggleStaged,
21071                            &focus_handle,
21072                            window,
21073                            cx,
21074                        )
21075                    }
21076                })
21077                .on_click({
21078                    let editor = editor.clone();
21079                    move |_event, _window, cx| {
21080                        editor.update(cx, |editor, cx| {
21081                            editor.stage_or_unstage_diff_hunks(
21082                                true,
21083                                vec![hunk_range.start..hunk_range.start],
21084                                cx,
21085                            );
21086                        });
21087                    }
21088                })
21089        } else {
21090            Button::new(("unstage", row as u64), "Unstage")
21091                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21092                .tooltip({
21093                    let focus_handle = editor.focus_handle(cx);
21094                    move |window, cx| {
21095                        Tooltip::for_action_in(
21096                            "Unstage Hunk",
21097                            &::git::ToggleStaged,
21098                            &focus_handle,
21099                            window,
21100                            cx,
21101                        )
21102                    }
21103                })
21104                .on_click({
21105                    let editor = editor.clone();
21106                    move |_event, _window, cx| {
21107                        editor.update(cx, |editor, cx| {
21108                            editor.stage_or_unstage_diff_hunks(
21109                                false,
21110                                vec![hunk_range.start..hunk_range.start],
21111                                cx,
21112                            );
21113                        });
21114                    }
21115                })
21116        })
21117        .child(
21118            Button::new(("restore", row as u64), "Restore")
21119                .tooltip({
21120                    let focus_handle = editor.focus_handle(cx);
21121                    move |window, cx| {
21122                        Tooltip::for_action_in(
21123                            "Restore Hunk",
21124                            &::git::Restore,
21125                            &focus_handle,
21126                            window,
21127                            cx,
21128                        )
21129                    }
21130                })
21131                .on_click({
21132                    let editor = editor.clone();
21133                    move |_event, window, cx| {
21134                        editor.update(cx, |editor, cx| {
21135                            let snapshot = editor.snapshot(window, cx);
21136                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21137                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21138                        });
21139                    }
21140                })
21141                .disabled(is_created_file),
21142        )
21143        .when(
21144            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21145            |el| {
21146                el.child(
21147                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21148                        .shape(IconButtonShape::Square)
21149                        .icon_size(IconSize::Small)
21150                        // .disabled(!has_multiple_hunks)
21151                        .tooltip({
21152                            let focus_handle = editor.focus_handle(cx);
21153                            move |window, cx| {
21154                                Tooltip::for_action_in(
21155                                    "Next Hunk",
21156                                    &GoToHunk,
21157                                    &focus_handle,
21158                                    window,
21159                                    cx,
21160                                )
21161                            }
21162                        })
21163                        .on_click({
21164                            let editor = editor.clone();
21165                            move |_event, window, cx| {
21166                                editor.update(cx, |editor, cx| {
21167                                    let snapshot = editor.snapshot(window, cx);
21168                                    let position =
21169                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21170                                    editor.go_to_hunk_before_or_after_position(
21171                                        &snapshot,
21172                                        position,
21173                                        Direction::Next,
21174                                        window,
21175                                        cx,
21176                                    );
21177                                    editor.expand_selected_diff_hunks(cx);
21178                                });
21179                            }
21180                        }),
21181                )
21182                .child(
21183                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21184                        .shape(IconButtonShape::Square)
21185                        .icon_size(IconSize::Small)
21186                        // .disabled(!has_multiple_hunks)
21187                        .tooltip({
21188                            let focus_handle = editor.focus_handle(cx);
21189                            move |window, cx| {
21190                                Tooltip::for_action_in(
21191                                    "Previous Hunk",
21192                                    &GoToPreviousHunk,
21193                                    &focus_handle,
21194                                    window,
21195                                    cx,
21196                                )
21197                            }
21198                        })
21199                        .on_click({
21200                            let editor = editor.clone();
21201                            move |_event, window, cx| {
21202                                editor.update(cx, |editor, cx| {
21203                                    let snapshot = editor.snapshot(window, cx);
21204                                    let point =
21205                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21206                                    editor.go_to_hunk_before_or_after_position(
21207                                        &snapshot,
21208                                        point,
21209                                        Direction::Prev,
21210                                        window,
21211                                        cx,
21212                                    );
21213                                    editor.expand_selected_diff_hunks(cx);
21214                                });
21215                            }
21216                        }),
21217                )
21218            },
21219        )
21220        .into_any_element()
21221}