editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64pub use editor_settings::{
   65    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   66    ShowScrollbar,
   67};
   68use editor_settings::{GoToDefinitionFallback, Minimap as MinimapSettings};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132    project_settings::DiagnosticSeverity,
  133};
  134
  135pub use git::blame::BlameRenderer;
  136pub use proposed_changes_editor::{
  137    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  138};
  139use smallvec::smallvec;
  140use std::{cell::OnceCell, iter::Peekable, ops::Not};
  141use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  142
  143pub use lsp::CompletionContext;
  144use lsp::{
  145    CodeActionKind, CompletionItemKind, CompletionTriggerKind, InsertTextFormat, InsertTextMode,
  146    LanguageServerId, LanguageServerName,
  147};
  148
  149use language::BufferSnapshot;
  150pub use lsp_ext::lsp_tasks;
  151use movement::TextLayoutDetails;
  152pub use multi_buffer::{
  153    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  154    RowInfo, ToOffset, ToPoint,
  155};
  156use multi_buffer::{
  157    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  158    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  159};
  160use parking_lot::Mutex;
  161use project::{
  162    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  163    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  164    TaskSourceKind,
  165    debugger::breakpoint_store::Breakpoint,
  166    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  167    project_settings::{GitGutterSetting, ProjectSettings},
  168};
  169use rand::prelude::*;
  170use rpc::{ErrorExt, proto::*};
  171use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  172use selections_collection::{
  173    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  174};
  175use serde::{Deserialize, Serialize};
  176use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  177use smallvec::SmallVec;
  178use snippet::Snippet;
  179use std::sync::Arc;
  180use std::{
  181    any::TypeId,
  182    borrow::Cow,
  183    cell::RefCell,
  184    cmp::{self, Ordering, Reverse},
  185    mem,
  186    num::NonZeroU32,
  187    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  188    path::{Path, PathBuf},
  189    rc::Rc,
  190    time::{Duration, Instant},
  191};
  192pub use sum_tree::Bias;
  193use sum_tree::TreeMap;
  194use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  195use theme::{
  196    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  197    observe_buffer_font_size_adjustment,
  198};
  199use ui::{
  200    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  201    IconSize, Key, Tooltip, h_flex, prelude::*,
  202};
  203use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  204use workspace::{
  205    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  206    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  207    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  208    item::{ItemHandle, PreviewTabsSettings},
  209    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  210    searchable::SearchEvent,
  211};
  212
  213use crate::hover_links::{find_url, find_url_from_range};
  214use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  215
  216pub const FILE_HEADER_HEIGHT: u32 = 2;
  217pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  218pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  219const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  220const MAX_LINE_LEN: usize = 1024;
  221const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  222const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  223pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  224#[doc(hidden)]
  225pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  226const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  227
  228pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  230pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  231
  232pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  233pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  234pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  235pub(crate) const MINIMAP_FONT_SIZE: AbsoluteLength = AbsoluteLength::Pixels(px(2.));
  236
  237pub type RenderDiffHunkControlsFn = Arc<
  238    dyn Fn(
  239        u32,
  240        &DiffHunkStatus,
  241        Range<Anchor>,
  242        bool,
  243        Pixels,
  244        &Entity<Editor>,
  245        &mut Window,
  246        &mut App,
  247    ) -> AnyElement,
  248>;
  249
  250const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  251    alt: true,
  252    shift: true,
  253    control: false,
  254    platform: false,
  255    function: false,
  256};
  257
  258struct InlineValueCache {
  259    enabled: bool,
  260    inlays: Vec<InlayId>,
  261    refresh_task: Task<Option<()>>,
  262}
  263
  264impl InlineValueCache {
  265    fn new(enabled: bool) -> Self {
  266        Self {
  267            enabled,
  268            inlays: Vec::new(),
  269            refresh_task: Task::ready(None),
  270        }
  271    }
  272}
  273
  274#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  275pub enum InlayId {
  276    InlineCompletion(usize),
  277    Hint(usize),
  278    DebuggerValue(usize),
  279}
  280
  281impl InlayId {
  282    fn id(&self) -> usize {
  283        match self {
  284            Self::InlineCompletion(id) => *id,
  285            Self::Hint(id) => *id,
  286            Self::DebuggerValue(id) => *id,
  287        }
  288    }
  289}
  290
  291pub enum ActiveDebugLine {}
  292enum DocumentHighlightRead {}
  293enum DocumentHighlightWrite {}
  294enum InputComposition {}
  295enum SelectedTextHighlight {}
  296
  297pub enum ConflictsOuter {}
  298pub enum ConflictsOurs {}
  299pub enum ConflictsTheirs {}
  300pub enum ConflictsOursMarker {}
  301pub enum ConflictsTheirsMarker {}
  302
  303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  304pub enum Navigated {
  305    Yes,
  306    No,
  307}
  308
  309impl Navigated {
  310    pub fn from_bool(yes: bool) -> Navigated {
  311        if yes { Navigated::Yes } else { Navigated::No }
  312    }
  313}
  314
  315#[derive(Debug, Clone, PartialEq, Eq)]
  316enum DisplayDiffHunk {
  317    Folded {
  318        display_row: DisplayRow,
  319    },
  320    Unfolded {
  321        is_created_file: bool,
  322        diff_base_byte_range: Range<usize>,
  323        display_row_range: Range<DisplayRow>,
  324        multi_buffer_range: Range<Anchor>,
  325        status: DiffHunkStatus,
  326    },
  327}
  328
  329pub enum HideMouseCursorOrigin {
  330    TypingAction,
  331    MovementAction,
  332}
  333
  334pub fn init_settings(cx: &mut App) {
  335    EditorSettings::register(cx);
  336}
  337
  338pub fn init(cx: &mut App) {
  339    init_settings(cx);
  340
  341    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  342
  343    workspace::register_project_item::<Editor>(cx);
  344    workspace::FollowableViewRegistry::register::<Editor>(cx);
  345    workspace::register_serializable_item::<Editor>(cx);
  346
  347    cx.observe_new(
  348        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  349            workspace.register_action(Editor::new_file);
  350            workspace.register_action(Editor::new_file_vertical);
  351            workspace.register_action(Editor::new_file_horizontal);
  352            workspace.register_action(Editor::cancel_language_server_work);
  353        },
  354    )
  355    .detach();
  356
  357    cx.on_action(move |_: &workspace::NewFile, cx| {
  358        let app_state = workspace::AppState::global(cx);
  359        if let Some(app_state) = app_state.upgrade() {
  360            workspace::open_new(
  361                Default::default(),
  362                app_state,
  363                cx,
  364                |workspace, window, cx| {
  365                    Editor::new_file(workspace, &Default::default(), window, cx)
  366                },
  367            )
  368            .detach();
  369        }
  370    });
  371    cx.on_action(move |_: &workspace::NewWindow, cx| {
  372        let app_state = workspace::AppState::global(cx);
  373        if let Some(app_state) = app_state.upgrade() {
  374            workspace::open_new(
  375                Default::default(),
  376                app_state,
  377                cx,
  378                |workspace, window, cx| {
  379                    cx.activate(true);
  380                    Editor::new_file(workspace, &Default::default(), window, cx)
  381                },
  382            )
  383            .detach();
  384        }
  385    });
  386}
  387
  388pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  389    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  390}
  391
  392pub trait DiagnosticRenderer {
  393    fn render_group(
  394        &self,
  395        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  396        buffer_id: BufferId,
  397        snapshot: EditorSnapshot,
  398        editor: WeakEntity<Editor>,
  399        cx: &mut App,
  400    ) -> Vec<BlockProperties<Anchor>>;
  401
  402    fn render_hover(
  403        &self,
  404        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  405        range: Range<Point>,
  406        buffer_id: BufferId,
  407        cx: &mut App,
  408    ) -> Option<Entity<markdown::Markdown>>;
  409
  410    fn open_link(
  411        &self,
  412        editor: &mut Editor,
  413        link: SharedString,
  414        window: &mut Window,
  415        cx: &mut Context<Editor>,
  416    );
  417}
  418
  419pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  420
  421impl GlobalDiagnosticRenderer {
  422    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  423        cx.try_global::<Self>().map(|g| g.0.clone())
  424    }
  425}
  426
  427impl gpui::Global for GlobalDiagnosticRenderer {}
  428pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  429    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  430}
  431
  432pub struct SearchWithinRange;
  433
  434trait InvalidationRegion {
  435    fn ranges(&self) -> &[Range<Anchor>];
  436}
  437
  438#[derive(Clone, Debug, PartialEq)]
  439pub enum SelectPhase {
  440    Begin {
  441        position: DisplayPoint,
  442        add: bool,
  443        click_count: usize,
  444    },
  445    BeginColumnar {
  446        position: DisplayPoint,
  447        reset: bool,
  448        goal_column: u32,
  449    },
  450    Extend {
  451        position: DisplayPoint,
  452        click_count: usize,
  453    },
  454    Update {
  455        position: DisplayPoint,
  456        goal_column: u32,
  457        scroll_delta: gpui::Point<f32>,
  458    },
  459    End,
  460}
  461
  462#[derive(Clone, Debug)]
  463pub enum SelectMode {
  464    Character,
  465    Word(Range<Anchor>),
  466    Line(Range<Anchor>),
  467    All,
  468}
  469
  470#[derive(Clone, PartialEq, Eq, Debug)]
  471pub enum EditorMode {
  472    SingleLine {
  473        auto_width: bool,
  474    },
  475    AutoHeight {
  476        max_lines: usize,
  477    },
  478    Full {
  479        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  480        scale_ui_elements_with_buffer_font_size: bool,
  481        /// When set to `true`, the editor will render a background for the active line.
  482        show_active_line_background: bool,
  483        /// When set to `true`, the editor's height will be determined by its content.
  484        sized_by_content: bool,
  485    },
  486    Minimap {
  487        parent: WeakEntity<Editor>,
  488    },
  489}
  490
  491impl EditorMode {
  492    pub fn full() -> Self {
  493        Self::Full {
  494            scale_ui_elements_with_buffer_font_size: true,
  495            show_active_line_background: true,
  496            sized_by_content: false,
  497        }
  498    }
  499
  500    pub fn is_full(&self) -> bool {
  501        matches!(self, Self::Full { .. })
  502    }
  503
  504    fn is_minimap(&self) -> bool {
  505        matches!(self, Self::Minimap { .. })
  506    }
  507}
  508
  509#[derive(Copy, Clone, Debug)]
  510pub enum SoftWrap {
  511    /// Prefer not to wrap at all.
  512    ///
  513    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  514    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  515    GitDiff,
  516    /// Prefer a single line generally, unless an overly long line is encountered.
  517    None,
  518    /// Soft wrap lines that exceed the editor width.
  519    EditorWidth,
  520    /// Soft wrap lines at the preferred line length.
  521    Column(u32),
  522    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  523    Bounded(u32),
  524}
  525
  526#[derive(Clone)]
  527pub struct EditorStyle {
  528    pub background: Hsla,
  529    pub local_player: PlayerColor,
  530    pub text: TextStyle,
  531    pub scrollbar_width: Pixels,
  532    pub syntax: Arc<SyntaxTheme>,
  533    pub status: StatusColors,
  534    pub inlay_hints_style: HighlightStyle,
  535    pub inline_completion_styles: InlineCompletionStyles,
  536    pub unnecessary_code_fade: f32,
  537    pub show_underlines: bool,
  538}
  539
  540impl Default for EditorStyle {
  541    fn default() -> Self {
  542        Self {
  543            background: Hsla::default(),
  544            local_player: PlayerColor::default(),
  545            text: TextStyle::default(),
  546            scrollbar_width: Pixels::default(),
  547            syntax: Default::default(),
  548            // HACK: Status colors don't have a real default.
  549            // We should look into removing the status colors from the editor
  550            // style and retrieve them directly from the theme.
  551            status: StatusColors::dark(),
  552            inlay_hints_style: HighlightStyle::default(),
  553            inline_completion_styles: InlineCompletionStyles {
  554                insertion: HighlightStyle::default(),
  555                whitespace: HighlightStyle::default(),
  556            },
  557            unnecessary_code_fade: Default::default(),
  558            show_underlines: true,
  559        }
  560    }
  561}
  562
  563pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  564    let show_background = language_settings::language_settings(None, None, cx)
  565        .inlay_hints
  566        .show_background;
  567
  568    HighlightStyle {
  569        color: Some(cx.theme().status().hint),
  570        background_color: show_background.then(|| cx.theme().status().hint_background),
  571        ..HighlightStyle::default()
  572    }
  573}
  574
  575pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  576    InlineCompletionStyles {
  577        insertion: HighlightStyle {
  578            color: Some(cx.theme().status().predictive),
  579            ..HighlightStyle::default()
  580        },
  581        whitespace: HighlightStyle {
  582            background_color: Some(cx.theme().status().created_background),
  583            ..HighlightStyle::default()
  584        },
  585    }
  586}
  587
  588type CompletionId = usize;
  589
  590pub(crate) enum EditDisplayMode {
  591    TabAccept,
  592    DiffPopover,
  593    Inline,
  594}
  595
  596enum InlineCompletion {
  597    Edit {
  598        edits: Vec<(Range<Anchor>, String)>,
  599        edit_preview: Option<EditPreview>,
  600        display_mode: EditDisplayMode,
  601        snapshot: BufferSnapshot,
  602    },
  603    Move {
  604        target: Anchor,
  605        snapshot: BufferSnapshot,
  606    },
  607}
  608
  609struct InlineCompletionState {
  610    inlay_ids: Vec<InlayId>,
  611    completion: InlineCompletion,
  612    completion_id: Option<SharedString>,
  613    invalidation_range: Range<Anchor>,
  614}
  615
  616enum EditPredictionSettings {
  617    Disabled,
  618    Enabled {
  619        show_in_menu: bool,
  620        preview_requires_modifier: bool,
  621    },
  622}
  623
  624enum InlineCompletionHighlight {}
  625
  626#[derive(Debug, Clone)]
  627struct InlineDiagnostic {
  628    message: SharedString,
  629    group_id: usize,
  630    is_primary: bool,
  631    start: Point,
  632    severity: lsp::DiagnosticSeverity,
  633}
  634
  635pub enum MenuInlineCompletionsPolicy {
  636    Never,
  637    ByProvider,
  638}
  639
  640pub enum EditPredictionPreview {
  641    /// Modifier is not pressed
  642    Inactive { released_too_fast: bool },
  643    /// Modifier pressed
  644    Active {
  645        since: Instant,
  646        previous_scroll_position: Option<ScrollAnchor>,
  647    },
  648}
  649
  650impl EditPredictionPreview {
  651    pub fn released_too_fast(&self) -> bool {
  652        match self {
  653            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  654            EditPredictionPreview::Active { .. } => false,
  655        }
  656    }
  657
  658    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  659        if let EditPredictionPreview::Active {
  660            previous_scroll_position,
  661            ..
  662        } = self
  663        {
  664            *previous_scroll_position = scroll_position;
  665        }
  666    }
  667}
  668
  669pub struct ContextMenuOptions {
  670    pub min_entries_visible: usize,
  671    pub max_entries_visible: usize,
  672    pub placement: Option<ContextMenuPlacement>,
  673}
  674
  675#[derive(Debug, Clone, PartialEq, Eq)]
  676pub enum ContextMenuPlacement {
  677    Above,
  678    Below,
  679}
  680
  681#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  682struct EditorActionId(usize);
  683
  684impl EditorActionId {
  685    pub fn post_inc(&mut self) -> Self {
  686        let answer = self.0;
  687
  688        *self = Self(answer + 1);
  689
  690        Self(answer)
  691    }
  692}
  693
  694// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  695// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  696
  697type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  698type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  699
  700#[derive(Default)]
  701struct ScrollbarMarkerState {
  702    scrollbar_size: Size<Pixels>,
  703    dirty: bool,
  704    markers: Arc<[PaintQuad]>,
  705    pending_refresh: Option<Task<Result<()>>>,
  706}
  707
  708impl ScrollbarMarkerState {
  709    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  710        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  711    }
  712}
  713
  714#[derive(Clone, Copy, PartialEq, Eq)]
  715pub enum MinimapVisibility {
  716    Disabled,
  717    Enabled(bool),
  718}
  719
  720impl MinimapVisibility {
  721    fn for_mode(mode: &EditorMode, cx: &App) -> Self {
  722        if mode.is_full() {
  723            Self::Enabled(EditorSettings::get_global(cx).minimap.minimap_enabled())
  724        } else {
  725            Self::Disabled
  726        }
  727    }
  728
  729    fn disabled(&self) -> bool {
  730        match *self {
  731            Self::Disabled => true,
  732            _ => false,
  733        }
  734    }
  735
  736    fn visible(&self) -> bool {
  737        match *self {
  738            Self::Enabled(visible) => visible,
  739            _ => false,
  740        }
  741    }
  742
  743    fn toggle_visibility(&self) -> Self {
  744        match *self {
  745            Self::Enabled(visible) => Self::Enabled(!visible),
  746            Self::Disabled => Self::Disabled,
  747        }
  748    }
  749}
  750
  751#[derive(Clone, Debug)]
  752struct RunnableTasks {
  753    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  754    offset: multi_buffer::Anchor,
  755    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  756    column: u32,
  757    // Values of all named captures, including those starting with '_'
  758    extra_variables: HashMap<String, String>,
  759    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  760    context_range: Range<BufferOffset>,
  761}
  762
  763impl RunnableTasks {
  764    fn resolve<'a>(
  765        &'a self,
  766        cx: &'a task::TaskContext,
  767    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  768        self.templates.iter().filter_map(|(kind, template)| {
  769            template
  770                .resolve_task(&kind.to_id_base(), cx)
  771                .map(|task| (kind.clone(), task))
  772        })
  773    }
  774}
  775
  776#[derive(Clone)]
  777struct ResolvedTasks {
  778    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  779    position: Anchor,
  780}
  781
  782#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  783struct BufferOffset(usize);
  784
  785// Addons allow storing per-editor state in other crates (e.g. Vim)
  786pub trait Addon: 'static {
  787    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  788
  789    fn render_buffer_header_controls(
  790        &self,
  791        _: &ExcerptInfo,
  792        _: &Window,
  793        _: &App,
  794    ) -> Option<AnyElement> {
  795        None
  796    }
  797
  798    fn to_any(&self) -> &dyn std::any::Any;
  799
  800    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  801        None
  802    }
  803}
  804
  805/// A set of caret positions, registered when the editor was edited.
  806pub struct ChangeList {
  807    changes: Vec<Vec<Anchor>>,
  808    /// Currently "selected" change.
  809    position: Option<usize>,
  810}
  811
  812impl ChangeList {
  813    pub fn new() -> Self {
  814        Self {
  815            changes: Vec::new(),
  816            position: None,
  817        }
  818    }
  819
  820    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  821    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  822    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  823        if self.changes.is_empty() {
  824            return None;
  825        }
  826
  827        let prev = self.position.unwrap_or(self.changes.len());
  828        let next = if direction == Direction::Prev {
  829            prev.saturating_sub(count)
  830        } else {
  831            (prev + count).min(self.changes.len() - 1)
  832        };
  833        self.position = Some(next);
  834        self.changes.get(next).map(|anchors| anchors.as_slice())
  835    }
  836
  837    /// Adds a new change to the list, resetting the change list position.
  838    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  839        self.position.take();
  840        if pop_state {
  841            self.changes.pop();
  842        }
  843        self.changes.push(new_positions.clone());
  844    }
  845
  846    pub fn last(&self) -> Option<&[Anchor]> {
  847        self.changes.last().map(|anchors| anchors.as_slice())
  848    }
  849}
  850
  851#[derive(Clone)]
  852struct InlineBlamePopoverState {
  853    scroll_handle: ScrollHandle,
  854    commit_message: Option<ParsedCommitMessage>,
  855    markdown: Entity<Markdown>,
  856}
  857
  858struct InlineBlamePopover {
  859    position: gpui::Point<Pixels>,
  860    show_task: Option<Task<()>>,
  861    hide_task: Option<Task<()>>,
  862    popover_bounds: Option<Bounds<Pixels>>,
  863    popover_state: InlineBlamePopoverState,
  864}
  865
  866/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  867/// a breakpoint on them.
  868#[derive(Clone, Copy, Debug)]
  869struct PhantomBreakpointIndicator {
  870    display_row: DisplayRow,
  871    /// There's a small debounce between hovering over the line and showing the indicator.
  872    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  873    is_active: bool,
  874    collides_with_existing_breakpoint: bool,
  875}
  876/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  877///
  878/// See the [module level documentation](self) for more information.
  879pub struct Editor {
  880    focus_handle: FocusHandle,
  881    last_focused_descendant: Option<WeakFocusHandle>,
  882    /// The text buffer being edited
  883    buffer: Entity<MultiBuffer>,
  884    /// Map of how text in the buffer should be displayed.
  885    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  886    pub display_map: Entity<DisplayMap>,
  887    pub selections: SelectionsCollection,
  888    pub scroll_manager: ScrollManager,
  889    /// When inline assist editors are linked, they all render cursors because
  890    /// typing enters text into each of them, even the ones that aren't focused.
  891    pub(crate) show_cursor_when_unfocused: bool,
  892    columnar_selection_tail: Option<Anchor>,
  893    add_selections_state: Option<AddSelectionsState>,
  894    select_next_state: Option<SelectNextState>,
  895    select_prev_state: Option<SelectNextState>,
  896    selection_history: SelectionHistory,
  897    autoclose_regions: Vec<AutocloseRegion>,
  898    snippet_stack: InvalidationStack<SnippetState>,
  899    select_syntax_node_history: SelectSyntaxNodeHistory,
  900    ime_transaction: Option<TransactionId>,
  901    pub diagnostics_max_severity: DiagnosticSeverity,
  902    active_diagnostics: ActiveDiagnostic,
  903    show_inline_diagnostics: bool,
  904    inline_diagnostics_update: Task<()>,
  905    inline_diagnostics_enabled: bool,
  906    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  907    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  908    hard_wrap: Option<usize>,
  909
  910    // TODO: make this a access method
  911    pub project: Option<Entity<Project>>,
  912    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  913    completion_provider: Option<Box<dyn CompletionProvider>>,
  914    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  915    blink_manager: Entity<BlinkManager>,
  916    show_cursor_names: bool,
  917    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  918    pub show_local_selections: bool,
  919    mode: EditorMode,
  920    show_breadcrumbs: bool,
  921    show_gutter: bool,
  922    show_scrollbars: bool,
  923    minimap_visibility: MinimapVisibility,
  924    disable_expand_excerpt_buttons: bool,
  925    show_line_numbers: Option<bool>,
  926    use_relative_line_numbers: Option<bool>,
  927    show_git_diff_gutter: Option<bool>,
  928    show_code_actions: Option<bool>,
  929    show_runnables: Option<bool>,
  930    show_breakpoints: Option<bool>,
  931    show_wrap_guides: Option<bool>,
  932    show_indent_guides: Option<bool>,
  933    placeholder_text: Option<Arc<str>>,
  934    highlight_order: usize,
  935    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  936    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  937    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  938    scrollbar_marker_state: ScrollbarMarkerState,
  939    active_indent_guides_state: ActiveIndentGuidesState,
  940    nav_history: Option<ItemNavHistory>,
  941    context_menu: RefCell<Option<CodeContextMenu>>,
  942    context_menu_options: Option<ContextMenuOptions>,
  943    mouse_context_menu: Option<MouseContextMenu>,
  944    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  945    inline_blame_popover: Option<InlineBlamePopover>,
  946    signature_help_state: SignatureHelpState,
  947    auto_signature_help: Option<bool>,
  948    find_all_references_task_sources: Vec<Anchor>,
  949    next_completion_id: CompletionId,
  950    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  951    code_actions_task: Option<Task<Result<()>>>,
  952    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  953    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  954    document_highlights_task: Option<Task<()>>,
  955    linked_editing_range_task: Option<Task<Option<()>>>,
  956    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  957    pending_rename: Option<RenameState>,
  958    searchable: bool,
  959    cursor_shape: CursorShape,
  960    current_line_highlight: Option<CurrentLineHighlight>,
  961    collapse_matches: bool,
  962    autoindent_mode: Option<AutoindentMode>,
  963    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  964    input_enabled: bool,
  965    use_modal_editing: bool,
  966    read_only: bool,
  967    leader_id: Option<CollaboratorId>,
  968    remote_id: Option<ViewId>,
  969    pub hover_state: HoverState,
  970    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  971    gutter_hovered: bool,
  972    hovered_link_state: Option<HoveredLinkState>,
  973    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  974    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  975    active_inline_completion: Option<InlineCompletionState>,
  976    /// Used to prevent flickering as the user types while the menu is open
  977    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  978    edit_prediction_settings: EditPredictionSettings,
  979    inline_completions_hidden_for_vim_mode: bool,
  980    show_inline_completions_override: Option<bool>,
  981    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  982    edit_prediction_preview: EditPredictionPreview,
  983    edit_prediction_indent_conflict: bool,
  984    edit_prediction_requires_modifier_in_indent_conflict: bool,
  985    inlay_hint_cache: InlayHintCache,
  986    next_inlay_id: usize,
  987    _subscriptions: Vec<Subscription>,
  988    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  989    gutter_dimensions: GutterDimensions,
  990    style: Option<EditorStyle>,
  991    text_style_refinement: Option<TextStyleRefinement>,
  992    next_editor_action_id: EditorActionId,
  993    editor_actions:
  994        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  995    use_autoclose: bool,
  996    use_auto_surround: bool,
  997    auto_replace_emoji_shortcode: bool,
  998    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  999    show_git_blame_gutter: bool,
 1000    show_git_blame_inline: bool,
 1001    show_git_blame_inline_delay_task: Option<Task<()>>,
 1002    git_blame_inline_enabled: bool,
 1003    render_diff_hunk_controls: RenderDiffHunkControlsFn,
 1004    serialize_dirty_buffers: bool,
 1005    show_selection_menu: Option<bool>,
 1006    blame: Option<Entity<GitBlame>>,
 1007    blame_subscription: Option<Subscription>,
 1008    custom_context_menu: Option<
 1009        Box<
 1010            dyn 'static
 1011                + Fn(
 1012                    &mut Self,
 1013                    DisplayPoint,
 1014                    &mut Window,
 1015                    &mut Context<Self>,
 1016                ) -> Option<Entity<ui::ContextMenu>>,
 1017        >,
 1018    >,
 1019    last_bounds: Option<Bounds<Pixels>>,
 1020    last_position_map: Option<Rc<PositionMap>>,
 1021    expect_bounds_change: Option<Bounds<Pixels>>,
 1022    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
 1023    tasks_update_task: Option<Task<()>>,
 1024    breakpoint_store: Option<Entity<BreakpointStore>>,
 1025    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
 1026    in_project_search: bool,
 1027    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
 1028    breadcrumb_header: Option<String>,
 1029    focused_block: Option<FocusedBlock>,
 1030    next_scroll_position: NextScrollCursorCenterTopBottom,
 1031    addons: HashMap<TypeId, Box<dyn Addon>>,
 1032    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
 1033    load_diff_task: Option<Shared<Task<()>>>,
 1034    /// Whether we are temporarily displaying a diff other than git's
 1035    temporary_diff_override: bool,
 1036    selection_mark_mode: bool,
 1037    toggle_fold_multiple_buffers: Task<()>,
 1038    _scroll_cursor_center_top_bottom_task: Task<()>,
 1039    serialize_selections: Task<()>,
 1040    serialize_folds: Task<()>,
 1041    mouse_cursor_hidden: bool,
 1042    minimap: Option<Entity<Self>>,
 1043    hide_mouse_mode: HideMouseMode,
 1044    pub change_list: ChangeList,
 1045    inline_value_cache: InlineValueCache,
 1046}
 1047
 1048#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
 1049enum NextScrollCursorCenterTopBottom {
 1050    #[default]
 1051    Center,
 1052    Top,
 1053    Bottom,
 1054}
 1055
 1056impl NextScrollCursorCenterTopBottom {
 1057    fn next(&self) -> Self {
 1058        match self {
 1059            Self::Center => Self::Top,
 1060            Self::Top => Self::Bottom,
 1061            Self::Bottom => Self::Center,
 1062        }
 1063    }
 1064}
 1065
 1066#[derive(Clone)]
 1067pub struct EditorSnapshot {
 1068    pub mode: EditorMode,
 1069    show_gutter: bool,
 1070    show_line_numbers: Option<bool>,
 1071    show_git_diff_gutter: Option<bool>,
 1072    show_runnables: Option<bool>,
 1073    show_breakpoints: Option<bool>,
 1074    git_blame_gutter_max_author_length: Option<usize>,
 1075    pub display_snapshot: DisplaySnapshot,
 1076    pub placeholder_text: Option<Arc<str>>,
 1077    is_focused: bool,
 1078    scroll_anchor: ScrollAnchor,
 1079    ongoing_scroll: OngoingScroll,
 1080    current_line_highlight: CurrentLineHighlight,
 1081    gutter_hovered: bool,
 1082}
 1083
 1084#[derive(Default, Debug, Clone, Copy)]
 1085pub struct GutterDimensions {
 1086    pub left_padding: Pixels,
 1087    pub right_padding: Pixels,
 1088    pub width: Pixels,
 1089    pub margin: Pixels,
 1090    pub git_blame_entries_width: Option<Pixels>,
 1091}
 1092
 1093impl GutterDimensions {
 1094    fn default_with_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Self {
 1095        Self {
 1096            margin: Self::default_gutter_margin(font_id, font_size, cx),
 1097            ..Default::default()
 1098        }
 1099    }
 1100
 1101    fn default_gutter_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Pixels {
 1102        -cx.text_system().descent(font_id, font_size)
 1103    }
 1104    /// The full width of the space taken up by the gutter.
 1105    pub fn full_width(&self) -> Pixels {
 1106        self.margin + self.width
 1107    }
 1108
 1109    /// The width of the space reserved for the fold indicators,
 1110    /// use alongside 'justify_end' and `gutter_width` to
 1111    /// right align content with the line numbers
 1112    pub fn fold_area_width(&self) -> Pixels {
 1113        self.margin + self.right_padding
 1114    }
 1115}
 1116
 1117#[derive(Debug)]
 1118pub struct RemoteSelection {
 1119    pub replica_id: ReplicaId,
 1120    pub selection: Selection<Anchor>,
 1121    pub cursor_shape: CursorShape,
 1122    pub collaborator_id: CollaboratorId,
 1123    pub line_mode: bool,
 1124    pub user_name: Option<SharedString>,
 1125    pub color: PlayerColor,
 1126}
 1127
 1128#[derive(Clone, Debug)]
 1129struct SelectionHistoryEntry {
 1130    selections: Arc<[Selection<Anchor>]>,
 1131    select_next_state: Option<SelectNextState>,
 1132    select_prev_state: Option<SelectNextState>,
 1133    add_selections_state: Option<AddSelectionsState>,
 1134}
 1135
 1136enum SelectionHistoryMode {
 1137    Normal,
 1138    Undoing,
 1139    Redoing,
 1140}
 1141
 1142#[derive(Clone, PartialEq, Eq, Hash)]
 1143struct HoveredCursor {
 1144    replica_id: u16,
 1145    selection_id: usize,
 1146}
 1147
 1148impl Default for SelectionHistoryMode {
 1149    fn default() -> Self {
 1150        Self::Normal
 1151    }
 1152}
 1153
 1154#[derive(Default)]
 1155struct SelectionHistory {
 1156    #[allow(clippy::type_complexity)]
 1157    selections_by_transaction:
 1158        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1159    mode: SelectionHistoryMode,
 1160    undo_stack: VecDeque<SelectionHistoryEntry>,
 1161    redo_stack: VecDeque<SelectionHistoryEntry>,
 1162}
 1163
 1164impl SelectionHistory {
 1165    fn insert_transaction(
 1166        &mut self,
 1167        transaction_id: TransactionId,
 1168        selections: Arc<[Selection<Anchor>]>,
 1169    ) {
 1170        self.selections_by_transaction
 1171            .insert(transaction_id, (selections, None));
 1172    }
 1173
 1174    #[allow(clippy::type_complexity)]
 1175    fn transaction(
 1176        &self,
 1177        transaction_id: TransactionId,
 1178    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1179        self.selections_by_transaction.get(&transaction_id)
 1180    }
 1181
 1182    #[allow(clippy::type_complexity)]
 1183    fn transaction_mut(
 1184        &mut self,
 1185        transaction_id: TransactionId,
 1186    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1187        self.selections_by_transaction.get_mut(&transaction_id)
 1188    }
 1189
 1190    fn push(&mut self, entry: SelectionHistoryEntry) {
 1191        if !entry.selections.is_empty() {
 1192            match self.mode {
 1193                SelectionHistoryMode::Normal => {
 1194                    self.push_undo(entry);
 1195                    self.redo_stack.clear();
 1196                }
 1197                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1198                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1199            }
 1200        }
 1201    }
 1202
 1203    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1204        if self
 1205            .undo_stack
 1206            .back()
 1207            .map_or(true, |e| e.selections != entry.selections)
 1208        {
 1209            self.undo_stack.push_back(entry);
 1210            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1211                self.undo_stack.pop_front();
 1212            }
 1213        }
 1214    }
 1215
 1216    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1217        if self
 1218            .redo_stack
 1219            .back()
 1220            .map_or(true, |e| e.selections != entry.selections)
 1221        {
 1222            self.redo_stack.push_back(entry);
 1223            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1224                self.redo_stack.pop_front();
 1225            }
 1226        }
 1227    }
 1228}
 1229
 1230#[derive(Clone, Copy)]
 1231pub struct RowHighlightOptions {
 1232    pub autoscroll: bool,
 1233    pub include_gutter: bool,
 1234}
 1235
 1236impl Default for RowHighlightOptions {
 1237    fn default() -> Self {
 1238        Self {
 1239            autoscroll: Default::default(),
 1240            include_gutter: true,
 1241        }
 1242    }
 1243}
 1244
 1245struct RowHighlight {
 1246    index: usize,
 1247    range: Range<Anchor>,
 1248    color: Hsla,
 1249    options: RowHighlightOptions,
 1250    type_id: TypeId,
 1251}
 1252
 1253#[derive(Clone, Debug)]
 1254struct AddSelectionsState {
 1255    above: bool,
 1256    stack: Vec<usize>,
 1257}
 1258
 1259#[derive(Clone)]
 1260struct SelectNextState {
 1261    query: AhoCorasick,
 1262    wordwise: bool,
 1263    done: bool,
 1264}
 1265
 1266impl std::fmt::Debug for SelectNextState {
 1267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1268        f.debug_struct(std::any::type_name::<Self>())
 1269            .field("wordwise", &self.wordwise)
 1270            .field("done", &self.done)
 1271            .finish()
 1272    }
 1273}
 1274
 1275#[derive(Debug)]
 1276struct AutocloseRegion {
 1277    selection_id: usize,
 1278    range: Range<Anchor>,
 1279    pair: BracketPair,
 1280}
 1281
 1282#[derive(Debug)]
 1283struct SnippetState {
 1284    ranges: Vec<Vec<Range<Anchor>>>,
 1285    active_index: usize,
 1286    choices: Vec<Option<Vec<String>>>,
 1287}
 1288
 1289#[doc(hidden)]
 1290pub struct RenameState {
 1291    pub range: Range<Anchor>,
 1292    pub old_name: Arc<str>,
 1293    pub editor: Entity<Editor>,
 1294    block_id: CustomBlockId,
 1295}
 1296
 1297struct InvalidationStack<T>(Vec<T>);
 1298
 1299struct RegisteredInlineCompletionProvider {
 1300    provider: Arc<dyn InlineCompletionProviderHandle>,
 1301    _subscription: Subscription,
 1302}
 1303
 1304#[derive(Debug, PartialEq, Eq)]
 1305pub struct ActiveDiagnosticGroup {
 1306    pub active_range: Range<Anchor>,
 1307    pub active_message: String,
 1308    pub group_id: usize,
 1309    pub blocks: HashSet<CustomBlockId>,
 1310}
 1311
 1312#[derive(Debug, PartialEq, Eq)]
 1313#[allow(clippy::large_enum_variant)]
 1314pub(crate) enum ActiveDiagnostic {
 1315    None,
 1316    All,
 1317    Group(ActiveDiagnosticGroup),
 1318}
 1319
 1320#[derive(Serialize, Deserialize, Clone, Debug)]
 1321pub struct ClipboardSelection {
 1322    /// The number of bytes in this selection.
 1323    pub len: usize,
 1324    /// Whether this was a full-line selection.
 1325    pub is_entire_line: bool,
 1326    /// The indentation of the first line when this content was originally copied.
 1327    pub first_line_indent: u32,
 1328}
 1329
 1330// selections, scroll behavior, was newest selection reversed
 1331type SelectSyntaxNodeHistoryState = (
 1332    Box<[Selection<usize>]>,
 1333    SelectSyntaxNodeScrollBehavior,
 1334    bool,
 1335);
 1336
 1337#[derive(Default)]
 1338struct SelectSyntaxNodeHistory {
 1339    stack: Vec<SelectSyntaxNodeHistoryState>,
 1340    // disable temporarily to allow changing selections without losing the stack
 1341    pub disable_clearing: bool,
 1342}
 1343
 1344impl SelectSyntaxNodeHistory {
 1345    pub fn try_clear(&mut self) {
 1346        if !self.disable_clearing {
 1347            self.stack.clear();
 1348        }
 1349    }
 1350
 1351    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1352        self.stack.push(selection);
 1353    }
 1354
 1355    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1356        self.stack.pop()
 1357    }
 1358}
 1359
 1360enum SelectSyntaxNodeScrollBehavior {
 1361    CursorTop,
 1362    FitSelection,
 1363    CursorBottom,
 1364}
 1365
 1366#[derive(Debug)]
 1367pub(crate) struct NavigationData {
 1368    cursor_anchor: Anchor,
 1369    cursor_position: Point,
 1370    scroll_anchor: ScrollAnchor,
 1371    scroll_top_row: u32,
 1372}
 1373
 1374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1375pub enum GotoDefinitionKind {
 1376    Symbol,
 1377    Declaration,
 1378    Type,
 1379    Implementation,
 1380}
 1381
 1382#[derive(Debug, Clone)]
 1383enum InlayHintRefreshReason {
 1384    ModifiersChanged(bool),
 1385    Toggle(bool),
 1386    SettingsChange(InlayHintSettings),
 1387    NewLinesShown,
 1388    BufferEdited(HashSet<Arc<Language>>),
 1389    RefreshRequested,
 1390    ExcerptsRemoved(Vec<ExcerptId>),
 1391}
 1392
 1393impl InlayHintRefreshReason {
 1394    fn description(&self) -> &'static str {
 1395        match self {
 1396            Self::ModifiersChanged(_) => "modifiers changed",
 1397            Self::Toggle(_) => "toggle",
 1398            Self::SettingsChange(_) => "settings change",
 1399            Self::NewLinesShown => "new lines shown",
 1400            Self::BufferEdited(_) => "buffer edited",
 1401            Self::RefreshRequested => "refresh requested",
 1402            Self::ExcerptsRemoved(_) => "excerpts removed",
 1403        }
 1404    }
 1405}
 1406
 1407pub enum FormatTarget {
 1408    Buffers,
 1409    Ranges(Vec<Range<MultiBufferPoint>>),
 1410}
 1411
 1412pub(crate) struct FocusedBlock {
 1413    id: BlockId,
 1414    focus_handle: WeakFocusHandle,
 1415}
 1416
 1417#[derive(Clone)]
 1418enum JumpData {
 1419    MultiBufferRow {
 1420        row: MultiBufferRow,
 1421        line_offset_from_top: u32,
 1422    },
 1423    MultiBufferPoint {
 1424        excerpt_id: ExcerptId,
 1425        position: Point,
 1426        anchor: text::Anchor,
 1427        line_offset_from_top: u32,
 1428    },
 1429}
 1430
 1431pub enum MultibufferSelectionMode {
 1432    First,
 1433    All,
 1434}
 1435
 1436#[derive(Clone, Copy, Debug, Default)]
 1437pub struct RewrapOptions {
 1438    pub override_language_settings: bool,
 1439    pub preserve_existing_whitespace: bool,
 1440}
 1441
 1442impl Editor {
 1443    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1444        let buffer = cx.new(|cx| Buffer::local("", cx));
 1445        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1446        Self::new(
 1447            EditorMode::SingleLine { auto_width: false },
 1448            buffer,
 1449            None,
 1450            window,
 1451            cx,
 1452        )
 1453    }
 1454
 1455    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1456        let buffer = cx.new(|cx| Buffer::local("", cx));
 1457        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1458        Self::new(EditorMode::full(), buffer, None, window, cx)
 1459    }
 1460
 1461    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1462        let buffer = cx.new(|cx| Buffer::local("", cx));
 1463        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1464        Self::new(
 1465            EditorMode::SingleLine { auto_width: true },
 1466            buffer,
 1467            None,
 1468            window,
 1469            cx,
 1470        )
 1471    }
 1472
 1473    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1474        let buffer = cx.new(|cx| Buffer::local("", cx));
 1475        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1476        Self::new(
 1477            EditorMode::AutoHeight { max_lines },
 1478            buffer,
 1479            None,
 1480            window,
 1481            cx,
 1482        )
 1483    }
 1484
 1485    pub fn for_buffer(
 1486        buffer: Entity<Buffer>,
 1487        project: Option<Entity<Project>>,
 1488        window: &mut Window,
 1489        cx: &mut Context<Self>,
 1490    ) -> Self {
 1491        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1492        Self::new(EditorMode::full(), buffer, project, window, cx)
 1493    }
 1494
 1495    pub fn for_multibuffer(
 1496        buffer: Entity<MultiBuffer>,
 1497        project: Option<Entity<Project>>,
 1498        window: &mut Window,
 1499        cx: &mut Context<Self>,
 1500    ) -> Self {
 1501        Self::new(EditorMode::full(), buffer, project, window, cx)
 1502    }
 1503
 1504    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1505        let mut clone = Self::new(
 1506            self.mode.clone(),
 1507            self.buffer.clone(),
 1508            self.project.clone(),
 1509            window,
 1510            cx,
 1511        );
 1512        self.display_map.update(cx, |display_map, cx| {
 1513            let snapshot = display_map.snapshot(cx);
 1514            clone.display_map.update(cx, |display_map, cx| {
 1515                display_map.set_state(&snapshot, cx);
 1516            });
 1517        });
 1518        clone.folds_did_change(cx);
 1519        clone.selections.clone_state(&self.selections);
 1520        clone.scroll_manager.clone_state(&self.scroll_manager);
 1521        clone.searchable = self.searchable;
 1522        clone.read_only = self.read_only;
 1523        clone
 1524    }
 1525
 1526    pub fn new(
 1527        mode: EditorMode,
 1528        buffer: Entity<MultiBuffer>,
 1529        project: Option<Entity<Project>>,
 1530        window: &mut Window,
 1531        cx: &mut Context<Self>,
 1532    ) -> Self {
 1533        Editor::new_internal(mode, buffer, project, None, window, cx)
 1534    }
 1535
 1536    fn new_internal(
 1537        mode: EditorMode,
 1538        buffer: Entity<MultiBuffer>,
 1539        project: Option<Entity<Project>>,
 1540        display_map: Option<Entity<DisplayMap>>,
 1541        window: &mut Window,
 1542        cx: &mut Context<Self>,
 1543    ) -> Self {
 1544        debug_assert!(
 1545            display_map.is_none() || mode.is_minimap(),
 1546            "Providing a display map for a new editor is only intended for the minimap and might have unindended side effects otherwise!"
 1547        );
 1548
 1549        let full_mode = mode.is_full();
 1550        let diagnostics_max_severity = if full_mode {
 1551            EditorSettings::get_global(cx)
 1552                .diagnostics_max_severity
 1553                .unwrap_or(DiagnosticSeverity::Hint)
 1554        } else {
 1555            DiagnosticSeverity::Off
 1556        };
 1557        let style = window.text_style();
 1558        let font_size = style.font_size.to_pixels(window.rem_size());
 1559        let editor = cx.entity().downgrade();
 1560        let fold_placeholder = FoldPlaceholder {
 1561            constrain_width: true,
 1562            render: Arc::new(move |fold_id, fold_range, cx| {
 1563                let editor = editor.clone();
 1564                div()
 1565                    .id(fold_id)
 1566                    .bg(cx.theme().colors().ghost_element_background)
 1567                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1568                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1569                    .rounded_xs()
 1570                    .size_full()
 1571                    .cursor_pointer()
 1572                    .child("")
 1573                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1574                    .on_click(move |_, _window, cx| {
 1575                        editor
 1576                            .update(cx, |editor, cx| {
 1577                                editor.unfold_ranges(
 1578                                    &[fold_range.start..fold_range.end],
 1579                                    true,
 1580                                    false,
 1581                                    cx,
 1582                                );
 1583                                cx.stop_propagation();
 1584                            })
 1585                            .ok();
 1586                    })
 1587                    .into_any()
 1588            }),
 1589            merge_adjacent: true,
 1590            ..FoldPlaceholder::default()
 1591        };
 1592        let display_map = display_map.unwrap_or_else(|| {
 1593            cx.new(|cx| {
 1594                DisplayMap::new(
 1595                    buffer.clone(),
 1596                    style.font(),
 1597                    font_size,
 1598                    None,
 1599                    FILE_HEADER_HEIGHT,
 1600                    MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1601                    fold_placeholder,
 1602                    diagnostics_max_severity,
 1603                    cx,
 1604                )
 1605            })
 1606        });
 1607
 1608        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1609
 1610        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1611
 1612        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1613            .then(|| language_settings::SoftWrap::None);
 1614
 1615        let mut project_subscriptions = Vec::new();
 1616        if mode.is_full() {
 1617            if let Some(project) = project.as_ref() {
 1618                project_subscriptions.push(cx.subscribe_in(
 1619                    project,
 1620                    window,
 1621                    |editor, _, event, window, cx| match event {
 1622                        project::Event::RefreshCodeLens => {
 1623                            // we always query lens with actions, without storing them, always refreshing them
 1624                        }
 1625                        project::Event::RefreshInlayHints => {
 1626                            editor
 1627                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1628                        }
 1629                        project::Event::SnippetEdit(id, snippet_edits) => {
 1630                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1631                                let focus_handle = editor.focus_handle(cx);
 1632                                if focus_handle.is_focused(window) {
 1633                                    let snapshot = buffer.read(cx).snapshot();
 1634                                    for (range, snippet) in snippet_edits {
 1635                                        let editor_range =
 1636                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1637                                        editor
 1638                                            .insert_snippet(
 1639                                                &[editor_range],
 1640                                                snippet.clone(),
 1641                                                window,
 1642                                                cx,
 1643                                            )
 1644                                            .ok();
 1645                                    }
 1646                                }
 1647                            }
 1648                        }
 1649                        _ => {}
 1650                    },
 1651                ));
 1652                if let Some(task_inventory) = project
 1653                    .read(cx)
 1654                    .task_store()
 1655                    .read(cx)
 1656                    .task_inventory()
 1657                    .cloned()
 1658                {
 1659                    project_subscriptions.push(cx.observe_in(
 1660                        &task_inventory,
 1661                        window,
 1662                        |editor, _, window, cx| {
 1663                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1664                        },
 1665                    ));
 1666                };
 1667
 1668                project_subscriptions.push(cx.subscribe_in(
 1669                    &project.read(cx).breakpoint_store(),
 1670                    window,
 1671                    |editor, _, event, window, cx| match event {
 1672                        BreakpointStoreEvent::ClearDebugLines => {
 1673                            editor.clear_row_highlights::<ActiveDebugLine>();
 1674                            editor.refresh_inline_values(cx);
 1675                        }
 1676                        BreakpointStoreEvent::SetDebugLine => {
 1677                            if editor.go_to_active_debug_line(window, cx) {
 1678                                cx.stop_propagation();
 1679                            }
 1680
 1681                            editor.refresh_inline_values(cx);
 1682                        }
 1683                        _ => {}
 1684                    },
 1685                ));
 1686            }
 1687        }
 1688
 1689        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1690
 1691        let inlay_hint_settings =
 1692            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1693        let focus_handle = cx.focus_handle();
 1694        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1695            .detach();
 1696        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1697            .detach();
 1698        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1699            .detach();
 1700        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1701            .detach();
 1702
 1703        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1704            Some(false)
 1705        } else {
 1706            None
 1707        };
 1708
 1709        let breakpoint_store = match (&mode, project.as_ref()) {
 1710            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1711            _ => None,
 1712        };
 1713
 1714        let mut code_action_providers = Vec::new();
 1715        let mut load_uncommitted_diff = None;
 1716        if let Some(project) = project.clone() {
 1717            load_uncommitted_diff = Some(
 1718                update_uncommitted_diff_for_buffer(
 1719                    cx.entity(),
 1720                    &project,
 1721                    buffer.read(cx).all_buffers(),
 1722                    buffer.clone(),
 1723                    cx,
 1724                )
 1725                .shared(),
 1726            );
 1727            code_action_providers.push(Rc::new(project) as Rc<_>);
 1728        }
 1729
 1730        let mut this = Self {
 1731            focus_handle,
 1732            show_cursor_when_unfocused: false,
 1733            last_focused_descendant: None,
 1734            buffer: buffer.clone(),
 1735            display_map: display_map.clone(),
 1736            selections,
 1737            scroll_manager: ScrollManager::new(cx),
 1738            columnar_selection_tail: None,
 1739            add_selections_state: None,
 1740            select_next_state: None,
 1741            select_prev_state: None,
 1742            selection_history: SelectionHistory::default(),
 1743            autoclose_regions: Vec::new(),
 1744            snippet_stack: InvalidationStack::default(),
 1745            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1746            ime_transaction: None,
 1747            active_diagnostics: ActiveDiagnostic::None,
 1748            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1749            inline_diagnostics_update: Task::ready(()),
 1750            inline_diagnostics: Vec::new(),
 1751            soft_wrap_mode_override,
 1752            diagnostics_max_severity,
 1753            hard_wrap: None,
 1754            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1755            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1756            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1757            project,
 1758            blink_manager: blink_manager.clone(),
 1759            show_local_selections: true,
 1760            show_scrollbars: full_mode,
 1761            minimap_visibility: MinimapVisibility::for_mode(&mode, cx),
 1762            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1763            show_gutter: mode.is_full(),
 1764            show_line_numbers: None,
 1765            use_relative_line_numbers: None,
 1766            disable_expand_excerpt_buttons: false,
 1767            show_git_diff_gutter: None,
 1768            show_code_actions: None,
 1769            show_runnables: None,
 1770            show_breakpoints: None,
 1771            show_wrap_guides: None,
 1772            show_indent_guides,
 1773            placeholder_text: None,
 1774            highlight_order: 0,
 1775            highlighted_rows: HashMap::default(),
 1776            background_highlights: TreeMap::default(),
 1777            gutter_highlights: TreeMap::default(),
 1778            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1779            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1780            nav_history: None,
 1781            context_menu: RefCell::new(None),
 1782            context_menu_options: None,
 1783            mouse_context_menu: None,
 1784            completion_tasks: Vec::new(),
 1785            inline_blame_popover: None,
 1786            signature_help_state: SignatureHelpState::default(),
 1787            auto_signature_help: None,
 1788            find_all_references_task_sources: Vec::new(),
 1789            next_completion_id: 0,
 1790            next_inlay_id: 0,
 1791            code_action_providers,
 1792            available_code_actions: None,
 1793            code_actions_task: None,
 1794            quick_selection_highlight_task: None,
 1795            debounced_selection_highlight_task: None,
 1796            document_highlights_task: None,
 1797            linked_editing_range_task: None,
 1798            pending_rename: None,
 1799            searchable: true,
 1800            cursor_shape: EditorSettings::get_global(cx)
 1801                .cursor_shape
 1802                .unwrap_or_default(),
 1803            current_line_highlight: None,
 1804            autoindent_mode: Some(AutoindentMode::EachLine),
 1805            collapse_matches: false,
 1806            workspace: None,
 1807            input_enabled: true,
 1808            use_modal_editing: mode.is_full(),
 1809            read_only: mode.is_minimap(),
 1810            use_autoclose: true,
 1811            use_auto_surround: true,
 1812            auto_replace_emoji_shortcode: false,
 1813            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1814            leader_id: None,
 1815            remote_id: None,
 1816            hover_state: HoverState::default(),
 1817            pending_mouse_down: None,
 1818            hovered_link_state: None,
 1819            edit_prediction_provider: None,
 1820            active_inline_completion: None,
 1821            stale_inline_completion_in_menu: None,
 1822            edit_prediction_preview: EditPredictionPreview::Inactive {
 1823                released_too_fast: false,
 1824            },
 1825            inline_diagnostics_enabled: mode.is_full(),
 1826            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1827            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1828
 1829            gutter_hovered: false,
 1830            pixel_position_of_newest_cursor: None,
 1831            last_bounds: None,
 1832            last_position_map: None,
 1833            expect_bounds_change: None,
 1834            gutter_dimensions: GutterDimensions::default(),
 1835            style: None,
 1836            show_cursor_names: false,
 1837            hovered_cursors: HashMap::default(),
 1838            next_editor_action_id: EditorActionId::default(),
 1839            editor_actions: Rc::default(),
 1840            inline_completions_hidden_for_vim_mode: false,
 1841            show_inline_completions_override: None,
 1842            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1843            edit_prediction_settings: EditPredictionSettings::Disabled,
 1844            edit_prediction_indent_conflict: false,
 1845            edit_prediction_requires_modifier_in_indent_conflict: true,
 1846            custom_context_menu: None,
 1847            show_git_blame_gutter: false,
 1848            show_git_blame_inline: false,
 1849            show_selection_menu: None,
 1850            show_git_blame_inline_delay_task: None,
 1851            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1852            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1853            serialize_dirty_buffers: !mode.is_minimap()
 1854                && ProjectSettings::get_global(cx)
 1855                    .session
 1856                    .restore_unsaved_buffers,
 1857            blame: None,
 1858            blame_subscription: None,
 1859            tasks: BTreeMap::default(),
 1860
 1861            breakpoint_store,
 1862            gutter_breakpoint_indicator: (None, None),
 1863            _subscriptions: vec![
 1864                cx.observe(&buffer, Self::on_buffer_changed),
 1865                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1866                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1867                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1868                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1869                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1870                cx.observe_window_activation(window, |editor, window, cx| {
 1871                    let active = window.is_window_active();
 1872                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1873                        if active {
 1874                            blink_manager.enable(cx);
 1875                        } else {
 1876                            blink_manager.disable(cx);
 1877                        }
 1878                    });
 1879                }),
 1880            ],
 1881            tasks_update_task: None,
 1882            linked_edit_ranges: Default::default(),
 1883            in_project_search: false,
 1884            previous_search_ranges: None,
 1885            breadcrumb_header: None,
 1886            focused_block: None,
 1887            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1888            addons: HashMap::default(),
 1889            registered_buffers: HashMap::default(),
 1890            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1891            selection_mark_mode: false,
 1892            toggle_fold_multiple_buffers: Task::ready(()),
 1893            serialize_selections: Task::ready(()),
 1894            serialize_folds: Task::ready(()),
 1895            text_style_refinement: None,
 1896            load_diff_task: load_uncommitted_diff,
 1897            temporary_diff_override: false,
 1898            mouse_cursor_hidden: false,
 1899            minimap: None,
 1900            hide_mouse_mode: EditorSettings::get_global(cx)
 1901                .hide_mouse
 1902                .unwrap_or_default(),
 1903            change_list: ChangeList::new(),
 1904            mode,
 1905        };
 1906        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1907            this._subscriptions
 1908                .push(cx.observe(breakpoints, |_, _, cx| {
 1909                    cx.notify();
 1910                }));
 1911        }
 1912        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1913        this._subscriptions.extend(project_subscriptions);
 1914
 1915        this._subscriptions.push(cx.subscribe_in(
 1916            &cx.entity(),
 1917            window,
 1918            |editor, _, e: &EditorEvent, window, cx| match e {
 1919                EditorEvent::ScrollPositionChanged { local, .. } => {
 1920                    if *local {
 1921                        let new_anchor = editor.scroll_manager.anchor();
 1922                        let snapshot = editor.snapshot(window, cx);
 1923                        editor.update_restoration_data(cx, move |data| {
 1924                            data.scroll_position = (
 1925                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1926                                new_anchor.offset,
 1927                            );
 1928                        });
 1929                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1930                        editor.inline_blame_popover.take();
 1931                    }
 1932                }
 1933                EditorEvent::Edited { .. } => {
 1934                    if !vim_enabled(cx) {
 1935                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1936                        let pop_state = editor
 1937                            .change_list
 1938                            .last()
 1939                            .map(|previous| {
 1940                                previous.len() == selections.len()
 1941                                    && previous.iter().enumerate().all(|(ix, p)| {
 1942                                        p.to_display_point(&map).row()
 1943                                            == selections[ix].head().row()
 1944                                    })
 1945                            })
 1946                            .unwrap_or(false);
 1947                        let new_positions = selections
 1948                            .into_iter()
 1949                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1950                            .collect();
 1951                        editor
 1952                            .change_list
 1953                            .push_to_change_list(pop_state, new_positions);
 1954                    }
 1955                }
 1956                _ => (),
 1957            },
 1958        ));
 1959
 1960        if let Some(dap_store) = this
 1961            .project
 1962            .as_ref()
 1963            .map(|project| project.read(cx).dap_store())
 1964        {
 1965            let weak_editor = cx.weak_entity();
 1966
 1967            this._subscriptions
 1968                .push(
 1969                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1970                        let session_entity = cx.entity();
 1971                        weak_editor
 1972                            .update(cx, |editor, cx| {
 1973                                editor._subscriptions.push(
 1974                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1975                                );
 1976                            })
 1977                            .ok();
 1978                    }),
 1979                );
 1980
 1981            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1982                this._subscriptions
 1983                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1984            }
 1985        }
 1986
 1987        this.end_selection(window, cx);
 1988        this.scroll_manager.show_scrollbars(window, cx);
 1989        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1990
 1991        if full_mode {
 1992            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1993            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1994
 1995            if this.git_blame_inline_enabled {
 1996                this.start_git_blame_inline(false, window, cx);
 1997            }
 1998
 1999            this.go_to_active_debug_line(window, cx);
 2000
 2001            if let Some(buffer) = buffer.read(cx).as_singleton() {
 2002                if let Some(project) = this.project.as_ref() {
 2003                    let handle = project.update(cx, |project, cx| {
 2004                        project.register_buffer_with_language_servers(&buffer, cx)
 2005                    });
 2006                    this.registered_buffers
 2007                        .insert(buffer.read(cx).remote_id(), handle);
 2008                }
 2009            }
 2010
 2011            this.minimap = this.create_minimap(EditorSettings::get_global(cx).minimap, window, cx);
 2012        }
 2013
 2014        this.report_editor_event("Editor Opened", None, cx);
 2015        this
 2016    }
 2017
 2018    pub fn deploy_mouse_context_menu(
 2019        &mut self,
 2020        position: gpui::Point<Pixels>,
 2021        context_menu: Entity<ContextMenu>,
 2022        window: &mut Window,
 2023        cx: &mut Context<Self>,
 2024    ) {
 2025        self.mouse_context_menu = Some(MouseContextMenu::new(
 2026            self,
 2027            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 2028            context_menu,
 2029            window,
 2030            cx,
 2031        ));
 2032    }
 2033
 2034    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 2035        self.mouse_context_menu
 2036            .as_ref()
 2037            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 2038    }
 2039
 2040    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 2041        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 2042    }
 2043
 2044    fn key_context_internal(
 2045        &self,
 2046        has_active_edit_prediction: bool,
 2047        window: &Window,
 2048        cx: &App,
 2049    ) -> KeyContext {
 2050        let mut key_context = KeyContext::new_with_defaults();
 2051        key_context.add("Editor");
 2052        let mode = match self.mode {
 2053            EditorMode::SingleLine { .. } => "single_line",
 2054            EditorMode::AutoHeight { .. } => "auto_height",
 2055            EditorMode::Minimap { .. } => "minimap",
 2056            EditorMode::Full { .. } => "full",
 2057        };
 2058
 2059        if EditorSettings::jupyter_enabled(cx) {
 2060            key_context.add("jupyter");
 2061        }
 2062
 2063        key_context.set("mode", mode);
 2064        if self.pending_rename.is_some() {
 2065            key_context.add("renaming");
 2066        }
 2067
 2068        match self.context_menu.borrow().as_ref() {
 2069            Some(CodeContextMenu::Completions(_)) => {
 2070                key_context.add("menu");
 2071                key_context.add("showing_completions");
 2072            }
 2073            Some(CodeContextMenu::CodeActions(_)) => {
 2074                key_context.add("menu");
 2075                key_context.add("showing_code_actions")
 2076            }
 2077            None => {}
 2078        }
 2079
 2080        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2081        if !self.focus_handle(cx).contains_focused(window, cx)
 2082            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 2083        {
 2084            for addon in self.addons.values() {
 2085                addon.extend_key_context(&mut key_context, cx)
 2086            }
 2087        }
 2088
 2089        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 2090            if let Some(extension) = singleton_buffer
 2091                .read(cx)
 2092                .file()
 2093                .and_then(|file| file.path().extension()?.to_str())
 2094            {
 2095                key_context.set("extension", extension.to_string());
 2096            }
 2097        } else {
 2098            key_context.add("multibuffer");
 2099        }
 2100
 2101        if has_active_edit_prediction {
 2102            if self.edit_prediction_in_conflict() {
 2103                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2104            } else {
 2105                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2106                key_context.add("copilot_suggestion");
 2107            }
 2108        }
 2109
 2110        if self.selection_mark_mode {
 2111            key_context.add("selection_mode");
 2112        }
 2113
 2114        key_context
 2115    }
 2116
 2117    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2118        self.mouse_cursor_hidden = match origin {
 2119            HideMouseCursorOrigin::TypingAction => {
 2120                matches!(
 2121                    self.hide_mouse_mode,
 2122                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2123                )
 2124            }
 2125            HideMouseCursorOrigin::MovementAction => {
 2126                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2127            }
 2128        };
 2129    }
 2130
 2131    pub fn edit_prediction_in_conflict(&self) -> bool {
 2132        if !self.show_edit_predictions_in_menu() {
 2133            return false;
 2134        }
 2135
 2136        let showing_completions = self
 2137            .context_menu
 2138            .borrow()
 2139            .as_ref()
 2140            .map_or(false, |context| {
 2141                matches!(context, CodeContextMenu::Completions(_))
 2142            });
 2143
 2144        showing_completions
 2145            || self.edit_prediction_requires_modifier()
 2146            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2147            // bindings to insert tab characters.
 2148            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2149    }
 2150
 2151    pub fn accept_edit_prediction_keybind(
 2152        &self,
 2153        window: &Window,
 2154        cx: &App,
 2155    ) -> AcceptEditPredictionBinding {
 2156        let key_context = self.key_context_internal(true, window, cx);
 2157        let in_conflict = self.edit_prediction_in_conflict();
 2158
 2159        AcceptEditPredictionBinding(
 2160            window
 2161                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2162                .into_iter()
 2163                .filter(|binding| {
 2164                    !in_conflict
 2165                        || binding
 2166                            .keystrokes()
 2167                            .first()
 2168                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2169                })
 2170                .rev()
 2171                .min_by_key(|binding| {
 2172                    binding
 2173                        .keystrokes()
 2174                        .first()
 2175                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2176                }),
 2177        )
 2178    }
 2179
 2180    pub fn new_file(
 2181        workspace: &mut Workspace,
 2182        _: &workspace::NewFile,
 2183        window: &mut Window,
 2184        cx: &mut Context<Workspace>,
 2185    ) {
 2186        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2187            "Failed to create buffer",
 2188            window,
 2189            cx,
 2190            |e, _, _| match e.error_code() {
 2191                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2192                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2193                e.error_tag("required").unwrap_or("the latest version")
 2194            )),
 2195                _ => None,
 2196            },
 2197        );
 2198    }
 2199
 2200    pub fn new_in_workspace(
 2201        workspace: &mut Workspace,
 2202        window: &mut Window,
 2203        cx: &mut Context<Workspace>,
 2204    ) -> Task<Result<Entity<Editor>>> {
 2205        let project = workspace.project().clone();
 2206        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2207
 2208        cx.spawn_in(window, async move |workspace, cx| {
 2209            let buffer = create.await?;
 2210            workspace.update_in(cx, |workspace, window, cx| {
 2211                let editor =
 2212                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2213                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2214                editor
 2215            })
 2216        })
 2217    }
 2218
 2219    fn new_file_vertical(
 2220        workspace: &mut Workspace,
 2221        _: &workspace::NewFileSplitVertical,
 2222        window: &mut Window,
 2223        cx: &mut Context<Workspace>,
 2224    ) {
 2225        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2226    }
 2227
 2228    fn new_file_horizontal(
 2229        workspace: &mut Workspace,
 2230        _: &workspace::NewFileSplitHorizontal,
 2231        window: &mut Window,
 2232        cx: &mut Context<Workspace>,
 2233    ) {
 2234        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2235    }
 2236
 2237    fn new_file_in_direction(
 2238        workspace: &mut Workspace,
 2239        direction: SplitDirection,
 2240        window: &mut Window,
 2241        cx: &mut Context<Workspace>,
 2242    ) {
 2243        let project = workspace.project().clone();
 2244        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2245
 2246        cx.spawn_in(window, async move |workspace, cx| {
 2247            let buffer = create.await?;
 2248            workspace.update_in(cx, move |workspace, window, cx| {
 2249                workspace.split_item(
 2250                    direction,
 2251                    Box::new(
 2252                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2253                    ),
 2254                    window,
 2255                    cx,
 2256                )
 2257            })?;
 2258            anyhow::Ok(())
 2259        })
 2260        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2261            match e.error_code() {
 2262                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2263                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2264                e.error_tag("required").unwrap_or("the latest version")
 2265            )),
 2266                _ => None,
 2267            }
 2268        });
 2269    }
 2270
 2271    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2272        self.leader_id
 2273    }
 2274
 2275    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2276        &self.buffer
 2277    }
 2278
 2279    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2280        self.workspace.as_ref()?.0.upgrade()
 2281    }
 2282
 2283    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2284        self.buffer().read(cx).title(cx)
 2285    }
 2286
 2287    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2288        let git_blame_gutter_max_author_length = self
 2289            .render_git_blame_gutter(cx)
 2290            .then(|| {
 2291                if let Some(blame) = self.blame.as_ref() {
 2292                    let max_author_length =
 2293                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2294                    Some(max_author_length)
 2295                } else {
 2296                    None
 2297                }
 2298            })
 2299            .flatten();
 2300
 2301        EditorSnapshot {
 2302            mode: self.mode.clone(),
 2303            show_gutter: self.show_gutter,
 2304            show_line_numbers: self.show_line_numbers,
 2305            show_git_diff_gutter: self.show_git_diff_gutter,
 2306            show_runnables: self.show_runnables,
 2307            show_breakpoints: self.show_breakpoints,
 2308            git_blame_gutter_max_author_length,
 2309            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2310            scroll_anchor: self.scroll_manager.anchor(),
 2311            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2312            placeholder_text: self.placeholder_text.clone(),
 2313            is_focused: self.focus_handle.is_focused(window),
 2314            current_line_highlight: self
 2315                .current_line_highlight
 2316                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2317            gutter_hovered: self.gutter_hovered,
 2318        }
 2319    }
 2320
 2321    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2322        self.buffer.read(cx).language_at(point, cx)
 2323    }
 2324
 2325    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2326        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2327    }
 2328
 2329    pub fn active_excerpt(
 2330        &self,
 2331        cx: &App,
 2332    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2333        self.buffer
 2334            .read(cx)
 2335            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2336    }
 2337
 2338    pub fn mode(&self) -> &EditorMode {
 2339        &self.mode
 2340    }
 2341
 2342    pub fn set_mode(&mut self, mode: EditorMode) {
 2343        self.mode = mode;
 2344    }
 2345
 2346    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2347        self.collaboration_hub.as_deref()
 2348    }
 2349
 2350    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2351        self.collaboration_hub = Some(hub);
 2352    }
 2353
 2354    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2355        self.in_project_search = in_project_search;
 2356    }
 2357
 2358    pub fn set_custom_context_menu(
 2359        &mut self,
 2360        f: impl 'static
 2361        + Fn(
 2362            &mut Self,
 2363            DisplayPoint,
 2364            &mut Window,
 2365            &mut Context<Self>,
 2366        ) -> Option<Entity<ui::ContextMenu>>,
 2367    ) {
 2368        self.custom_context_menu = Some(Box::new(f))
 2369    }
 2370
 2371    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2372        self.completion_provider = provider;
 2373    }
 2374
 2375    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2376        self.semantics_provider.clone()
 2377    }
 2378
 2379    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2380        self.semantics_provider = provider;
 2381    }
 2382
 2383    pub fn set_edit_prediction_provider<T>(
 2384        &mut self,
 2385        provider: Option<Entity<T>>,
 2386        window: &mut Window,
 2387        cx: &mut Context<Self>,
 2388    ) where
 2389        T: EditPredictionProvider,
 2390    {
 2391        self.edit_prediction_provider =
 2392            provider.map(|provider| RegisteredInlineCompletionProvider {
 2393                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2394                    if this.focus_handle.is_focused(window) {
 2395                        this.update_visible_inline_completion(window, cx);
 2396                    }
 2397                }),
 2398                provider: Arc::new(provider),
 2399            });
 2400        self.update_edit_prediction_settings(cx);
 2401        self.refresh_inline_completion(false, false, window, cx);
 2402    }
 2403
 2404    pub fn placeholder_text(&self) -> Option<&str> {
 2405        self.placeholder_text.as_deref()
 2406    }
 2407
 2408    pub fn set_placeholder_text(
 2409        &mut self,
 2410        placeholder_text: impl Into<Arc<str>>,
 2411        cx: &mut Context<Self>,
 2412    ) {
 2413        let placeholder_text = Some(placeholder_text.into());
 2414        if self.placeholder_text != placeholder_text {
 2415            self.placeholder_text = placeholder_text;
 2416            cx.notify();
 2417        }
 2418    }
 2419
 2420    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2421        self.cursor_shape = cursor_shape;
 2422
 2423        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2424        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2425
 2426        cx.notify();
 2427    }
 2428
 2429    pub fn set_current_line_highlight(
 2430        &mut self,
 2431        current_line_highlight: Option<CurrentLineHighlight>,
 2432    ) {
 2433        self.current_line_highlight = current_line_highlight;
 2434    }
 2435
 2436    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2437        self.collapse_matches = collapse_matches;
 2438    }
 2439
 2440    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2441        let buffers = self.buffer.read(cx).all_buffers();
 2442        let Some(project) = self.project.as_ref() else {
 2443            return;
 2444        };
 2445        project.update(cx, |project, cx| {
 2446            for buffer in buffers {
 2447                self.registered_buffers
 2448                    .entry(buffer.read(cx).remote_id())
 2449                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2450            }
 2451        })
 2452    }
 2453
 2454    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2455        if self.collapse_matches {
 2456            return range.start..range.start;
 2457        }
 2458        range.clone()
 2459    }
 2460
 2461    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2462        if self.display_map.read(cx).clip_at_line_ends != clip {
 2463            self.display_map
 2464                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2465        }
 2466    }
 2467
 2468    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2469        self.input_enabled = input_enabled;
 2470    }
 2471
 2472    pub fn set_inline_completions_hidden_for_vim_mode(
 2473        &mut self,
 2474        hidden: bool,
 2475        window: &mut Window,
 2476        cx: &mut Context<Self>,
 2477    ) {
 2478        if hidden != self.inline_completions_hidden_for_vim_mode {
 2479            self.inline_completions_hidden_for_vim_mode = hidden;
 2480            if hidden {
 2481                self.update_visible_inline_completion(window, cx);
 2482            } else {
 2483                self.refresh_inline_completion(true, false, window, cx);
 2484            }
 2485        }
 2486    }
 2487
 2488    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2489        self.menu_inline_completions_policy = value;
 2490    }
 2491
 2492    pub fn set_autoindent(&mut self, autoindent: bool) {
 2493        if autoindent {
 2494            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2495        } else {
 2496            self.autoindent_mode = None;
 2497        }
 2498    }
 2499
 2500    pub fn read_only(&self, cx: &App) -> bool {
 2501        self.read_only || self.buffer.read(cx).read_only()
 2502    }
 2503
 2504    pub fn set_read_only(&mut self, read_only: bool) {
 2505        self.read_only = read_only;
 2506    }
 2507
 2508    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2509        self.use_autoclose = autoclose;
 2510    }
 2511
 2512    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2513        self.use_auto_surround = auto_surround;
 2514    }
 2515
 2516    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2517        self.auto_replace_emoji_shortcode = auto_replace;
 2518    }
 2519
 2520    pub fn toggle_edit_predictions(
 2521        &mut self,
 2522        _: &ToggleEditPrediction,
 2523        window: &mut Window,
 2524        cx: &mut Context<Self>,
 2525    ) {
 2526        if self.show_inline_completions_override.is_some() {
 2527            self.set_show_edit_predictions(None, window, cx);
 2528        } else {
 2529            let show_edit_predictions = !self.edit_predictions_enabled();
 2530            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2531        }
 2532    }
 2533
 2534    pub fn set_show_edit_predictions(
 2535        &mut self,
 2536        show_edit_predictions: Option<bool>,
 2537        window: &mut Window,
 2538        cx: &mut Context<Self>,
 2539    ) {
 2540        self.show_inline_completions_override = show_edit_predictions;
 2541        self.update_edit_prediction_settings(cx);
 2542
 2543        if let Some(false) = show_edit_predictions {
 2544            self.discard_inline_completion(false, cx);
 2545        } else {
 2546            self.refresh_inline_completion(false, true, window, cx);
 2547        }
 2548    }
 2549
 2550    fn inline_completions_disabled_in_scope(
 2551        &self,
 2552        buffer: &Entity<Buffer>,
 2553        buffer_position: language::Anchor,
 2554        cx: &App,
 2555    ) -> bool {
 2556        let snapshot = buffer.read(cx).snapshot();
 2557        let settings = snapshot.settings_at(buffer_position, cx);
 2558
 2559        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2560            return false;
 2561        };
 2562
 2563        scope.override_name().map_or(false, |scope_name| {
 2564            settings
 2565                .edit_predictions_disabled_in
 2566                .iter()
 2567                .any(|s| s == scope_name)
 2568        })
 2569    }
 2570
 2571    pub fn set_use_modal_editing(&mut self, to: bool) {
 2572        self.use_modal_editing = to;
 2573    }
 2574
 2575    pub fn use_modal_editing(&self) -> bool {
 2576        self.use_modal_editing
 2577    }
 2578
 2579    fn selections_did_change(
 2580        &mut self,
 2581        local: bool,
 2582        old_cursor_position: &Anchor,
 2583        show_completions: bool,
 2584        window: &mut Window,
 2585        cx: &mut Context<Self>,
 2586    ) {
 2587        window.invalidate_character_coordinates();
 2588
 2589        // Copy selections to primary selection buffer
 2590        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2591        if local {
 2592            let selections = self.selections.all::<usize>(cx);
 2593            let buffer_handle = self.buffer.read(cx).read(cx);
 2594
 2595            let mut text = String::new();
 2596            for (index, selection) in selections.iter().enumerate() {
 2597                let text_for_selection = buffer_handle
 2598                    .text_for_range(selection.start..selection.end)
 2599                    .collect::<String>();
 2600
 2601                text.push_str(&text_for_selection);
 2602                if index != selections.len() - 1 {
 2603                    text.push('\n');
 2604                }
 2605            }
 2606
 2607            if !text.is_empty() {
 2608                cx.write_to_primary(ClipboardItem::new_string(text));
 2609            }
 2610        }
 2611
 2612        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2613            self.buffer.update(cx, |buffer, cx| {
 2614                buffer.set_active_selections(
 2615                    &self.selections.disjoint_anchors(),
 2616                    self.selections.line_mode,
 2617                    self.cursor_shape,
 2618                    cx,
 2619                )
 2620            });
 2621        }
 2622        let display_map = self
 2623            .display_map
 2624            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2625        let buffer = &display_map.buffer_snapshot;
 2626        self.add_selections_state = None;
 2627        self.select_next_state = None;
 2628        self.select_prev_state = None;
 2629        self.select_syntax_node_history.try_clear();
 2630        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2631        self.snippet_stack
 2632            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2633        self.take_rename(false, window, cx);
 2634
 2635        let new_cursor_position = self.selections.newest_anchor().head();
 2636
 2637        self.push_to_nav_history(
 2638            *old_cursor_position,
 2639            Some(new_cursor_position.to_point(buffer)),
 2640            false,
 2641            cx,
 2642        );
 2643
 2644        if local {
 2645            let new_cursor_position = self.selections.newest_anchor().head();
 2646            let mut context_menu = self.context_menu.borrow_mut();
 2647            let completion_menu = match context_menu.as_ref() {
 2648                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2649                _ => {
 2650                    *context_menu = None;
 2651                    None
 2652                }
 2653            };
 2654            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2655                if !self.registered_buffers.contains_key(&buffer_id) {
 2656                    if let Some(project) = self.project.as_ref() {
 2657                        project.update(cx, |project, cx| {
 2658                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2659                                return;
 2660                            };
 2661                            self.registered_buffers.insert(
 2662                                buffer_id,
 2663                                project.register_buffer_with_language_servers(&buffer, cx),
 2664                            );
 2665                        })
 2666                    }
 2667                }
 2668            }
 2669
 2670            if let Some(completion_menu) = completion_menu {
 2671                let cursor_position = new_cursor_position.to_offset(buffer);
 2672                let (word_range, kind) =
 2673                    buffer.surrounding_word(completion_menu.initial_position, true);
 2674                if kind == Some(CharKind::Word)
 2675                    && word_range.to_inclusive().contains(&cursor_position)
 2676                {
 2677                    let mut completion_menu = completion_menu.clone();
 2678                    drop(context_menu);
 2679
 2680                    let query = Self::completion_query(buffer, cursor_position);
 2681                    cx.spawn(async move |this, cx| {
 2682                        completion_menu
 2683                            .filter(query.as_deref(), cx.background_executor().clone())
 2684                            .await;
 2685
 2686                        this.update(cx, |this, cx| {
 2687                            let mut context_menu = this.context_menu.borrow_mut();
 2688                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2689                            else {
 2690                                return;
 2691                            };
 2692
 2693                            if menu.id > completion_menu.id {
 2694                                return;
 2695                            }
 2696
 2697                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2698                            drop(context_menu);
 2699                            cx.notify();
 2700                        })
 2701                    })
 2702                    .detach();
 2703
 2704                    if show_completions {
 2705                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2706                    }
 2707                } else {
 2708                    drop(context_menu);
 2709                    self.hide_context_menu(window, cx);
 2710                }
 2711            } else {
 2712                drop(context_menu);
 2713            }
 2714
 2715            hide_hover(self, cx);
 2716
 2717            if old_cursor_position.to_display_point(&display_map).row()
 2718                != new_cursor_position.to_display_point(&display_map).row()
 2719            {
 2720                self.available_code_actions.take();
 2721            }
 2722            self.refresh_code_actions(window, cx);
 2723            self.refresh_document_highlights(cx);
 2724            self.refresh_selected_text_highlights(false, window, cx);
 2725            refresh_matching_bracket_highlights(self, window, cx);
 2726            self.update_visible_inline_completion(window, cx);
 2727            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2728            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2729            self.inline_blame_popover.take();
 2730            if self.git_blame_inline_enabled {
 2731                self.start_inline_blame_timer(window, cx);
 2732            }
 2733        }
 2734
 2735        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2736        cx.emit(EditorEvent::SelectionsChanged { local });
 2737
 2738        let selections = &self.selections.disjoint;
 2739        if selections.len() == 1 {
 2740            cx.emit(SearchEvent::ActiveMatchChanged)
 2741        }
 2742        if local {
 2743            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2744                let inmemory_selections = selections
 2745                    .iter()
 2746                    .map(|s| {
 2747                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2748                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2749                    })
 2750                    .collect();
 2751                self.update_restoration_data(cx, |data| {
 2752                    data.selections = inmemory_selections;
 2753                });
 2754
 2755                if WorkspaceSettings::get(None, cx).restore_on_startup
 2756                    != RestoreOnStartupBehavior::None
 2757                {
 2758                    if let Some(workspace_id) =
 2759                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2760                    {
 2761                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2762                        let selections = selections.clone();
 2763                        let background_executor = cx.background_executor().clone();
 2764                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2765                        self.serialize_selections = cx.background_spawn(async move {
 2766                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2767                    let db_selections = selections
 2768                        .iter()
 2769                        .map(|selection| {
 2770                            (
 2771                                selection.start.to_offset(&snapshot),
 2772                                selection.end.to_offset(&snapshot),
 2773                            )
 2774                        })
 2775                        .collect();
 2776
 2777                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2778                        .await
 2779                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2780                        .log_err();
 2781                });
 2782                    }
 2783                }
 2784            }
 2785        }
 2786
 2787        cx.notify();
 2788    }
 2789
 2790    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2791        use text::ToOffset as _;
 2792        use text::ToPoint as _;
 2793
 2794        if self.mode.is_minimap()
 2795            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
 2796        {
 2797            return;
 2798        }
 2799
 2800        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2801            return;
 2802        };
 2803
 2804        let snapshot = singleton.read(cx).snapshot();
 2805        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2806            let display_snapshot = display_map.snapshot(cx);
 2807
 2808            display_snapshot
 2809                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2810                .map(|fold| {
 2811                    fold.range.start.text_anchor.to_point(&snapshot)
 2812                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2813                })
 2814                .collect()
 2815        });
 2816        self.update_restoration_data(cx, |data| {
 2817            data.folds = inmemory_folds;
 2818        });
 2819
 2820        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2821            return;
 2822        };
 2823        let background_executor = cx.background_executor().clone();
 2824        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2825        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2826            display_map
 2827                .snapshot(cx)
 2828                .folds_in_range(0..snapshot.len())
 2829                .map(|fold| {
 2830                    (
 2831                        fold.range.start.text_anchor.to_offset(&snapshot),
 2832                        fold.range.end.text_anchor.to_offset(&snapshot),
 2833                    )
 2834                })
 2835                .collect()
 2836        });
 2837        self.serialize_folds = cx.background_spawn(async move {
 2838            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2839            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2840                .await
 2841                .with_context(|| {
 2842                    format!(
 2843                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2844                    )
 2845                })
 2846                .log_err();
 2847        });
 2848    }
 2849
 2850    pub fn sync_selections(
 2851        &mut self,
 2852        other: Entity<Editor>,
 2853        cx: &mut Context<Self>,
 2854    ) -> gpui::Subscription {
 2855        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2856        self.selections.change_with(cx, |selections| {
 2857            selections.select_anchors(other_selections);
 2858        });
 2859
 2860        let other_subscription =
 2861            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2862                EditorEvent::SelectionsChanged { local: true } => {
 2863                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2864                    if other_selections.is_empty() {
 2865                        return;
 2866                    }
 2867                    this.selections.change_with(cx, |selections| {
 2868                        selections.select_anchors(other_selections);
 2869                    });
 2870                }
 2871                _ => {}
 2872            });
 2873
 2874        let this_subscription =
 2875            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2876                EditorEvent::SelectionsChanged { local: true } => {
 2877                    let these_selections = this.selections.disjoint.to_vec();
 2878                    if these_selections.is_empty() {
 2879                        return;
 2880                    }
 2881                    other.update(cx, |other_editor, cx| {
 2882                        other_editor.selections.change_with(cx, |selections| {
 2883                            selections.select_anchors(these_selections);
 2884                        })
 2885                    });
 2886                }
 2887                _ => {}
 2888            });
 2889
 2890        Subscription::join(other_subscription, this_subscription)
 2891    }
 2892
 2893    pub fn change_selections<R>(
 2894        &mut self,
 2895        autoscroll: Option<Autoscroll>,
 2896        window: &mut Window,
 2897        cx: &mut Context<Self>,
 2898        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2899    ) -> R {
 2900        self.change_selections_inner(autoscroll, true, window, cx, change)
 2901    }
 2902
 2903    fn change_selections_inner<R>(
 2904        &mut self,
 2905        autoscroll: Option<Autoscroll>,
 2906        request_completions: bool,
 2907        window: &mut Window,
 2908        cx: &mut Context<Self>,
 2909        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2910    ) -> R {
 2911        let old_cursor_position = self.selections.newest_anchor().head();
 2912        self.push_to_selection_history();
 2913
 2914        let (changed, result) = self.selections.change_with(cx, change);
 2915
 2916        if changed {
 2917            if let Some(autoscroll) = autoscroll {
 2918                self.request_autoscroll(autoscroll, cx);
 2919            }
 2920            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2921
 2922            if self.should_open_signature_help_automatically(
 2923                &old_cursor_position,
 2924                self.signature_help_state.backspace_pressed(),
 2925                cx,
 2926            ) {
 2927                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2928            }
 2929            self.signature_help_state.set_backspace_pressed(false);
 2930        }
 2931
 2932        result
 2933    }
 2934
 2935    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2936    where
 2937        I: IntoIterator<Item = (Range<S>, T)>,
 2938        S: ToOffset,
 2939        T: Into<Arc<str>>,
 2940    {
 2941        if self.read_only(cx) {
 2942            return;
 2943        }
 2944
 2945        self.buffer
 2946            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2947    }
 2948
 2949    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2950    where
 2951        I: IntoIterator<Item = (Range<S>, T)>,
 2952        S: ToOffset,
 2953        T: Into<Arc<str>>,
 2954    {
 2955        if self.read_only(cx) {
 2956            return;
 2957        }
 2958
 2959        self.buffer.update(cx, |buffer, cx| {
 2960            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2961        });
 2962    }
 2963
 2964    pub fn edit_with_block_indent<I, S, T>(
 2965        &mut self,
 2966        edits: I,
 2967        original_indent_columns: Vec<Option<u32>>,
 2968        cx: &mut Context<Self>,
 2969    ) where
 2970        I: IntoIterator<Item = (Range<S>, T)>,
 2971        S: ToOffset,
 2972        T: Into<Arc<str>>,
 2973    {
 2974        if self.read_only(cx) {
 2975            return;
 2976        }
 2977
 2978        self.buffer.update(cx, |buffer, cx| {
 2979            buffer.edit(
 2980                edits,
 2981                Some(AutoindentMode::Block {
 2982                    original_indent_columns,
 2983                }),
 2984                cx,
 2985            )
 2986        });
 2987    }
 2988
 2989    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2990        self.hide_context_menu(window, cx);
 2991
 2992        match phase {
 2993            SelectPhase::Begin {
 2994                position,
 2995                add,
 2996                click_count,
 2997            } => self.begin_selection(position, add, click_count, window, cx),
 2998            SelectPhase::BeginColumnar {
 2999                position,
 3000                goal_column,
 3001                reset,
 3002            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 3003            SelectPhase::Extend {
 3004                position,
 3005                click_count,
 3006            } => self.extend_selection(position, click_count, window, cx),
 3007            SelectPhase::Update {
 3008                position,
 3009                goal_column,
 3010                scroll_delta,
 3011            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 3012            SelectPhase::End => self.end_selection(window, cx),
 3013        }
 3014    }
 3015
 3016    fn extend_selection(
 3017        &mut self,
 3018        position: DisplayPoint,
 3019        click_count: usize,
 3020        window: &mut Window,
 3021        cx: &mut Context<Self>,
 3022    ) {
 3023        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3024        let tail = self.selections.newest::<usize>(cx).tail();
 3025        self.begin_selection(position, false, click_count, window, cx);
 3026
 3027        let position = position.to_offset(&display_map, Bias::Left);
 3028        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 3029
 3030        let mut pending_selection = self
 3031            .selections
 3032            .pending_anchor()
 3033            .expect("extend_selection not called with pending selection");
 3034        if position >= tail {
 3035            pending_selection.start = tail_anchor;
 3036        } else {
 3037            pending_selection.end = tail_anchor;
 3038            pending_selection.reversed = true;
 3039        }
 3040
 3041        let mut pending_mode = self.selections.pending_mode().unwrap();
 3042        match &mut pending_mode {
 3043            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 3044            _ => {}
 3045        }
 3046
 3047        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 3048
 3049        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 3050            s.set_pending(pending_selection, pending_mode)
 3051        });
 3052    }
 3053
 3054    fn begin_selection(
 3055        &mut self,
 3056        position: DisplayPoint,
 3057        add: bool,
 3058        click_count: usize,
 3059        window: &mut Window,
 3060        cx: &mut Context<Self>,
 3061    ) {
 3062        if !self.focus_handle.is_focused(window) {
 3063            self.last_focused_descendant = None;
 3064            window.focus(&self.focus_handle);
 3065        }
 3066
 3067        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3068        let buffer = &display_map.buffer_snapshot;
 3069        let position = display_map.clip_point(position, Bias::Left);
 3070
 3071        let start;
 3072        let end;
 3073        let mode;
 3074        let mut auto_scroll;
 3075        match click_count {
 3076            1 => {
 3077                start = buffer.anchor_before(position.to_point(&display_map));
 3078                end = start;
 3079                mode = SelectMode::Character;
 3080                auto_scroll = true;
 3081            }
 3082            2 => {
 3083                let range = movement::surrounding_word(&display_map, position);
 3084                start = buffer.anchor_before(range.start.to_point(&display_map));
 3085                end = buffer.anchor_before(range.end.to_point(&display_map));
 3086                mode = SelectMode::Word(start..end);
 3087                auto_scroll = true;
 3088            }
 3089            3 => {
 3090                let position = display_map
 3091                    .clip_point(position, Bias::Left)
 3092                    .to_point(&display_map);
 3093                let line_start = display_map.prev_line_boundary(position).0;
 3094                let next_line_start = buffer.clip_point(
 3095                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3096                    Bias::Left,
 3097                );
 3098                start = buffer.anchor_before(line_start);
 3099                end = buffer.anchor_before(next_line_start);
 3100                mode = SelectMode::Line(start..end);
 3101                auto_scroll = true;
 3102            }
 3103            _ => {
 3104                start = buffer.anchor_before(0);
 3105                end = buffer.anchor_before(buffer.len());
 3106                mode = SelectMode::All;
 3107                auto_scroll = false;
 3108            }
 3109        }
 3110        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3111
 3112        let point_to_delete: Option<usize> = {
 3113            let selected_points: Vec<Selection<Point>> =
 3114                self.selections.disjoint_in_range(start..end, cx);
 3115
 3116            if !add || click_count > 1 {
 3117                None
 3118            } else if !selected_points.is_empty() {
 3119                Some(selected_points[0].id)
 3120            } else {
 3121                let clicked_point_already_selected =
 3122                    self.selections.disjoint.iter().find(|selection| {
 3123                        selection.start.to_point(buffer) == start.to_point(buffer)
 3124                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3125                    });
 3126
 3127                clicked_point_already_selected.map(|selection| selection.id)
 3128            }
 3129        };
 3130
 3131        let selections_count = self.selections.count();
 3132
 3133        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3134            if let Some(point_to_delete) = point_to_delete {
 3135                s.delete(point_to_delete);
 3136
 3137                if selections_count == 1 {
 3138                    s.set_pending_anchor_range(start..end, mode);
 3139                }
 3140            } else {
 3141                if !add {
 3142                    s.clear_disjoint();
 3143                }
 3144
 3145                s.set_pending_anchor_range(start..end, mode);
 3146            }
 3147        });
 3148    }
 3149
 3150    fn begin_columnar_selection(
 3151        &mut self,
 3152        position: DisplayPoint,
 3153        goal_column: u32,
 3154        reset: bool,
 3155        window: &mut Window,
 3156        cx: &mut Context<Self>,
 3157    ) {
 3158        if !self.focus_handle.is_focused(window) {
 3159            self.last_focused_descendant = None;
 3160            window.focus(&self.focus_handle);
 3161        }
 3162
 3163        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3164
 3165        if reset {
 3166            let pointer_position = display_map
 3167                .buffer_snapshot
 3168                .anchor_before(position.to_point(&display_map));
 3169
 3170            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3171                s.clear_disjoint();
 3172                s.set_pending_anchor_range(
 3173                    pointer_position..pointer_position,
 3174                    SelectMode::Character,
 3175                );
 3176            });
 3177        }
 3178
 3179        let tail = self.selections.newest::<Point>(cx).tail();
 3180        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3181
 3182        if !reset {
 3183            self.select_columns(
 3184                tail.to_display_point(&display_map),
 3185                position,
 3186                goal_column,
 3187                &display_map,
 3188                window,
 3189                cx,
 3190            );
 3191        }
 3192    }
 3193
 3194    fn update_selection(
 3195        &mut self,
 3196        position: DisplayPoint,
 3197        goal_column: u32,
 3198        scroll_delta: gpui::Point<f32>,
 3199        window: &mut Window,
 3200        cx: &mut Context<Self>,
 3201    ) {
 3202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3203
 3204        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3205            let tail = tail.to_display_point(&display_map);
 3206            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3207        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3208            let buffer = self.buffer.read(cx).snapshot(cx);
 3209            let head;
 3210            let tail;
 3211            let mode = self.selections.pending_mode().unwrap();
 3212            match &mode {
 3213                SelectMode::Character => {
 3214                    head = position.to_point(&display_map);
 3215                    tail = pending.tail().to_point(&buffer);
 3216                }
 3217                SelectMode::Word(original_range) => {
 3218                    let original_display_range = original_range.start.to_display_point(&display_map)
 3219                        ..original_range.end.to_display_point(&display_map);
 3220                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3221                        ..original_display_range.end.to_point(&display_map);
 3222                    if movement::is_inside_word(&display_map, position)
 3223                        || original_display_range.contains(&position)
 3224                    {
 3225                        let word_range = movement::surrounding_word(&display_map, position);
 3226                        if word_range.start < original_display_range.start {
 3227                            head = word_range.start.to_point(&display_map);
 3228                        } else {
 3229                            head = word_range.end.to_point(&display_map);
 3230                        }
 3231                    } else {
 3232                        head = position.to_point(&display_map);
 3233                    }
 3234
 3235                    if head <= original_buffer_range.start {
 3236                        tail = original_buffer_range.end;
 3237                    } else {
 3238                        tail = original_buffer_range.start;
 3239                    }
 3240                }
 3241                SelectMode::Line(original_range) => {
 3242                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3243
 3244                    let position = display_map
 3245                        .clip_point(position, Bias::Left)
 3246                        .to_point(&display_map);
 3247                    let line_start = display_map.prev_line_boundary(position).0;
 3248                    let next_line_start = buffer.clip_point(
 3249                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3250                        Bias::Left,
 3251                    );
 3252
 3253                    if line_start < original_range.start {
 3254                        head = line_start
 3255                    } else {
 3256                        head = next_line_start
 3257                    }
 3258
 3259                    if head <= original_range.start {
 3260                        tail = original_range.end;
 3261                    } else {
 3262                        tail = original_range.start;
 3263                    }
 3264                }
 3265                SelectMode::All => {
 3266                    return;
 3267                }
 3268            };
 3269
 3270            if head < tail {
 3271                pending.start = buffer.anchor_before(head);
 3272                pending.end = buffer.anchor_before(tail);
 3273                pending.reversed = true;
 3274            } else {
 3275                pending.start = buffer.anchor_before(tail);
 3276                pending.end = buffer.anchor_before(head);
 3277                pending.reversed = false;
 3278            }
 3279
 3280            self.change_selections(None, window, cx, |s| {
 3281                s.set_pending(pending, mode);
 3282            });
 3283        } else {
 3284            log::error!("update_selection dispatched with no pending selection");
 3285            return;
 3286        }
 3287
 3288        self.apply_scroll_delta(scroll_delta, window, cx);
 3289        cx.notify();
 3290    }
 3291
 3292    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3293        self.columnar_selection_tail.take();
 3294        if self.selections.pending_anchor().is_some() {
 3295            let selections = self.selections.all::<usize>(cx);
 3296            self.change_selections(None, window, cx, |s| {
 3297                s.select(selections);
 3298                s.clear_pending();
 3299            });
 3300        }
 3301    }
 3302
 3303    fn select_columns(
 3304        &mut self,
 3305        tail: DisplayPoint,
 3306        head: DisplayPoint,
 3307        goal_column: u32,
 3308        display_map: &DisplaySnapshot,
 3309        window: &mut Window,
 3310        cx: &mut Context<Self>,
 3311    ) {
 3312        let start_row = cmp::min(tail.row(), head.row());
 3313        let end_row = cmp::max(tail.row(), head.row());
 3314        let start_column = cmp::min(tail.column(), goal_column);
 3315        let end_column = cmp::max(tail.column(), goal_column);
 3316        let reversed = start_column < tail.column();
 3317
 3318        let selection_ranges = (start_row.0..=end_row.0)
 3319            .map(DisplayRow)
 3320            .filter_map(|row| {
 3321                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3322                    let start = display_map
 3323                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3324                        .to_point(display_map);
 3325                    let end = display_map
 3326                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3327                        .to_point(display_map);
 3328                    if reversed {
 3329                        Some(end..start)
 3330                    } else {
 3331                        Some(start..end)
 3332                    }
 3333                } else {
 3334                    None
 3335                }
 3336            })
 3337            .collect::<Vec<_>>();
 3338
 3339        self.change_selections(None, window, cx, |s| {
 3340            s.select_ranges(selection_ranges);
 3341        });
 3342        cx.notify();
 3343    }
 3344
 3345    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3346        self.selections
 3347            .all_adjusted(cx)
 3348            .iter()
 3349            .any(|selection| !selection.is_empty())
 3350    }
 3351
 3352    pub fn has_pending_nonempty_selection(&self) -> bool {
 3353        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3354            Some(Selection { start, end, .. }) => start != end,
 3355            None => false,
 3356        };
 3357
 3358        pending_nonempty_selection
 3359            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3360    }
 3361
 3362    pub fn has_pending_selection(&self) -> bool {
 3363        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3364    }
 3365
 3366    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3367        self.selection_mark_mode = false;
 3368
 3369        if self.clear_expanded_diff_hunks(cx) {
 3370            cx.notify();
 3371            return;
 3372        }
 3373        if self.dismiss_menus_and_popups(true, window, cx) {
 3374            return;
 3375        }
 3376
 3377        if self.mode.is_full()
 3378            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3379        {
 3380            return;
 3381        }
 3382
 3383        cx.propagate();
 3384    }
 3385
 3386    pub fn dismiss_menus_and_popups(
 3387        &mut self,
 3388        is_user_requested: bool,
 3389        window: &mut Window,
 3390        cx: &mut Context<Self>,
 3391    ) -> bool {
 3392        if self.take_rename(false, window, cx).is_some() {
 3393            return true;
 3394        }
 3395
 3396        if hide_hover(self, cx) {
 3397            return true;
 3398        }
 3399
 3400        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3401            return true;
 3402        }
 3403
 3404        if self.hide_context_menu(window, cx).is_some() {
 3405            return true;
 3406        }
 3407
 3408        if self.mouse_context_menu.take().is_some() {
 3409            return true;
 3410        }
 3411
 3412        if is_user_requested && self.discard_inline_completion(true, cx) {
 3413            return true;
 3414        }
 3415
 3416        if self.snippet_stack.pop().is_some() {
 3417            return true;
 3418        }
 3419
 3420        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3421            self.dismiss_diagnostics(cx);
 3422            return true;
 3423        }
 3424
 3425        false
 3426    }
 3427
 3428    fn linked_editing_ranges_for(
 3429        &self,
 3430        selection: Range<text::Anchor>,
 3431        cx: &App,
 3432    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3433        if self.linked_edit_ranges.is_empty() {
 3434            return None;
 3435        }
 3436        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3437            selection.end.buffer_id.and_then(|end_buffer_id| {
 3438                if selection.start.buffer_id != Some(end_buffer_id) {
 3439                    return None;
 3440                }
 3441                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3442                let snapshot = buffer.read(cx).snapshot();
 3443                self.linked_edit_ranges
 3444                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3445                    .map(|ranges| (ranges, snapshot, buffer))
 3446            })?;
 3447        use text::ToOffset as TO;
 3448        // find offset from the start of current range to current cursor position
 3449        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3450
 3451        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3452        let start_difference = start_offset - start_byte_offset;
 3453        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3454        let end_difference = end_offset - start_byte_offset;
 3455        // Current range has associated linked ranges.
 3456        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3457        for range in linked_ranges.iter() {
 3458            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3459            let end_offset = start_offset + end_difference;
 3460            let start_offset = start_offset + start_difference;
 3461            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3462                continue;
 3463            }
 3464            if self.selections.disjoint_anchor_ranges().any(|s| {
 3465                if s.start.buffer_id != selection.start.buffer_id
 3466                    || s.end.buffer_id != selection.end.buffer_id
 3467                {
 3468                    return false;
 3469                }
 3470                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3471                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3472            }) {
 3473                continue;
 3474            }
 3475            let start = buffer_snapshot.anchor_after(start_offset);
 3476            let end = buffer_snapshot.anchor_after(end_offset);
 3477            linked_edits
 3478                .entry(buffer.clone())
 3479                .or_default()
 3480                .push(start..end);
 3481        }
 3482        Some(linked_edits)
 3483    }
 3484
 3485    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3486        let text: Arc<str> = text.into();
 3487
 3488        if self.read_only(cx) {
 3489            return;
 3490        }
 3491
 3492        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3493
 3494        let selections = self.selections.all_adjusted(cx);
 3495        let mut bracket_inserted = false;
 3496        let mut edits = Vec::new();
 3497        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3498        let mut new_selections = Vec::with_capacity(selections.len());
 3499        let mut new_autoclose_regions = Vec::new();
 3500        let snapshot = self.buffer.read(cx).read(cx);
 3501        let mut clear_linked_edit_ranges = false;
 3502
 3503        for (selection, autoclose_region) in
 3504            self.selections_with_autoclose_regions(selections, &snapshot)
 3505        {
 3506            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3507                // Determine if the inserted text matches the opening or closing
 3508                // bracket of any of this language's bracket pairs.
 3509                let mut bracket_pair = None;
 3510                let mut is_bracket_pair_start = false;
 3511                let mut is_bracket_pair_end = false;
 3512                if !text.is_empty() {
 3513                    let mut bracket_pair_matching_end = None;
 3514                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3515                    //  and they are removing the character that triggered IME popup.
 3516                    for (pair, enabled) in scope.brackets() {
 3517                        if !pair.close && !pair.surround {
 3518                            continue;
 3519                        }
 3520
 3521                        if enabled && pair.start.ends_with(text.as_ref()) {
 3522                            let prefix_len = pair.start.len() - text.len();
 3523                            let preceding_text_matches_prefix = prefix_len == 0
 3524                                || (selection.start.column >= (prefix_len as u32)
 3525                                    && snapshot.contains_str_at(
 3526                                        Point::new(
 3527                                            selection.start.row,
 3528                                            selection.start.column - (prefix_len as u32),
 3529                                        ),
 3530                                        &pair.start[..prefix_len],
 3531                                    ));
 3532                            if preceding_text_matches_prefix {
 3533                                bracket_pair = Some(pair.clone());
 3534                                is_bracket_pair_start = true;
 3535                                break;
 3536                            }
 3537                        }
 3538                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3539                        {
 3540                            // take first bracket pair matching end, but don't break in case a later bracket
 3541                            // pair matches start
 3542                            bracket_pair_matching_end = Some(pair.clone());
 3543                        }
 3544                    }
 3545                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3546                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3547                        is_bracket_pair_end = true;
 3548                    }
 3549                }
 3550
 3551                if let Some(bracket_pair) = bracket_pair {
 3552                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3553                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3554                    let auto_surround =
 3555                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3556                    if selection.is_empty() {
 3557                        if is_bracket_pair_start {
 3558                            // If the inserted text is a suffix of an opening bracket and the
 3559                            // selection is preceded by the rest of the opening bracket, then
 3560                            // insert the closing bracket.
 3561                            let following_text_allows_autoclose = snapshot
 3562                                .chars_at(selection.start)
 3563                                .next()
 3564                                .map_or(true, |c| scope.should_autoclose_before(c));
 3565
 3566                            let preceding_text_allows_autoclose = selection.start.column == 0
 3567                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3568                                    true,
 3569                                    |c| {
 3570                                        bracket_pair.start != bracket_pair.end
 3571                                            || !snapshot
 3572                                                .char_classifier_at(selection.start)
 3573                                                .is_word(c)
 3574                                    },
 3575                                );
 3576
 3577                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3578                                && bracket_pair.start.len() == 1
 3579                            {
 3580                                let target = bracket_pair.start.chars().next().unwrap();
 3581                                let current_line_count = snapshot
 3582                                    .reversed_chars_at(selection.start)
 3583                                    .take_while(|&c| c != '\n')
 3584                                    .filter(|&c| c == target)
 3585                                    .count();
 3586                                current_line_count % 2 == 1
 3587                            } else {
 3588                                false
 3589                            };
 3590
 3591                            if autoclose
 3592                                && bracket_pair.close
 3593                                && following_text_allows_autoclose
 3594                                && preceding_text_allows_autoclose
 3595                                && !is_closing_quote
 3596                            {
 3597                                let anchor = snapshot.anchor_before(selection.end);
 3598                                new_selections.push((selection.map(|_| anchor), text.len()));
 3599                                new_autoclose_regions.push((
 3600                                    anchor,
 3601                                    text.len(),
 3602                                    selection.id,
 3603                                    bracket_pair.clone(),
 3604                                ));
 3605                                edits.push((
 3606                                    selection.range(),
 3607                                    format!("{}{}", text, bracket_pair.end).into(),
 3608                                ));
 3609                                bracket_inserted = true;
 3610                                continue;
 3611                            }
 3612                        }
 3613
 3614                        if let Some(region) = autoclose_region {
 3615                            // If the selection is followed by an auto-inserted closing bracket,
 3616                            // then don't insert that closing bracket again; just move the selection
 3617                            // past the closing bracket.
 3618                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3619                                && text.as_ref() == region.pair.end.as_str();
 3620                            if should_skip {
 3621                                let anchor = snapshot.anchor_after(selection.end);
 3622                                new_selections
 3623                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3624                                continue;
 3625                            }
 3626                        }
 3627
 3628                        let always_treat_brackets_as_autoclosed = snapshot
 3629                            .language_settings_at(selection.start, cx)
 3630                            .always_treat_brackets_as_autoclosed;
 3631                        if always_treat_brackets_as_autoclosed
 3632                            && is_bracket_pair_end
 3633                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3634                        {
 3635                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3636                            // and the inserted text is a closing bracket and the selection is followed
 3637                            // by the closing bracket then move the selection past the closing bracket.
 3638                            let anchor = snapshot.anchor_after(selection.end);
 3639                            new_selections.push((selection.map(|_| anchor), text.len()));
 3640                            continue;
 3641                        }
 3642                    }
 3643                    // If an opening bracket is 1 character long and is typed while
 3644                    // text is selected, then surround that text with the bracket pair.
 3645                    else if auto_surround
 3646                        && bracket_pair.surround
 3647                        && is_bracket_pair_start
 3648                        && bracket_pair.start.chars().count() == 1
 3649                    {
 3650                        edits.push((selection.start..selection.start, text.clone()));
 3651                        edits.push((
 3652                            selection.end..selection.end,
 3653                            bracket_pair.end.as_str().into(),
 3654                        ));
 3655                        bracket_inserted = true;
 3656                        new_selections.push((
 3657                            Selection {
 3658                                id: selection.id,
 3659                                start: snapshot.anchor_after(selection.start),
 3660                                end: snapshot.anchor_before(selection.end),
 3661                                reversed: selection.reversed,
 3662                                goal: selection.goal,
 3663                            },
 3664                            0,
 3665                        ));
 3666                        continue;
 3667                    }
 3668                }
 3669            }
 3670
 3671            if self.auto_replace_emoji_shortcode
 3672                && selection.is_empty()
 3673                && text.as_ref().ends_with(':')
 3674            {
 3675                if let Some(possible_emoji_short_code) =
 3676                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3677                {
 3678                    if !possible_emoji_short_code.is_empty() {
 3679                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3680                            let emoji_shortcode_start = Point::new(
 3681                                selection.start.row,
 3682                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3683                            );
 3684
 3685                            // Remove shortcode from buffer
 3686                            edits.push((
 3687                                emoji_shortcode_start..selection.start,
 3688                                "".to_string().into(),
 3689                            ));
 3690                            new_selections.push((
 3691                                Selection {
 3692                                    id: selection.id,
 3693                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3694                                    end: snapshot.anchor_before(selection.start),
 3695                                    reversed: selection.reversed,
 3696                                    goal: selection.goal,
 3697                                },
 3698                                0,
 3699                            ));
 3700
 3701                            // Insert emoji
 3702                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3703                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3704                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3705
 3706                            continue;
 3707                        }
 3708                    }
 3709                }
 3710            }
 3711
 3712            // If not handling any auto-close operation, then just replace the selected
 3713            // text with the given input and move the selection to the end of the
 3714            // newly inserted text.
 3715            let anchor = snapshot.anchor_after(selection.end);
 3716            if !self.linked_edit_ranges.is_empty() {
 3717                let start_anchor = snapshot.anchor_before(selection.start);
 3718
 3719                let is_word_char = text.chars().next().map_or(true, |char| {
 3720                    let classifier = snapshot
 3721                        .char_classifier_at(start_anchor.to_offset(&snapshot))
 3722                        .ignore_punctuation(true);
 3723                    classifier.is_word(char)
 3724                });
 3725
 3726                if is_word_char {
 3727                    if let Some(ranges) = self
 3728                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3729                    {
 3730                        for (buffer, edits) in ranges {
 3731                            linked_edits
 3732                                .entry(buffer.clone())
 3733                                .or_default()
 3734                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3735                        }
 3736                    }
 3737                } else {
 3738                    clear_linked_edit_ranges = true;
 3739                }
 3740            }
 3741
 3742            new_selections.push((selection.map(|_| anchor), 0));
 3743            edits.push((selection.start..selection.end, text.clone()));
 3744        }
 3745
 3746        drop(snapshot);
 3747
 3748        self.transact(window, cx, |this, window, cx| {
 3749            if clear_linked_edit_ranges {
 3750                this.linked_edit_ranges.clear();
 3751            }
 3752            let initial_buffer_versions =
 3753                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3754
 3755            this.buffer.update(cx, |buffer, cx| {
 3756                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3757            });
 3758            for (buffer, edits) in linked_edits {
 3759                buffer.update(cx, |buffer, cx| {
 3760                    let snapshot = buffer.snapshot();
 3761                    let edits = edits
 3762                        .into_iter()
 3763                        .map(|(range, text)| {
 3764                            use text::ToPoint as TP;
 3765                            let end_point = TP::to_point(&range.end, &snapshot);
 3766                            let start_point = TP::to_point(&range.start, &snapshot);
 3767                            (start_point..end_point, text)
 3768                        })
 3769                        .sorted_by_key(|(range, _)| range.start);
 3770                    buffer.edit(edits, None, cx);
 3771                })
 3772            }
 3773            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3774            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3775            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3776            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3777                .zip(new_selection_deltas)
 3778                .map(|(selection, delta)| Selection {
 3779                    id: selection.id,
 3780                    start: selection.start + delta,
 3781                    end: selection.end + delta,
 3782                    reversed: selection.reversed,
 3783                    goal: SelectionGoal::None,
 3784                })
 3785                .collect::<Vec<_>>();
 3786
 3787            let mut i = 0;
 3788            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3789                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3790                let start = map.buffer_snapshot.anchor_before(position);
 3791                let end = map.buffer_snapshot.anchor_after(position);
 3792                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3793                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3794                        Ordering::Less => i += 1,
 3795                        Ordering::Greater => break,
 3796                        Ordering::Equal => {
 3797                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3798                                Ordering::Less => i += 1,
 3799                                Ordering::Equal => break,
 3800                                Ordering::Greater => break,
 3801                            }
 3802                        }
 3803                    }
 3804                }
 3805                this.autoclose_regions.insert(
 3806                    i,
 3807                    AutocloseRegion {
 3808                        selection_id,
 3809                        range: start..end,
 3810                        pair,
 3811                    },
 3812                );
 3813            }
 3814
 3815            let had_active_inline_completion = this.has_active_inline_completion();
 3816            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3817                s.select(new_selections)
 3818            });
 3819
 3820            if !bracket_inserted {
 3821                if let Some(on_type_format_task) =
 3822                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3823                {
 3824                    on_type_format_task.detach_and_log_err(cx);
 3825                }
 3826            }
 3827
 3828            let editor_settings = EditorSettings::get_global(cx);
 3829            if bracket_inserted
 3830                && (editor_settings.auto_signature_help
 3831                    || editor_settings.show_signature_help_after_edits)
 3832            {
 3833                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3834            }
 3835
 3836            let trigger_in_words =
 3837                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3838            if this.hard_wrap.is_some() {
 3839                let latest: Range<Point> = this.selections.newest(cx).range();
 3840                if latest.is_empty()
 3841                    && this
 3842                        .buffer()
 3843                        .read(cx)
 3844                        .snapshot(cx)
 3845                        .line_len(MultiBufferRow(latest.start.row))
 3846                        == latest.start.column
 3847                {
 3848                    this.rewrap_impl(
 3849                        RewrapOptions {
 3850                            override_language_settings: true,
 3851                            preserve_existing_whitespace: true,
 3852                        },
 3853                        cx,
 3854                    )
 3855                }
 3856            }
 3857            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3858            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3859            this.refresh_inline_completion(true, false, window, cx);
 3860            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3861        });
 3862    }
 3863
 3864    fn find_possible_emoji_shortcode_at_position(
 3865        snapshot: &MultiBufferSnapshot,
 3866        position: Point,
 3867    ) -> Option<String> {
 3868        let mut chars = Vec::new();
 3869        let mut found_colon = false;
 3870        for char in snapshot.reversed_chars_at(position).take(100) {
 3871            // Found a possible emoji shortcode in the middle of the buffer
 3872            if found_colon {
 3873                if char.is_whitespace() {
 3874                    chars.reverse();
 3875                    return Some(chars.iter().collect());
 3876                }
 3877                // If the previous character is not a whitespace, we are in the middle of a word
 3878                // and we only want to complete the shortcode if the word is made up of other emojis
 3879                let mut containing_word = String::new();
 3880                for ch in snapshot
 3881                    .reversed_chars_at(position)
 3882                    .skip(chars.len() + 1)
 3883                    .take(100)
 3884                {
 3885                    if ch.is_whitespace() {
 3886                        break;
 3887                    }
 3888                    containing_word.push(ch);
 3889                }
 3890                let containing_word = containing_word.chars().rev().collect::<String>();
 3891                if util::word_consists_of_emojis(containing_word.as_str()) {
 3892                    chars.reverse();
 3893                    return Some(chars.iter().collect());
 3894                }
 3895            }
 3896
 3897            if char.is_whitespace() || !char.is_ascii() {
 3898                return None;
 3899            }
 3900            if char == ':' {
 3901                found_colon = true;
 3902            } else {
 3903                chars.push(char);
 3904            }
 3905        }
 3906        // Found a possible emoji shortcode at the beginning of the buffer
 3907        chars.reverse();
 3908        Some(chars.iter().collect())
 3909    }
 3910
 3911    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3912        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3913        self.transact(window, cx, |this, window, cx| {
 3914            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3915                let selections = this.selections.all::<usize>(cx);
 3916                let multi_buffer = this.buffer.read(cx);
 3917                let buffer = multi_buffer.snapshot(cx);
 3918                selections
 3919                    .iter()
 3920                    .map(|selection| {
 3921                        let start_point = selection.start.to_point(&buffer);
 3922                        let mut indent =
 3923                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3924                        indent.len = cmp::min(indent.len, start_point.column);
 3925                        let start = selection.start;
 3926                        let end = selection.end;
 3927                        let selection_is_empty = start == end;
 3928                        let language_scope = buffer.language_scope_at(start);
 3929                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3930                            &language_scope
 3931                        {
 3932                            let insert_extra_newline =
 3933                                insert_extra_newline_brackets(&buffer, start..end, language)
 3934                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3935
 3936                            // Comment extension on newline is allowed only for cursor selections
 3937                            let comment_delimiter = maybe!({
 3938                                if !selection_is_empty {
 3939                                    return None;
 3940                                }
 3941
 3942                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3943                                    return None;
 3944                                }
 3945
 3946                                let delimiters = language.line_comment_prefixes();
 3947                                let max_len_of_delimiter =
 3948                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3949                                let (snapshot, range) =
 3950                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3951
 3952                                let mut index_of_first_non_whitespace = 0;
 3953                                let comment_candidate = snapshot
 3954                                    .chars_for_range(range)
 3955                                    .skip_while(|c| {
 3956                                        let should_skip = c.is_whitespace();
 3957                                        if should_skip {
 3958                                            index_of_first_non_whitespace += 1;
 3959                                        }
 3960                                        should_skip
 3961                                    })
 3962                                    .take(max_len_of_delimiter)
 3963                                    .collect::<String>();
 3964                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3965                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3966                                })?;
 3967                                let cursor_is_placed_after_comment_marker =
 3968                                    index_of_first_non_whitespace + comment_prefix.len()
 3969                                        <= start_point.column as usize;
 3970                                if cursor_is_placed_after_comment_marker {
 3971                                    Some(comment_prefix.clone())
 3972                                } else {
 3973                                    None
 3974                                }
 3975                            });
 3976                            (comment_delimiter, insert_extra_newline)
 3977                        } else {
 3978                            (None, false)
 3979                        };
 3980
 3981                        let capacity_for_delimiter = comment_delimiter
 3982                            .as_deref()
 3983                            .map(str::len)
 3984                            .unwrap_or_default();
 3985                        let mut new_text =
 3986                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3987                        new_text.push('\n');
 3988                        new_text.extend(indent.chars());
 3989                        if let Some(delimiter) = &comment_delimiter {
 3990                            new_text.push_str(delimiter);
 3991                        }
 3992                        if insert_extra_newline {
 3993                            new_text = new_text.repeat(2);
 3994                        }
 3995
 3996                        let anchor = buffer.anchor_after(end);
 3997                        let new_selection = selection.map(|_| anchor);
 3998                        (
 3999                            (start..end, new_text),
 4000                            (insert_extra_newline, new_selection),
 4001                        )
 4002                    })
 4003                    .unzip()
 4004            };
 4005
 4006            this.edit_with_autoindent(edits, cx);
 4007            let buffer = this.buffer.read(cx).snapshot(cx);
 4008            let new_selections = selection_fixup_info
 4009                .into_iter()
 4010                .map(|(extra_newline_inserted, new_selection)| {
 4011                    let mut cursor = new_selection.end.to_point(&buffer);
 4012                    if extra_newline_inserted {
 4013                        cursor.row -= 1;
 4014                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 4015                    }
 4016                    new_selection.map(|_| cursor)
 4017                })
 4018                .collect();
 4019
 4020            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4021                s.select(new_selections)
 4022            });
 4023            this.refresh_inline_completion(true, false, window, cx);
 4024        });
 4025    }
 4026
 4027    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 4028        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4029
 4030        let buffer = self.buffer.read(cx);
 4031        let snapshot = buffer.snapshot(cx);
 4032
 4033        let mut edits = Vec::new();
 4034        let mut rows = Vec::new();
 4035
 4036        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 4037            let cursor = selection.head();
 4038            let row = cursor.row;
 4039
 4040            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 4041
 4042            let newline = "\n".to_string();
 4043            edits.push((start_of_line..start_of_line, newline));
 4044
 4045            rows.push(row + rows_inserted as u32);
 4046        }
 4047
 4048        self.transact(window, cx, |editor, window, cx| {
 4049            editor.edit(edits, cx);
 4050
 4051            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4052                let mut index = 0;
 4053                s.move_cursors_with(|map, _, _| {
 4054                    let row = rows[index];
 4055                    index += 1;
 4056
 4057                    let point = Point::new(row, 0);
 4058                    let boundary = map.next_line_boundary(point).1;
 4059                    let clipped = map.clip_point(boundary, Bias::Left);
 4060
 4061                    (clipped, SelectionGoal::None)
 4062                });
 4063            });
 4064
 4065            let mut indent_edits = Vec::new();
 4066            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4067            for row in rows {
 4068                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4069                for (row, indent) in indents {
 4070                    if indent.len == 0 {
 4071                        continue;
 4072                    }
 4073
 4074                    let text = match indent.kind {
 4075                        IndentKind::Space => " ".repeat(indent.len as usize),
 4076                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4077                    };
 4078                    let point = Point::new(row.0, 0);
 4079                    indent_edits.push((point..point, text));
 4080                }
 4081            }
 4082            editor.edit(indent_edits, cx);
 4083        });
 4084    }
 4085
 4086    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 4087        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4088
 4089        let buffer = self.buffer.read(cx);
 4090        let snapshot = buffer.snapshot(cx);
 4091
 4092        let mut edits = Vec::new();
 4093        let mut rows = Vec::new();
 4094        let mut rows_inserted = 0;
 4095
 4096        for selection in self.selections.all_adjusted(cx) {
 4097            let cursor = selection.head();
 4098            let row = cursor.row;
 4099
 4100            let point = Point::new(row + 1, 0);
 4101            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4102
 4103            let newline = "\n".to_string();
 4104            edits.push((start_of_line..start_of_line, newline));
 4105
 4106            rows_inserted += 1;
 4107            rows.push(row + rows_inserted);
 4108        }
 4109
 4110        self.transact(window, cx, |editor, window, cx| {
 4111            editor.edit(edits, cx);
 4112
 4113            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4114                let mut index = 0;
 4115                s.move_cursors_with(|map, _, _| {
 4116                    let row = rows[index];
 4117                    index += 1;
 4118
 4119                    let point = Point::new(row, 0);
 4120                    let boundary = map.next_line_boundary(point).1;
 4121                    let clipped = map.clip_point(boundary, Bias::Left);
 4122
 4123                    (clipped, SelectionGoal::None)
 4124                });
 4125            });
 4126
 4127            let mut indent_edits = Vec::new();
 4128            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4129            for row in rows {
 4130                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4131                for (row, indent) in indents {
 4132                    if indent.len == 0 {
 4133                        continue;
 4134                    }
 4135
 4136                    let text = match indent.kind {
 4137                        IndentKind::Space => " ".repeat(indent.len as usize),
 4138                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4139                    };
 4140                    let point = Point::new(row.0, 0);
 4141                    indent_edits.push((point..point, text));
 4142                }
 4143            }
 4144            editor.edit(indent_edits, cx);
 4145        });
 4146    }
 4147
 4148    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4149        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4150            original_indent_columns: Vec::new(),
 4151        });
 4152        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4153    }
 4154
 4155    fn insert_with_autoindent_mode(
 4156        &mut self,
 4157        text: &str,
 4158        autoindent_mode: Option<AutoindentMode>,
 4159        window: &mut Window,
 4160        cx: &mut Context<Self>,
 4161    ) {
 4162        if self.read_only(cx) {
 4163            return;
 4164        }
 4165
 4166        let text: Arc<str> = text.into();
 4167        self.transact(window, cx, |this, window, cx| {
 4168            let old_selections = this.selections.all_adjusted(cx);
 4169            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4170                let anchors = {
 4171                    let snapshot = buffer.read(cx);
 4172                    old_selections
 4173                        .iter()
 4174                        .map(|s| {
 4175                            let anchor = snapshot.anchor_after(s.head());
 4176                            s.map(|_| anchor)
 4177                        })
 4178                        .collect::<Vec<_>>()
 4179                };
 4180                buffer.edit(
 4181                    old_selections
 4182                        .iter()
 4183                        .map(|s| (s.start..s.end, text.clone())),
 4184                    autoindent_mode,
 4185                    cx,
 4186                );
 4187                anchors
 4188            });
 4189
 4190            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4191                s.select_anchors(selection_anchors);
 4192            });
 4193
 4194            cx.notify();
 4195        });
 4196    }
 4197
 4198    fn trigger_completion_on_input(
 4199        &mut self,
 4200        text: &str,
 4201        trigger_in_words: bool,
 4202        window: &mut Window,
 4203        cx: &mut Context<Self>,
 4204    ) {
 4205        let ignore_completion_provider = self
 4206            .context_menu
 4207            .borrow()
 4208            .as_ref()
 4209            .map(|menu| match menu {
 4210                CodeContextMenu::Completions(completions_menu) => {
 4211                    completions_menu.ignore_completion_provider
 4212                }
 4213                CodeContextMenu::CodeActions(_) => false,
 4214            })
 4215            .unwrap_or(false);
 4216
 4217        if ignore_completion_provider {
 4218            self.show_word_completions(&ShowWordCompletions, window, cx);
 4219        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4220            self.show_completions(
 4221                &ShowCompletions {
 4222                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4223                },
 4224                window,
 4225                cx,
 4226            );
 4227        } else {
 4228            self.hide_context_menu(window, cx);
 4229        }
 4230    }
 4231
 4232    fn is_completion_trigger(
 4233        &self,
 4234        text: &str,
 4235        trigger_in_words: bool,
 4236        cx: &mut Context<Self>,
 4237    ) -> bool {
 4238        let position = self.selections.newest_anchor().head();
 4239        let multibuffer = self.buffer.read(cx);
 4240        let Some(buffer) = position
 4241            .buffer_id
 4242            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4243        else {
 4244            return false;
 4245        };
 4246
 4247        if let Some(completion_provider) = &self.completion_provider {
 4248            completion_provider.is_completion_trigger(
 4249                &buffer,
 4250                position.text_anchor,
 4251                text,
 4252                trigger_in_words,
 4253                cx,
 4254            )
 4255        } else {
 4256            false
 4257        }
 4258    }
 4259
 4260    /// If any empty selections is touching the start of its innermost containing autoclose
 4261    /// region, expand it to select the brackets.
 4262    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4263        let selections = self.selections.all::<usize>(cx);
 4264        let buffer = self.buffer.read(cx).read(cx);
 4265        let new_selections = self
 4266            .selections_with_autoclose_regions(selections, &buffer)
 4267            .map(|(mut selection, region)| {
 4268                if !selection.is_empty() {
 4269                    return selection;
 4270                }
 4271
 4272                if let Some(region) = region {
 4273                    let mut range = region.range.to_offset(&buffer);
 4274                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4275                        range.start -= region.pair.start.len();
 4276                        if buffer.contains_str_at(range.start, &region.pair.start)
 4277                            && buffer.contains_str_at(range.end, &region.pair.end)
 4278                        {
 4279                            range.end += region.pair.end.len();
 4280                            selection.start = range.start;
 4281                            selection.end = range.end;
 4282
 4283                            return selection;
 4284                        }
 4285                    }
 4286                }
 4287
 4288                let always_treat_brackets_as_autoclosed = buffer
 4289                    .language_settings_at(selection.start, cx)
 4290                    .always_treat_brackets_as_autoclosed;
 4291
 4292                if !always_treat_brackets_as_autoclosed {
 4293                    return selection;
 4294                }
 4295
 4296                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4297                    for (pair, enabled) in scope.brackets() {
 4298                        if !enabled || !pair.close {
 4299                            continue;
 4300                        }
 4301
 4302                        if buffer.contains_str_at(selection.start, &pair.end) {
 4303                            let pair_start_len = pair.start.len();
 4304                            if buffer.contains_str_at(
 4305                                selection.start.saturating_sub(pair_start_len),
 4306                                &pair.start,
 4307                            ) {
 4308                                selection.start -= pair_start_len;
 4309                                selection.end += pair.end.len();
 4310
 4311                                return selection;
 4312                            }
 4313                        }
 4314                    }
 4315                }
 4316
 4317                selection
 4318            })
 4319            .collect();
 4320
 4321        drop(buffer);
 4322        self.change_selections(None, window, cx, |selections| {
 4323            selections.select(new_selections)
 4324        });
 4325    }
 4326
 4327    /// Iterate the given selections, and for each one, find the smallest surrounding
 4328    /// autoclose region. This uses the ordering of the selections and the autoclose
 4329    /// regions to avoid repeated comparisons.
 4330    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4331        &'a self,
 4332        selections: impl IntoIterator<Item = Selection<D>>,
 4333        buffer: &'a MultiBufferSnapshot,
 4334    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4335        let mut i = 0;
 4336        let mut regions = self.autoclose_regions.as_slice();
 4337        selections.into_iter().map(move |selection| {
 4338            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4339
 4340            let mut enclosing = None;
 4341            while let Some(pair_state) = regions.get(i) {
 4342                if pair_state.range.end.to_offset(buffer) < range.start {
 4343                    regions = &regions[i + 1..];
 4344                    i = 0;
 4345                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4346                    break;
 4347                } else {
 4348                    if pair_state.selection_id == selection.id {
 4349                        enclosing = Some(pair_state);
 4350                    }
 4351                    i += 1;
 4352                }
 4353            }
 4354
 4355            (selection, enclosing)
 4356        })
 4357    }
 4358
 4359    /// Remove any autoclose regions that no longer contain their selection.
 4360    fn invalidate_autoclose_regions(
 4361        &mut self,
 4362        mut selections: &[Selection<Anchor>],
 4363        buffer: &MultiBufferSnapshot,
 4364    ) {
 4365        self.autoclose_regions.retain(|state| {
 4366            let mut i = 0;
 4367            while let Some(selection) = selections.get(i) {
 4368                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4369                    selections = &selections[1..];
 4370                    continue;
 4371                }
 4372                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4373                    break;
 4374                }
 4375                if selection.id == state.selection_id {
 4376                    return true;
 4377                } else {
 4378                    i += 1;
 4379                }
 4380            }
 4381            false
 4382        });
 4383    }
 4384
 4385    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4386        let offset = position.to_offset(buffer);
 4387        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4388        if offset > word_range.start && kind == Some(CharKind::Word) {
 4389            Some(
 4390                buffer
 4391                    .text_for_range(word_range.start..offset)
 4392                    .collect::<String>(),
 4393            )
 4394        } else {
 4395            None
 4396        }
 4397    }
 4398
 4399    pub fn toggle_inline_values(
 4400        &mut self,
 4401        _: &ToggleInlineValues,
 4402        _: &mut Window,
 4403        cx: &mut Context<Self>,
 4404    ) {
 4405        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4406
 4407        self.refresh_inline_values(cx);
 4408    }
 4409
 4410    pub fn toggle_inlay_hints(
 4411        &mut self,
 4412        _: &ToggleInlayHints,
 4413        _: &mut Window,
 4414        cx: &mut Context<Self>,
 4415    ) {
 4416        self.refresh_inlay_hints(
 4417            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4418            cx,
 4419        );
 4420    }
 4421
 4422    pub fn inlay_hints_enabled(&self) -> bool {
 4423        self.inlay_hint_cache.enabled
 4424    }
 4425
 4426    pub fn inline_values_enabled(&self) -> bool {
 4427        self.inline_value_cache.enabled
 4428    }
 4429
 4430    #[cfg(any(test, feature = "test-support"))]
 4431    pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
 4432        self.display_map
 4433            .read(cx)
 4434            .current_inlays()
 4435            .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
 4436            .cloned()
 4437            .collect()
 4438    }
 4439
 4440    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4441        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4442            return;
 4443        }
 4444
 4445        let reason_description = reason.description();
 4446        let ignore_debounce = matches!(
 4447            reason,
 4448            InlayHintRefreshReason::SettingsChange(_)
 4449                | InlayHintRefreshReason::Toggle(_)
 4450                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4451                | InlayHintRefreshReason::ModifiersChanged(_)
 4452        );
 4453        let (invalidate_cache, required_languages) = match reason {
 4454            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4455                match self.inlay_hint_cache.modifiers_override(enabled) {
 4456                    Some(enabled) => {
 4457                        if enabled {
 4458                            (InvalidationStrategy::RefreshRequested, None)
 4459                        } else {
 4460                            self.splice_inlays(
 4461                                &self
 4462                                    .visible_inlay_hints(cx)
 4463                                    .iter()
 4464                                    .map(|inlay| inlay.id)
 4465                                    .collect::<Vec<InlayId>>(),
 4466                                Vec::new(),
 4467                                cx,
 4468                            );
 4469                            return;
 4470                        }
 4471                    }
 4472                    None => return,
 4473                }
 4474            }
 4475            InlayHintRefreshReason::Toggle(enabled) => {
 4476                if self.inlay_hint_cache.toggle(enabled) {
 4477                    if enabled {
 4478                        (InvalidationStrategy::RefreshRequested, None)
 4479                    } else {
 4480                        self.splice_inlays(
 4481                            &self
 4482                                .visible_inlay_hints(cx)
 4483                                .iter()
 4484                                .map(|inlay| inlay.id)
 4485                                .collect::<Vec<InlayId>>(),
 4486                            Vec::new(),
 4487                            cx,
 4488                        );
 4489                        return;
 4490                    }
 4491                } else {
 4492                    return;
 4493                }
 4494            }
 4495            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4496                match self.inlay_hint_cache.update_settings(
 4497                    &self.buffer,
 4498                    new_settings,
 4499                    self.visible_inlay_hints(cx),
 4500                    cx,
 4501                ) {
 4502                    ControlFlow::Break(Some(InlaySplice {
 4503                        to_remove,
 4504                        to_insert,
 4505                    })) => {
 4506                        self.splice_inlays(&to_remove, to_insert, cx);
 4507                        return;
 4508                    }
 4509                    ControlFlow::Break(None) => return,
 4510                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4511                }
 4512            }
 4513            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4514                if let Some(InlaySplice {
 4515                    to_remove,
 4516                    to_insert,
 4517                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4518                {
 4519                    self.splice_inlays(&to_remove, to_insert, cx);
 4520                }
 4521                self.display_map.update(cx, |display_map, _| {
 4522                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4523                });
 4524                return;
 4525            }
 4526            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4527            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4528                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4529            }
 4530            InlayHintRefreshReason::RefreshRequested => {
 4531                (InvalidationStrategy::RefreshRequested, None)
 4532            }
 4533        };
 4534
 4535        if let Some(InlaySplice {
 4536            to_remove,
 4537            to_insert,
 4538        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4539            reason_description,
 4540            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4541            invalidate_cache,
 4542            ignore_debounce,
 4543            cx,
 4544        ) {
 4545            self.splice_inlays(&to_remove, to_insert, cx);
 4546        }
 4547    }
 4548
 4549    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4550        self.display_map
 4551            .read(cx)
 4552            .current_inlays()
 4553            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4554            .cloned()
 4555            .collect()
 4556    }
 4557
 4558    pub fn excerpts_for_inlay_hints_query(
 4559        &self,
 4560        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4561        cx: &mut Context<Editor>,
 4562    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4563        let Some(project) = self.project.as_ref() else {
 4564            return HashMap::default();
 4565        };
 4566        let project = project.read(cx);
 4567        let multi_buffer = self.buffer().read(cx);
 4568        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4569        let multi_buffer_visible_start = self
 4570            .scroll_manager
 4571            .anchor()
 4572            .anchor
 4573            .to_point(&multi_buffer_snapshot);
 4574        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4575            multi_buffer_visible_start
 4576                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4577            Bias::Left,
 4578        );
 4579        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4580        multi_buffer_snapshot
 4581            .range_to_buffer_ranges(multi_buffer_visible_range)
 4582            .into_iter()
 4583            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4584            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4585                let buffer_file = project::File::from_dyn(buffer.file())?;
 4586                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4587                let worktree_entry = buffer_worktree
 4588                    .read(cx)
 4589                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4590                if worktree_entry.is_ignored {
 4591                    return None;
 4592                }
 4593
 4594                let language = buffer.language()?;
 4595                if let Some(restrict_to_languages) = restrict_to_languages {
 4596                    if !restrict_to_languages.contains(language) {
 4597                        return None;
 4598                    }
 4599                }
 4600                Some((
 4601                    excerpt_id,
 4602                    (
 4603                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4604                        buffer.version().clone(),
 4605                        excerpt_visible_range,
 4606                    ),
 4607                ))
 4608            })
 4609            .collect()
 4610    }
 4611
 4612    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4613        TextLayoutDetails {
 4614            text_system: window.text_system().clone(),
 4615            editor_style: self.style.clone().unwrap(),
 4616            rem_size: window.rem_size(),
 4617            scroll_anchor: self.scroll_manager.anchor(),
 4618            visible_rows: self.visible_line_count(),
 4619            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4620        }
 4621    }
 4622
 4623    pub fn splice_inlays(
 4624        &self,
 4625        to_remove: &[InlayId],
 4626        to_insert: Vec<Inlay>,
 4627        cx: &mut Context<Self>,
 4628    ) {
 4629        self.display_map.update(cx, |display_map, cx| {
 4630            display_map.splice_inlays(to_remove, to_insert, cx)
 4631        });
 4632        cx.notify();
 4633    }
 4634
 4635    fn trigger_on_type_formatting(
 4636        &self,
 4637        input: String,
 4638        window: &mut Window,
 4639        cx: &mut Context<Self>,
 4640    ) -> Option<Task<Result<()>>> {
 4641        if input.len() != 1 {
 4642            return None;
 4643        }
 4644
 4645        let project = self.project.as_ref()?;
 4646        let position = self.selections.newest_anchor().head();
 4647        let (buffer, buffer_position) = self
 4648            .buffer
 4649            .read(cx)
 4650            .text_anchor_for_position(position, cx)?;
 4651
 4652        let settings = language_settings::language_settings(
 4653            buffer
 4654                .read(cx)
 4655                .language_at(buffer_position)
 4656                .map(|l| l.name()),
 4657            buffer.read(cx).file(),
 4658            cx,
 4659        );
 4660        if !settings.use_on_type_format {
 4661            return None;
 4662        }
 4663
 4664        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4665        // hence we do LSP request & edit on host side only — add formats to host's history.
 4666        let push_to_lsp_host_history = true;
 4667        // If this is not the host, append its history with new edits.
 4668        let push_to_client_history = project.read(cx).is_via_collab();
 4669
 4670        let on_type_formatting = project.update(cx, |project, cx| {
 4671            project.on_type_format(
 4672                buffer.clone(),
 4673                buffer_position,
 4674                input,
 4675                push_to_lsp_host_history,
 4676                cx,
 4677            )
 4678        });
 4679        Some(cx.spawn_in(window, async move |editor, cx| {
 4680            if let Some(transaction) = on_type_formatting.await? {
 4681                if push_to_client_history {
 4682                    buffer
 4683                        .update(cx, |buffer, _| {
 4684                            buffer.push_transaction(transaction, Instant::now());
 4685                            buffer.finalize_last_transaction();
 4686                        })
 4687                        .ok();
 4688                }
 4689                editor.update(cx, |editor, cx| {
 4690                    editor.refresh_document_highlights(cx);
 4691                })?;
 4692            }
 4693            Ok(())
 4694        }))
 4695    }
 4696
 4697    pub fn show_word_completions(
 4698        &mut self,
 4699        _: &ShowWordCompletions,
 4700        window: &mut Window,
 4701        cx: &mut Context<Self>,
 4702    ) {
 4703        self.open_completions_menu(true, None, window, cx);
 4704    }
 4705
 4706    pub fn show_completions(
 4707        &mut self,
 4708        options: &ShowCompletions,
 4709        window: &mut Window,
 4710        cx: &mut Context<Self>,
 4711    ) {
 4712        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4713    }
 4714
 4715    fn open_completions_menu(
 4716        &mut self,
 4717        ignore_completion_provider: bool,
 4718        trigger: Option<&str>,
 4719        window: &mut Window,
 4720        cx: &mut Context<Self>,
 4721    ) {
 4722        if self.pending_rename.is_some() {
 4723            return;
 4724        }
 4725        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4726            return;
 4727        }
 4728
 4729        let position = self.selections.newest_anchor().head();
 4730        if position.diff_base_anchor.is_some() {
 4731            return;
 4732        }
 4733        let (buffer, buffer_position) =
 4734            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4735                output
 4736            } else {
 4737                return;
 4738            };
 4739        let buffer_snapshot = buffer.read(cx).snapshot();
 4740        let show_completion_documentation = buffer_snapshot
 4741            .settings_at(buffer_position, cx)
 4742            .show_completion_documentation;
 4743
 4744        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4745
 4746        let trigger_kind = match trigger {
 4747            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4748                CompletionTriggerKind::TRIGGER_CHARACTER
 4749            }
 4750            _ => CompletionTriggerKind::INVOKED,
 4751        };
 4752        let completion_context = CompletionContext {
 4753            trigger_character: trigger.and_then(|trigger| {
 4754                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4755                    Some(String::from(trigger))
 4756                } else {
 4757                    None
 4758                }
 4759            }),
 4760            trigger_kind,
 4761        };
 4762
 4763        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4764        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4765            let word_to_exclude = buffer_snapshot
 4766                .text_for_range(old_range.clone())
 4767                .collect::<String>();
 4768            (
 4769                buffer_snapshot.anchor_before(old_range.start)
 4770                    ..buffer_snapshot.anchor_after(old_range.end),
 4771                Some(word_to_exclude),
 4772            )
 4773        } else {
 4774            (buffer_position..buffer_position, None)
 4775        };
 4776
 4777        let completion_settings = language_settings(
 4778            buffer_snapshot
 4779                .language_at(buffer_position)
 4780                .map(|language| language.name()),
 4781            buffer_snapshot.file(),
 4782            cx,
 4783        )
 4784        .completions;
 4785
 4786        // The document can be large, so stay in reasonable bounds when searching for words,
 4787        // otherwise completion pop-up might be slow to appear.
 4788        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4789        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4790        let min_word_search = buffer_snapshot.clip_point(
 4791            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4792            Bias::Left,
 4793        );
 4794        let max_word_search = buffer_snapshot.clip_point(
 4795            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4796            Bias::Right,
 4797        );
 4798        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4799            ..buffer_snapshot.point_to_offset(max_word_search);
 4800
 4801        let provider = self
 4802            .completion_provider
 4803            .as_ref()
 4804            .filter(|_| !ignore_completion_provider);
 4805        let skip_digits = query
 4806            .as_ref()
 4807            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4808
 4809        let (mut words, provided_completions) = match provider {
 4810            Some(provider) => {
 4811                let completions = provider.completions(
 4812                    position.excerpt_id,
 4813                    &buffer,
 4814                    buffer_position,
 4815                    completion_context,
 4816                    window,
 4817                    cx,
 4818                );
 4819
 4820                let words = match completion_settings.words {
 4821                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4822                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4823                        .background_spawn(async move {
 4824                            buffer_snapshot.words_in_range(WordsQuery {
 4825                                fuzzy_contents: None,
 4826                                range: word_search_range,
 4827                                skip_digits,
 4828                            })
 4829                        }),
 4830                };
 4831
 4832                (words, completions)
 4833            }
 4834            None => (
 4835                cx.background_spawn(async move {
 4836                    buffer_snapshot.words_in_range(WordsQuery {
 4837                        fuzzy_contents: None,
 4838                        range: word_search_range,
 4839                        skip_digits,
 4840                    })
 4841                }),
 4842                Task::ready(Ok(None)),
 4843            ),
 4844        };
 4845
 4846        let sort_completions = provider
 4847            .as_ref()
 4848            .map_or(false, |provider| provider.sort_completions());
 4849
 4850        let filter_completions = provider
 4851            .as_ref()
 4852            .map_or(true, |provider| provider.filter_completions());
 4853
 4854        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4855
 4856        let id = post_inc(&mut self.next_completion_id);
 4857        let task = cx.spawn_in(window, async move |editor, cx| {
 4858            async move {
 4859                editor.update(cx, |this, _| {
 4860                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4861                })?;
 4862
 4863                let mut completions = Vec::new();
 4864                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4865                    completions.extend(provided_completions);
 4866                    if completion_settings.words == WordsCompletionMode::Fallback {
 4867                        words = Task::ready(BTreeMap::default());
 4868                    }
 4869                }
 4870
 4871                let mut words = words.await;
 4872                if let Some(word_to_exclude) = &word_to_exclude {
 4873                    words.remove(word_to_exclude);
 4874                }
 4875                for lsp_completion in &completions {
 4876                    words.remove(&lsp_completion.new_text);
 4877                }
 4878                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4879                    replace_range: old_range.clone(),
 4880                    new_text: word.clone(),
 4881                    label: CodeLabel::plain(word, None),
 4882                    icon_path: None,
 4883                    documentation: None,
 4884                    source: CompletionSource::BufferWord {
 4885                        word_range,
 4886                        resolved: false,
 4887                    },
 4888                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4889                    confirm: None,
 4890                }));
 4891
 4892                let menu = if completions.is_empty() {
 4893                    None
 4894                } else {
 4895                    let mut menu = CompletionsMenu::new(
 4896                        id,
 4897                        sort_completions,
 4898                        show_completion_documentation,
 4899                        ignore_completion_provider,
 4900                        position,
 4901                        buffer.clone(),
 4902                        completions.into(),
 4903                        snippet_sort_order,
 4904                    );
 4905
 4906                    menu.filter(
 4907                        if filter_completions {
 4908                            query.as_deref()
 4909                        } else {
 4910                            None
 4911                        },
 4912                        cx.background_executor().clone(),
 4913                    )
 4914                    .await;
 4915
 4916                    menu.visible().then_some(menu)
 4917                };
 4918
 4919                editor.update_in(cx, |editor, window, cx| {
 4920                    match editor.context_menu.borrow().as_ref() {
 4921                        None => {}
 4922                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4923                            if prev_menu.id > id {
 4924                                return;
 4925                            }
 4926                        }
 4927                        _ => return,
 4928                    }
 4929
 4930                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4931                        let mut menu = menu.unwrap();
 4932                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4933
 4934                        *editor.context_menu.borrow_mut() =
 4935                            Some(CodeContextMenu::Completions(menu));
 4936
 4937                        if editor.show_edit_predictions_in_menu() {
 4938                            editor.update_visible_inline_completion(window, cx);
 4939                        } else {
 4940                            editor.discard_inline_completion(false, cx);
 4941                        }
 4942
 4943                        cx.notify();
 4944                    } else if editor.completion_tasks.len() <= 1 {
 4945                        // If there are no more completion tasks and the last menu was
 4946                        // empty, we should hide it.
 4947                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4948                        // If it was already hidden and we don't show inline
 4949                        // completions in the menu, we should also show the
 4950                        // inline-completion when available.
 4951                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4952                            editor.update_visible_inline_completion(window, cx);
 4953                        }
 4954                    }
 4955                })?;
 4956
 4957                anyhow::Ok(())
 4958            }
 4959            .log_err()
 4960            .await
 4961        });
 4962
 4963        self.completion_tasks.push((id, task));
 4964    }
 4965
 4966    #[cfg(feature = "test-support")]
 4967    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4968        let menu = self.context_menu.borrow();
 4969        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4970            let completions = menu.completions.borrow();
 4971            Some(completions.to_vec())
 4972        } else {
 4973            None
 4974        }
 4975    }
 4976
 4977    pub fn confirm_completion(
 4978        &mut self,
 4979        action: &ConfirmCompletion,
 4980        window: &mut Window,
 4981        cx: &mut Context<Self>,
 4982    ) -> Option<Task<Result<()>>> {
 4983        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4984        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4985    }
 4986
 4987    pub fn confirm_completion_insert(
 4988        &mut self,
 4989        _: &ConfirmCompletionInsert,
 4990        window: &mut Window,
 4991        cx: &mut Context<Self>,
 4992    ) -> Option<Task<Result<()>>> {
 4993        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4994        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4995    }
 4996
 4997    pub fn confirm_completion_replace(
 4998        &mut self,
 4999        _: &ConfirmCompletionReplace,
 5000        window: &mut Window,
 5001        cx: &mut Context<Self>,
 5002    ) -> Option<Task<Result<()>>> {
 5003        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5004        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 5005    }
 5006
 5007    pub fn compose_completion(
 5008        &mut self,
 5009        action: &ComposeCompletion,
 5010        window: &mut Window,
 5011        cx: &mut Context<Self>,
 5012    ) -> Option<Task<Result<()>>> {
 5013        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5014        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 5015    }
 5016
 5017    fn do_completion(
 5018        &mut self,
 5019        item_ix: Option<usize>,
 5020        intent: CompletionIntent,
 5021        window: &mut Window,
 5022        cx: &mut Context<Editor>,
 5023    ) -> Option<Task<Result<()>>> {
 5024        use language::ToOffset as _;
 5025
 5026        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 5027        else {
 5028            return None;
 5029        };
 5030
 5031        let candidate_id = {
 5032            let entries = completions_menu.entries.borrow();
 5033            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 5034            if self.show_edit_predictions_in_menu() {
 5035                self.discard_inline_completion(true, cx);
 5036            }
 5037            mat.candidate_id
 5038        };
 5039
 5040        let buffer_handle = completions_menu.buffer;
 5041        let completion = completions_menu
 5042            .completions
 5043            .borrow()
 5044            .get(candidate_id)?
 5045            .clone();
 5046        cx.stop_propagation();
 5047
 5048        let snapshot = self.buffer.read(cx).snapshot(cx);
 5049        let newest_anchor = self.selections.newest_anchor();
 5050
 5051        let snippet;
 5052        let new_text;
 5053        if completion.is_snippet() {
 5054            let mut snippet_source = completion.new_text.clone();
 5055            if let Some(scope) = snapshot.language_scope_at(newest_anchor.head()) {
 5056                if scope.prefers_label_for_snippet_in_completion() {
 5057                    if let Some(label) = completion.label() {
 5058                        if matches!(
 5059                            completion.kind(),
 5060                            Some(CompletionItemKind::FUNCTION) | Some(CompletionItemKind::METHOD)
 5061                        ) {
 5062                            snippet_source = label;
 5063                        }
 5064                    }
 5065                }
 5066            }
 5067            snippet = Some(Snippet::parse(&snippet_source).log_err()?);
 5068            new_text = snippet.as_ref().unwrap().text.clone();
 5069        } else {
 5070            snippet = None;
 5071            new_text = completion.new_text.clone();
 5072        };
 5073
 5074        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 5075        let buffer = buffer_handle.read(cx);
 5076        let replace_range_multibuffer = {
 5077            let excerpt = snapshot.excerpt_containing(newest_anchor.range()).unwrap();
 5078            let multibuffer_anchor = snapshot
 5079                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 5080                .unwrap()
 5081                ..snapshot
 5082                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 5083                    .unwrap();
 5084            multibuffer_anchor.start.to_offset(&snapshot)
 5085                ..multibuffer_anchor.end.to_offset(&snapshot)
 5086        };
 5087        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 5088            return None;
 5089        }
 5090
 5091        let old_text = buffer
 5092            .text_for_range(replace_range.clone())
 5093            .collect::<String>();
 5094        let lookbehind = newest_anchor
 5095            .start
 5096            .text_anchor
 5097            .to_offset(buffer)
 5098            .saturating_sub(replace_range.start);
 5099        let lookahead = replace_range
 5100            .end
 5101            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 5102        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 5103        let suffix = &old_text[lookbehind.min(old_text.len())..];
 5104
 5105        let selections = self.selections.all::<usize>(cx);
 5106        let mut ranges = Vec::new();
 5107        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 5108
 5109        for selection in &selections {
 5110            let range = if selection.id == newest_anchor.id {
 5111                replace_range_multibuffer.clone()
 5112            } else {
 5113                let mut range = selection.range();
 5114
 5115                // if prefix is present, don't duplicate it
 5116                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5117                    range.start = range.start.saturating_sub(lookbehind);
 5118
 5119                    // if suffix is also present, mimic the newest cursor and replace it
 5120                    if selection.id != newest_anchor.id
 5121                        && snapshot.contains_str_at(range.end, suffix)
 5122                    {
 5123                        range.end += lookahead;
 5124                    }
 5125                }
 5126                range
 5127            };
 5128
 5129            ranges.push(range.clone());
 5130
 5131            if !self.linked_edit_ranges.is_empty() {
 5132                let start_anchor = snapshot.anchor_before(range.start);
 5133                let end_anchor = snapshot.anchor_after(range.end);
 5134                if let Some(ranges) = self
 5135                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5136                {
 5137                    for (buffer, edits) in ranges {
 5138                        linked_edits
 5139                            .entry(buffer.clone())
 5140                            .or_default()
 5141                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5142                    }
 5143                }
 5144            }
 5145        }
 5146
 5147        cx.emit(EditorEvent::InputHandled {
 5148            utf16_range_to_replace: None,
 5149            text: new_text.clone().into(),
 5150        });
 5151
 5152        self.transact(window, cx, |this, window, cx| {
 5153            if let Some(mut snippet) = snippet {
 5154                snippet.text = new_text.to_string();
 5155                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5156            } else {
 5157                this.buffer.update(cx, |buffer, cx| {
 5158                    let auto_indent = match completion.insert_text_mode {
 5159                        Some(InsertTextMode::AS_IS) => None,
 5160                        _ => this.autoindent_mode.clone(),
 5161                    };
 5162                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5163                    buffer.edit(edits, auto_indent, cx);
 5164                });
 5165            }
 5166            for (buffer, edits) in linked_edits {
 5167                buffer.update(cx, |buffer, cx| {
 5168                    let snapshot = buffer.snapshot();
 5169                    let edits = edits
 5170                        .into_iter()
 5171                        .map(|(range, text)| {
 5172                            use text::ToPoint as TP;
 5173                            let end_point = TP::to_point(&range.end, &snapshot);
 5174                            let start_point = TP::to_point(&range.start, &snapshot);
 5175                            (start_point..end_point, text)
 5176                        })
 5177                        .sorted_by_key(|(range, _)| range.start);
 5178                    buffer.edit(edits, None, cx);
 5179                })
 5180            }
 5181
 5182            this.refresh_inline_completion(true, false, window, cx);
 5183        });
 5184
 5185        let show_new_completions_on_confirm = completion
 5186            .confirm
 5187            .as_ref()
 5188            .map_or(false, |confirm| confirm(intent, window, cx));
 5189        if show_new_completions_on_confirm {
 5190            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5191        }
 5192
 5193        let provider = self.completion_provider.as_ref()?;
 5194        drop(completion);
 5195        let apply_edits = provider.apply_additional_edits_for_completion(
 5196            buffer_handle,
 5197            completions_menu.completions.clone(),
 5198            candidate_id,
 5199            true,
 5200            cx,
 5201        );
 5202
 5203        let editor_settings = EditorSettings::get_global(cx);
 5204        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5205            // After the code completion is finished, users often want to know what signatures are needed.
 5206            // so we should automatically call signature_help
 5207            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5208        }
 5209
 5210        Some(cx.foreground_executor().spawn(async move {
 5211            apply_edits.await?;
 5212            Ok(())
 5213        }))
 5214    }
 5215
 5216    pub fn toggle_code_actions(
 5217        &mut self,
 5218        action: &ToggleCodeActions,
 5219        window: &mut Window,
 5220        cx: &mut Context<Self>,
 5221    ) {
 5222        let quick_launch = action.quick_launch;
 5223        let mut context_menu = self.context_menu.borrow_mut();
 5224        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5225            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5226                // Toggle if we're selecting the same one
 5227                *context_menu = None;
 5228                cx.notify();
 5229                return;
 5230            } else {
 5231                // Otherwise, clear it and start a new one
 5232                *context_menu = None;
 5233                cx.notify();
 5234            }
 5235        }
 5236        drop(context_menu);
 5237        let snapshot = self.snapshot(window, cx);
 5238        let deployed_from_indicator = action.deployed_from_indicator;
 5239        let mut task = self.code_actions_task.take();
 5240        let action = action.clone();
 5241        cx.spawn_in(window, async move |editor, cx| {
 5242            while let Some(prev_task) = task {
 5243                prev_task.await.log_err();
 5244                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5245            }
 5246
 5247            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5248                if editor.focus_handle.is_focused(window) {
 5249                    let multibuffer_point = action
 5250                        .deployed_from_indicator
 5251                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5252                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5253                    let (buffer, buffer_row) = snapshot
 5254                        .buffer_snapshot
 5255                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5256                        .and_then(|(buffer_snapshot, range)| {
 5257                            editor
 5258                                .buffer
 5259                                .read(cx)
 5260                                .buffer(buffer_snapshot.remote_id())
 5261                                .map(|buffer| (buffer, range.start.row))
 5262                        })?;
 5263                    let (_, code_actions) = editor
 5264                        .available_code_actions
 5265                        .clone()
 5266                        .and_then(|(location, code_actions)| {
 5267                            let snapshot = location.buffer.read(cx).snapshot();
 5268                            let point_range = location.range.to_point(&snapshot);
 5269                            let point_range = point_range.start.row..=point_range.end.row;
 5270                            if point_range.contains(&buffer_row) {
 5271                                Some((location, code_actions))
 5272                            } else {
 5273                                None
 5274                            }
 5275                        })
 5276                        .unzip();
 5277                    let buffer_id = buffer.read(cx).remote_id();
 5278                    let tasks = editor
 5279                        .tasks
 5280                        .get(&(buffer_id, buffer_row))
 5281                        .map(|t| Arc::new(t.to_owned()));
 5282                    if tasks.is_none() && code_actions.is_none() {
 5283                        return None;
 5284                    }
 5285
 5286                    editor.completion_tasks.clear();
 5287                    editor.discard_inline_completion(false, cx);
 5288                    let task_context =
 5289                        tasks
 5290                            .as_ref()
 5291                            .zip(editor.project.clone())
 5292                            .map(|(tasks, project)| {
 5293                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5294                            });
 5295
 5296                    Some(cx.spawn_in(window, async move |editor, cx| {
 5297                        let task_context = match task_context {
 5298                            Some(task_context) => task_context.await,
 5299                            None => None,
 5300                        };
 5301                        let resolved_tasks =
 5302                            tasks
 5303                                .zip(task_context.clone())
 5304                                .map(|(tasks, task_context)| ResolvedTasks {
 5305                                    templates: tasks.resolve(&task_context).collect(),
 5306                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5307                                        multibuffer_point.row,
 5308                                        tasks.column,
 5309                                    )),
 5310                                });
 5311                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5312                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5313                                maybe!({
 5314                                    let project = editor.project.as_ref()?;
 5315                                    let dap_store = project.read(cx).dap_store();
 5316                                    let mut scenarios = vec![];
 5317                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5318                                    let buffer = buffer.read(cx);
 5319                                    let language = buffer.language()?;
 5320                                    let file = buffer.file();
 5321                                    let debug_adapter =
 5322                                        language_settings(language.name().into(), file, cx)
 5323                                            .debuggers
 5324                                            .first()
 5325                                            .map(SharedString::from)
 5326                                            .or_else(|| {
 5327                                                language
 5328                                                    .config()
 5329                                                    .debuggers
 5330                                                    .first()
 5331                                                    .map(SharedString::from)
 5332                                            })?;
 5333
 5334                                    dap_store.update(cx, |this, cx| {
 5335                                        for (_, task) in &resolved_tasks.templates {
 5336                                            if let Some(scenario) = this
 5337                                                .debug_scenario_for_build_task(
 5338                                                    task.original_task().clone(),
 5339                                                    debug_adapter.clone().into(),
 5340                                                    task.display_label().to_owned().into(),
 5341                                                    cx,
 5342                                                )
 5343                                            {
 5344                                                scenarios.push(scenario);
 5345                                            }
 5346                                        }
 5347                                    });
 5348                                    Some(scenarios)
 5349                                })
 5350                                .unwrap_or_default()
 5351                            } else {
 5352                                vec![]
 5353                            }
 5354                        })?;
 5355                        let spawn_straight_away = quick_launch
 5356                            && resolved_tasks
 5357                                .as_ref()
 5358                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5359                            && code_actions
 5360                                .as_ref()
 5361                                .map_or(true, |actions| actions.is_empty())
 5362                            && debug_scenarios.is_empty();
 5363                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5364                            *editor.context_menu.borrow_mut() =
 5365                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5366                                    buffer,
 5367                                    actions: CodeActionContents::new(
 5368                                        resolved_tasks,
 5369                                        code_actions,
 5370                                        debug_scenarios,
 5371                                        task_context.unwrap_or_default(),
 5372                                    ),
 5373                                    selected_item: Default::default(),
 5374                                    scroll_handle: UniformListScrollHandle::default(),
 5375                                    deployed_from_indicator,
 5376                                }));
 5377                            if spawn_straight_away {
 5378                                if let Some(task) = editor.confirm_code_action(
 5379                                    &ConfirmCodeAction { item_ix: Some(0) },
 5380                                    window,
 5381                                    cx,
 5382                                ) {
 5383                                    cx.notify();
 5384                                    return task;
 5385                                }
 5386                            }
 5387                            cx.notify();
 5388                            Task::ready(Ok(()))
 5389                        }) {
 5390                            task.await
 5391                        } else {
 5392                            Ok(())
 5393                        }
 5394                    }))
 5395                } else {
 5396                    Some(Task::ready(Ok(())))
 5397                }
 5398            })?;
 5399            if let Some(task) = spawned_test_task {
 5400                task.await?;
 5401            }
 5402
 5403            Ok::<_, anyhow::Error>(())
 5404        })
 5405        .detach_and_log_err(cx);
 5406    }
 5407
 5408    pub fn confirm_code_action(
 5409        &mut self,
 5410        action: &ConfirmCodeAction,
 5411        window: &mut Window,
 5412        cx: &mut Context<Self>,
 5413    ) -> Option<Task<Result<()>>> {
 5414        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5415
 5416        let actions_menu =
 5417            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5418                menu
 5419            } else {
 5420                return None;
 5421            };
 5422
 5423        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5424        let action = actions_menu.actions.get(action_ix)?;
 5425        let title = action.label();
 5426        let buffer = actions_menu.buffer;
 5427        let workspace = self.workspace()?;
 5428
 5429        match action {
 5430            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5431                workspace.update(cx, |workspace, cx| {
 5432                    workspace.schedule_resolved_task(
 5433                        task_source_kind,
 5434                        resolved_task,
 5435                        false,
 5436                        window,
 5437                        cx,
 5438                    );
 5439
 5440                    Some(Task::ready(Ok(())))
 5441                })
 5442            }
 5443            CodeActionsItem::CodeAction {
 5444                excerpt_id,
 5445                action,
 5446                provider,
 5447            } => {
 5448                let apply_code_action =
 5449                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5450                let workspace = workspace.downgrade();
 5451                Some(cx.spawn_in(window, async move |editor, cx| {
 5452                    let project_transaction = apply_code_action.await?;
 5453                    Self::open_project_transaction(
 5454                        &editor,
 5455                        workspace,
 5456                        project_transaction,
 5457                        title,
 5458                        cx,
 5459                    )
 5460                    .await
 5461                }))
 5462            }
 5463            CodeActionsItem::DebugScenario(scenario) => {
 5464                let context = actions_menu.actions.context.clone();
 5465
 5466                workspace.update(cx, |workspace, cx| {
 5467                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5468                });
 5469                Some(Task::ready(Ok(())))
 5470            }
 5471        }
 5472    }
 5473
 5474    pub async fn open_project_transaction(
 5475        this: &WeakEntity<Editor>,
 5476        workspace: WeakEntity<Workspace>,
 5477        transaction: ProjectTransaction,
 5478        title: String,
 5479        cx: &mut AsyncWindowContext,
 5480    ) -> Result<()> {
 5481        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5482        cx.update(|_, cx| {
 5483            entries.sort_unstable_by_key(|(buffer, _)| {
 5484                buffer.read(cx).file().map(|f| f.path().clone())
 5485            });
 5486        })?;
 5487
 5488        // If the project transaction's edits are all contained within this editor, then
 5489        // avoid opening a new editor to display them.
 5490
 5491        if let Some((buffer, transaction)) = entries.first() {
 5492            if entries.len() == 1 {
 5493                let excerpt = this.update(cx, |editor, cx| {
 5494                    editor
 5495                        .buffer()
 5496                        .read(cx)
 5497                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5498                })?;
 5499                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5500                    if excerpted_buffer == *buffer {
 5501                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5502                            let excerpt_range = excerpt_range.to_offset(buffer);
 5503                            buffer
 5504                                .edited_ranges_for_transaction::<usize>(transaction)
 5505                                .all(|range| {
 5506                                    excerpt_range.start <= range.start
 5507                                        && excerpt_range.end >= range.end
 5508                                })
 5509                        })?;
 5510
 5511                        if all_edits_within_excerpt {
 5512                            return Ok(());
 5513                        }
 5514                    }
 5515                }
 5516            }
 5517        } else {
 5518            return Ok(());
 5519        }
 5520
 5521        let mut ranges_to_highlight = Vec::new();
 5522        let excerpt_buffer = cx.new(|cx| {
 5523            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5524            for (buffer_handle, transaction) in &entries {
 5525                let edited_ranges = buffer_handle
 5526                    .read(cx)
 5527                    .edited_ranges_for_transaction::<Point>(transaction)
 5528                    .collect::<Vec<_>>();
 5529                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5530                    PathKey::for_buffer(buffer_handle, cx),
 5531                    buffer_handle.clone(),
 5532                    edited_ranges,
 5533                    DEFAULT_MULTIBUFFER_CONTEXT,
 5534                    cx,
 5535                );
 5536
 5537                ranges_to_highlight.extend(ranges);
 5538            }
 5539            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5540            multibuffer
 5541        })?;
 5542
 5543        workspace.update_in(cx, |workspace, window, cx| {
 5544            let project = workspace.project().clone();
 5545            let editor =
 5546                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5547            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5548            editor.update(cx, |editor, cx| {
 5549                editor.highlight_background::<Self>(
 5550                    &ranges_to_highlight,
 5551                    |theme| theme.editor_highlighted_line_background,
 5552                    cx,
 5553                );
 5554            });
 5555        })?;
 5556
 5557        Ok(())
 5558    }
 5559
 5560    pub fn clear_code_action_providers(&mut self) {
 5561        self.code_action_providers.clear();
 5562        self.available_code_actions.take();
 5563    }
 5564
 5565    pub fn add_code_action_provider(
 5566        &mut self,
 5567        provider: Rc<dyn CodeActionProvider>,
 5568        window: &mut Window,
 5569        cx: &mut Context<Self>,
 5570    ) {
 5571        if self
 5572            .code_action_providers
 5573            .iter()
 5574            .any(|existing_provider| existing_provider.id() == provider.id())
 5575        {
 5576            return;
 5577        }
 5578
 5579        self.code_action_providers.push(provider);
 5580        self.refresh_code_actions(window, cx);
 5581    }
 5582
 5583    pub fn remove_code_action_provider(
 5584        &mut self,
 5585        id: Arc<str>,
 5586        window: &mut Window,
 5587        cx: &mut Context<Self>,
 5588    ) {
 5589        self.code_action_providers
 5590            .retain(|provider| provider.id() != id);
 5591        self.refresh_code_actions(window, cx);
 5592    }
 5593
 5594    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5595        let newest_selection = self.selections.newest_anchor().clone();
 5596        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5597        let buffer = self.buffer.read(cx);
 5598        if newest_selection.head().diff_base_anchor.is_some() {
 5599            return None;
 5600        }
 5601        let (start_buffer, start) =
 5602            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5603        let (end_buffer, end) =
 5604            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5605        if start_buffer != end_buffer {
 5606            return None;
 5607        }
 5608
 5609        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5610            cx.background_executor()
 5611                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5612                .await;
 5613
 5614            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5615                let providers = this.code_action_providers.clone();
 5616                let tasks = this
 5617                    .code_action_providers
 5618                    .iter()
 5619                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5620                    .collect::<Vec<_>>();
 5621                (providers, tasks)
 5622            })?;
 5623
 5624            let mut actions = Vec::new();
 5625            for (provider, provider_actions) in
 5626                providers.into_iter().zip(future::join_all(tasks).await)
 5627            {
 5628                if let Some(provider_actions) = provider_actions.log_err() {
 5629                    actions.extend(provider_actions.into_iter().map(|action| {
 5630                        AvailableCodeAction {
 5631                            excerpt_id: newest_selection.start.excerpt_id,
 5632                            action,
 5633                            provider: provider.clone(),
 5634                        }
 5635                    }));
 5636                }
 5637            }
 5638
 5639            this.update(cx, |this, cx| {
 5640                this.available_code_actions = if actions.is_empty() {
 5641                    None
 5642                } else {
 5643                    Some((
 5644                        Location {
 5645                            buffer: start_buffer,
 5646                            range: start..end,
 5647                        },
 5648                        actions.into(),
 5649                    ))
 5650                };
 5651                cx.notify();
 5652            })
 5653        }));
 5654        None
 5655    }
 5656
 5657    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5658        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5659            self.show_git_blame_inline = false;
 5660
 5661            self.show_git_blame_inline_delay_task =
 5662                Some(cx.spawn_in(window, async move |this, cx| {
 5663                    cx.background_executor().timer(delay).await;
 5664
 5665                    this.update(cx, |this, cx| {
 5666                        this.show_git_blame_inline = true;
 5667                        cx.notify();
 5668                    })
 5669                    .log_err();
 5670                }));
 5671        }
 5672    }
 5673
 5674    fn show_blame_popover(
 5675        &mut self,
 5676        blame_entry: &BlameEntry,
 5677        position: gpui::Point<Pixels>,
 5678        cx: &mut Context<Self>,
 5679    ) {
 5680        if let Some(state) = &mut self.inline_blame_popover {
 5681            state.hide_task.take();
 5682            cx.notify();
 5683        } else {
 5684            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5685            let show_task = cx.spawn(async move |editor, cx| {
 5686                cx.background_executor()
 5687                    .timer(std::time::Duration::from_millis(delay))
 5688                    .await;
 5689                editor
 5690                    .update(cx, |editor, cx| {
 5691                        if let Some(state) = &mut editor.inline_blame_popover {
 5692                            state.show_task = None;
 5693                            cx.notify();
 5694                        }
 5695                    })
 5696                    .ok();
 5697            });
 5698            let Some(blame) = self.blame.as_ref() else {
 5699                return;
 5700            };
 5701            let blame = blame.read(cx);
 5702            let details = blame.details_for_entry(&blame_entry);
 5703            let markdown = cx.new(|cx| {
 5704                Markdown::new(
 5705                    details
 5706                        .as_ref()
 5707                        .map(|message| message.message.clone())
 5708                        .unwrap_or_default(),
 5709                    None,
 5710                    None,
 5711                    cx,
 5712                )
 5713            });
 5714            self.inline_blame_popover = Some(InlineBlamePopover {
 5715                position,
 5716                show_task: Some(show_task),
 5717                hide_task: None,
 5718                popover_bounds: None,
 5719                popover_state: InlineBlamePopoverState {
 5720                    scroll_handle: ScrollHandle::new(),
 5721                    commit_message: details,
 5722                    markdown,
 5723                },
 5724            });
 5725        }
 5726    }
 5727
 5728    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5729        if let Some(state) = &mut self.inline_blame_popover {
 5730            if state.show_task.is_some() {
 5731                self.inline_blame_popover.take();
 5732                cx.notify();
 5733            } else {
 5734                let hide_task = cx.spawn(async move |editor, cx| {
 5735                    cx.background_executor()
 5736                        .timer(std::time::Duration::from_millis(100))
 5737                        .await;
 5738                    editor
 5739                        .update(cx, |editor, cx| {
 5740                            editor.inline_blame_popover.take();
 5741                            cx.notify();
 5742                        })
 5743                        .ok();
 5744                });
 5745                state.hide_task = Some(hide_task);
 5746            }
 5747        }
 5748    }
 5749
 5750    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5751        if self.pending_rename.is_some() {
 5752            return None;
 5753        }
 5754
 5755        let provider = self.semantics_provider.clone()?;
 5756        let buffer = self.buffer.read(cx);
 5757        let newest_selection = self.selections.newest_anchor().clone();
 5758        let cursor_position = newest_selection.head();
 5759        let (cursor_buffer, cursor_buffer_position) =
 5760            buffer.text_anchor_for_position(cursor_position, cx)?;
 5761        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5762        if cursor_buffer != tail_buffer {
 5763            return None;
 5764        }
 5765        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5766        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5767            cx.background_executor()
 5768                .timer(Duration::from_millis(debounce))
 5769                .await;
 5770
 5771            let highlights = if let Some(highlights) = cx
 5772                .update(|cx| {
 5773                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5774                })
 5775                .ok()
 5776                .flatten()
 5777            {
 5778                highlights.await.log_err()
 5779            } else {
 5780                None
 5781            };
 5782
 5783            if let Some(highlights) = highlights {
 5784                this.update(cx, |this, cx| {
 5785                    if this.pending_rename.is_some() {
 5786                        return;
 5787                    }
 5788
 5789                    let buffer_id = cursor_position.buffer_id;
 5790                    let buffer = this.buffer.read(cx);
 5791                    if !buffer
 5792                        .text_anchor_for_position(cursor_position, cx)
 5793                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5794                    {
 5795                        return;
 5796                    }
 5797
 5798                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5799                    let mut write_ranges = Vec::new();
 5800                    let mut read_ranges = Vec::new();
 5801                    for highlight in highlights {
 5802                        for (excerpt_id, excerpt_range) in
 5803                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5804                        {
 5805                            let start = highlight
 5806                                .range
 5807                                .start
 5808                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5809                            let end = highlight
 5810                                .range
 5811                                .end
 5812                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5813                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5814                                continue;
 5815                            }
 5816
 5817                            let range = Anchor {
 5818                                buffer_id,
 5819                                excerpt_id,
 5820                                text_anchor: start,
 5821                                diff_base_anchor: None,
 5822                            }..Anchor {
 5823                                buffer_id,
 5824                                excerpt_id,
 5825                                text_anchor: end,
 5826                                diff_base_anchor: None,
 5827                            };
 5828                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5829                                write_ranges.push(range);
 5830                            } else {
 5831                                read_ranges.push(range);
 5832                            }
 5833                        }
 5834                    }
 5835
 5836                    this.highlight_background::<DocumentHighlightRead>(
 5837                        &read_ranges,
 5838                        |theme| theme.editor_document_highlight_read_background,
 5839                        cx,
 5840                    );
 5841                    this.highlight_background::<DocumentHighlightWrite>(
 5842                        &write_ranges,
 5843                        |theme| theme.editor_document_highlight_write_background,
 5844                        cx,
 5845                    );
 5846                    cx.notify();
 5847                })
 5848                .log_err();
 5849            }
 5850        }));
 5851        None
 5852    }
 5853
 5854    fn prepare_highlight_query_from_selection(
 5855        &mut self,
 5856        cx: &mut Context<Editor>,
 5857    ) -> Option<(String, Range<Anchor>)> {
 5858        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5859            return None;
 5860        }
 5861        if !EditorSettings::get_global(cx).selection_highlight {
 5862            return None;
 5863        }
 5864        if self.selections.count() != 1 || self.selections.line_mode {
 5865            return None;
 5866        }
 5867        let selection = self.selections.newest::<Point>(cx);
 5868        if selection.is_empty() || selection.start.row != selection.end.row {
 5869            return None;
 5870        }
 5871        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5872        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5873        let query = multi_buffer_snapshot
 5874            .text_for_range(selection_anchor_range.clone())
 5875            .collect::<String>();
 5876        if query.trim().is_empty() {
 5877            return None;
 5878        }
 5879        Some((query, selection_anchor_range))
 5880    }
 5881
 5882    fn update_selection_occurrence_highlights(
 5883        &mut self,
 5884        query_text: String,
 5885        query_range: Range<Anchor>,
 5886        multi_buffer_range_to_query: Range<Point>,
 5887        use_debounce: bool,
 5888        window: &mut Window,
 5889        cx: &mut Context<Editor>,
 5890    ) -> Task<()> {
 5891        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5892        cx.spawn_in(window, async move |editor, cx| {
 5893            if use_debounce {
 5894                cx.background_executor()
 5895                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5896                    .await;
 5897            }
 5898            let match_task = cx.background_spawn(async move {
 5899                let buffer_ranges = multi_buffer_snapshot
 5900                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5901                    .into_iter()
 5902                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5903                let mut match_ranges = Vec::new();
 5904                let Ok(regex) = project::search::SearchQuery::text(
 5905                    query_text.clone(),
 5906                    false,
 5907                    false,
 5908                    false,
 5909                    Default::default(),
 5910                    Default::default(),
 5911                    false,
 5912                    None,
 5913                ) else {
 5914                    return Vec::default();
 5915                };
 5916                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5917                    match_ranges.extend(
 5918                        regex
 5919                            .search(&buffer_snapshot, Some(search_range.clone()))
 5920                            .await
 5921                            .into_iter()
 5922                            .filter_map(|match_range| {
 5923                                let match_start = buffer_snapshot
 5924                                    .anchor_after(search_range.start + match_range.start);
 5925                                let match_end = buffer_snapshot
 5926                                    .anchor_before(search_range.start + match_range.end);
 5927                                let match_anchor_range = Anchor::range_in_buffer(
 5928                                    excerpt_id,
 5929                                    buffer_snapshot.remote_id(),
 5930                                    match_start..match_end,
 5931                                );
 5932                                (match_anchor_range != query_range).then_some(match_anchor_range)
 5933                            }),
 5934                    );
 5935                }
 5936                match_ranges
 5937            });
 5938            let match_ranges = match_task.await;
 5939            editor
 5940                .update_in(cx, |editor, _, cx| {
 5941                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5942                    if !match_ranges.is_empty() {
 5943                        editor.highlight_background::<SelectedTextHighlight>(
 5944                            &match_ranges,
 5945                            |theme| theme.editor_document_highlight_bracket_background,
 5946                            cx,
 5947                        )
 5948                    }
 5949                })
 5950                .log_err();
 5951        })
 5952    }
 5953
 5954    fn refresh_selected_text_highlights(
 5955        &mut self,
 5956        on_buffer_edit: bool,
 5957        window: &mut Window,
 5958        cx: &mut Context<Editor>,
 5959    ) {
 5960        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5961        else {
 5962            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5963            self.quick_selection_highlight_task.take();
 5964            self.debounced_selection_highlight_task.take();
 5965            return;
 5966        };
 5967        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5968        if on_buffer_edit
 5969            || self
 5970                .quick_selection_highlight_task
 5971                .as_ref()
 5972                .map_or(true, |(prev_anchor_range, _)| {
 5973                    prev_anchor_range != &query_range
 5974                })
 5975        {
 5976            let multi_buffer_visible_start = self
 5977                .scroll_manager
 5978                .anchor()
 5979                .anchor
 5980                .to_point(&multi_buffer_snapshot);
 5981            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5982                multi_buffer_visible_start
 5983                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5984                Bias::Left,
 5985            );
 5986            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5987            self.quick_selection_highlight_task = Some((
 5988                query_range.clone(),
 5989                self.update_selection_occurrence_highlights(
 5990                    query_text.clone(),
 5991                    query_range.clone(),
 5992                    multi_buffer_visible_range,
 5993                    false,
 5994                    window,
 5995                    cx,
 5996                ),
 5997            ));
 5998        }
 5999        if on_buffer_edit
 6000            || self
 6001                .debounced_selection_highlight_task
 6002                .as_ref()
 6003                .map_or(true, |(prev_anchor_range, _)| {
 6004                    prev_anchor_range != &query_range
 6005                })
 6006        {
 6007            let multi_buffer_start = multi_buffer_snapshot
 6008                .anchor_before(0)
 6009                .to_point(&multi_buffer_snapshot);
 6010            let multi_buffer_end = multi_buffer_snapshot
 6011                .anchor_after(multi_buffer_snapshot.len())
 6012                .to_point(&multi_buffer_snapshot);
 6013            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 6014            self.debounced_selection_highlight_task = Some((
 6015                query_range.clone(),
 6016                self.update_selection_occurrence_highlights(
 6017                    query_text,
 6018                    query_range,
 6019                    multi_buffer_full_range,
 6020                    true,
 6021                    window,
 6022                    cx,
 6023                ),
 6024            ));
 6025        }
 6026    }
 6027
 6028    pub fn refresh_inline_completion(
 6029        &mut self,
 6030        debounce: bool,
 6031        user_requested: bool,
 6032        window: &mut Window,
 6033        cx: &mut Context<Self>,
 6034    ) -> Option<()> {
 6035        let provider = self.edit_prediction_provider()?;
 6036        let cursor = self.selections.newest_anchor().head();
 6037        let (buffer, cursor_buffer_position) =
 6038            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6039
 6040        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 6041            self.discard_inline_completion(false, cx);
 6042            return None;
 6043        }
 6044
 6045        if !user_requested
 6046            && (!self.should_show_edit_predictions()
 6047                || !self.is_focused(window)
 6048                || buffer.read(cx).is_empty())
 6049        {
 6050            self.discard_inline_completion(false, cx);
 6051            return None;
 6052        }
 6053
 6054        self.update_visible_inline_completion(window, cx);
 6055        provider.refresh(
 6056            self.project.clone(),
 6057            buffer,
 6058            cursor_buffer_position,
 6059            debounce,
 6060            cx,
 6061        );
 6062        Some(())
 6063    }
 6064
 6065    fn show_edit_predictions_in_menu(&self) -> bool {
 6066        match self.edit_prediction_settings {
 6067            EditPredictionSettings::Disabled => false,
 6068            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 6069        }
 6070    }
 6071
 6072    pub fn edit_predictions_enabled(&self) -> bool {
 6073        match self.edit_prediction_settings {
 6074            EditPredictionSettings::Disabled => false,
 6075            EditPredictionSettings::Enabled { .. } => true,
 6076        }
 6077    }
 6078
 6079    fn edit_prediction_requires_modifier(&self) -> bool {
 6080        match self.edit_prediction_settings {
 6081            EditPredictionSettings::Disabled => false,
 6082            EditPredictionSettings::Enabled {
 6083                preview_requires_modifier,
 6084                ..
 6085            } => preview_requires_modifier,
 6086        }
 6087    }
 6088
 6089    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 6090        if self.edit_prediction_provider.is_none() {
 6091            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6092        } else {
 6093            let selection = self.selections.newest_anchor();
 6094            let cursor = selection.head();
 6095
 6096            if let Some((buffer, cursor_buffer_position)) =
 6097                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6098            {
 6099                self.edit_prediction_settings =
 6100                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6101            }
 6102        }
 6103    }
 6104
 6105    fn edit_prediction_settings_at_position(
 6106        &self,
 6107        buffer: &Entity<Buffer>,
 6108        buffer_position: language::Anchor,
 6109        cx: &App,
 6110    ) -> EditPredictionSettings {
 6111        if !self.mode.is_full()
 6112            || !self.show_inline_completions_override.unwrap_or(true)
 6113            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 6114        {
 6115            return EditPredictionSettings::Disabled;
 6116        }
 6117
 6118        let buffer = buffer.read(cx);
 6119
 6120        let file = buffer.file();
 6121
 6122        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 6123            return EditPredictionSettings::Disabled;
 6124        };
 6125
 6126        let by_provider = matches!(
 6127            self.menu_inline_completions_policy,
 6128            MenuInlineCompletionsPolicy::ByProvider
 6129        );
 6130
 6131        let show_in_menu = by_provider
 6132            && self
 6133                .edit_prediction_provider
 6134                .as_ref()
 6135                .map_or(false, |provider| {
 6136                    provider.provider.show_completions_in_menu()
 6137                });
 6138
 6139        let preview_requires_modifier =
 6140            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6141
 6142        EditPredictionSettings::Enabled {
 6143            show_in_menu,
 6144            preview_requires_modifier,
 6145        }
 6146    }
 6147
 6148    fn should_show_edit_predictions(&self) -> bool {
 6149        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6150    }
 6151
 6152    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6153        matches!(
 6154            self.edit_prediction_preview,
 6155            EditPredictionPreview::Active { .. }
 6156        )
 6157    }
 6158
 6159    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6160        let cursor = self.selections.newest_anchor().head();
 6161        if let Some((buffer, cursor_position)) =
 6162            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6163        {
 6164            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6165        } else {
 6166            false
 6167        }
 6168    }
 6169
 6170    pub fn supports_minimap(&self, cx: &App) -> bool {
 6171        !self.minimap_visibility.disabled() && self.is_singleton(cx)
 6172    }
 6173
 6174    fn edit_predictions_enabled_in_buffer(
 6175        &self,
 6176        buffer: &Entity<Buffer>,
 6177        buffer_position: language::Anchor,
 6178        cx: &App,
 6179    ) -> bool {
 6180        maybe!({
 6181            if self.read_only(cx) {
 6182                return Some(false);
 6183            }
 6184            let provider = self.edit_prediction_provider()?;
 6185            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6186                return Some(false);
 6187            }
 6188            let buffer = buffer.read(cx);
 6189            let Some(file) = buffer.file() else {
 6190                return Some(true);
 6191            };
 6192            let settings = all_language_settings(Some(file), cx);
 6193            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6194        })
 6195        .unwrap_or(false)
 6196    }
 6197
 6198    fn cycle_inline_completion(
 6199        &mut self,
 6200        direction: Direction,
 6201        window: &mut Window,
 6202        cx: &mut Context<Self>,
 6203    ) -> Option<()> {
 6204        let provider = self.edit_prediction_provider()?;
 6205        let cursor = self.selections.newest_anchor().head();
 6206        let (buffer, cursor_buffer_position) =
 6207            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6208        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6209            return None;
 6210        }
 6211
 6212        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6213        self.update_visible_inline_completion(window, cx);
 6214
 6215        Some(())
 6216    }
 6217
 6218    pub fn show_inline_completion(
 6219        &mut self,
 6220        _: &ShowEditPrediction,
 6221        window: &mut Window,
 6222        cx: &mut Context<Self>,
 6223    ) {
 6224        if !self.has_active_inline_completion() {
 6225            self.refresh_inline_completion(false, true, window, cx);
 6226            return;
 6227        }
 6228
 6229        self.update_visible_inline_completion(window, cx);
 6230    }
 6231
 6232    pub fn display_cursor_names(
 6233        &mut self,
 6234        _: &DisplayCursorNames,
 6235        window: &mut Window,
 6236        cx: &mut Context<Self>,
 6237    ) {
 6238        self.show_cursor_names(window, cx);
 6239    }
 6240
 6241    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6242        self.show_cursor_names = true;
 6243        cx.notify();
 6244        cx.spawn_in(window, async move |this, cx| {
 6245            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6246            this.update(cx, |this, cx| {
 6247                this.show_cursor_names = false;
 6248                cx.notify()
 6249            })
 6250            .ok()
 6251        })
 6252        .detach();
 6253    }
 6254
 6255    pub fn next_edit_prediction(
 6256        &mut self,
 6257        _: &NextEditPrediction,
 6258        window: &mut Window,
 6259        cx: &mut Context<Self>,
 6260    ) {
 6261        if self.has_active_inline_completion() {
 6262            self.cycle_inline_completion(Direction::Next, window, cx);
 6263        } else {
 6264            let is_copilot_disabled = self
 6265                .refresh_inline_completion(false, true, window, cx)
 6266                .is_none();
 6267            if is_copilot_disabled {
 6268                cx.propagate();
 6269            }
 6270        }
 6271    }
 6272
 6273    pub fn previous_edit_prediction(
 6274        &mut self,
 6275        _: &PreviousEditPrediction,
 6276        window: &mut Window,
 6277        cx: &mut Context<Self>,
 6278    ) {
 6279        if self.has_active_inline_completion() {
 6280            self.cycle_inline_completion(Direction::Prev, window, cx);
 6281        } else {
 6282            let is_copilot_disabled = self
 6283                .refresh_inline_completion(false, true, window, cx)
 6284                .is_none();
 6285            if is_copilot_disabled {
 6286                cx.propagate();
 6287            }
 6288        }
 6289    }
 6290
 6291    pub fn accept_edit_prediction(
 6292        &mut self,
 6293        _: &AcceptEditPrediction,
 6294        window: &mut Window,
 6295        cx: &mut Context<Self>,
 6296    ) {
 6297        if self.show_edit_predictions_in_menu() {
 6298            self.hide_context_menu(window, cx);
 6299        }
 6300
 6301        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6302            return;
 6303        };
 6304
 6305        self.report_inline_completion_event(
 6306            active_inline_completion.completion_id.clone(),
 6307            true,
 6308            cx,
 6309        );
 6310
 6311        match &active_inline_completion.completion {
 6312            InlineCompletion::Move { target, .. } => {
 6313                let target = *target;
 6314
 6315                if let Some(position_map) = &self.last_position_map {
 6316                    if position_map
 6317                        .visible_row_range
 6318                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6319                        || !self.edit_prediction_requires_modifier()
 6320                    {
 6321                        self.unfold_ranges(&[target..target], true, false, cx);
 6322                        // Note that this is also done in vim's handler of the Tab action.
 6323                        self.change_selections(
 6324                            Some(Autoscroll::newest()),
 6325                            window,
 6326                            cx,
 6327                            |selections| {
 6328                                selections.select_anchor_ranges([target..target]);
 6329                            },
 6330                        );
 6331                        self.clear_row_highlights::<EditPredictionPreview>();
 6332
 6333                        self.edit_prediction_preview
 6334                            .set_previous_scroll_position(None);
 6335                    } else {
 6336                        self.edit_prediction_preview
 6337                            .set_previous_scroll_position(Some(
 6338                                position_map.snapshot.scroll_anchor,
 6339                            ));
 6340
 6341                        self.highlight_rows::<EditPredictionPreview>(
 6342                            target..target,
 6343                            cx.theme().colors().editor_highlighted_line_background,
 6344                            RowHighlightOptions {
 6345                                autoscroll: true,
 6346                                ..Default::default()
 6347                            },
 6348                            cx,
 6349                        );
 6350                        self.request_autoscroll(Autoscroll::fit(), cx);
 6351                    }
 6352                }
 6353            }
 6354            InlineCompletion::Edit { edits, .. } => {
 6355                if let Some(provider) = self.edit_prediction_provider() {
 6356                    provider.accept(cx);
 6357                }
 6358
 6359                let snapshot = self.buffer.read(cx).snapshot(cx);
 6360                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6361
 6362                self.buffer.update(cx, |buffer, cx| {
 6363                    buffer.edit(edits.iter().cloned(), None, cx)
 6364                });
 6365
 6366                self.change_selections(None, window, cx, |s| {
 6367                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6368                });
 6369
 6370                self.update_visible_inline_completion(window, cx);
 6371                if self.active_inline_completion.is_none() {
 6372                    self.refresh_inline_completion(true, true, window, cx);
 6373                }
 6374
 6375                cx.notify();
 6376            }
 6377        }
 6378
 6379        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6380    }
 6381
 6382    pub fn accept_partial_inline_completion(
 6383        &mut self,
 6384        _: &AcceptPartialEditPrediction,
 6385        window: &mut Window,
 6386        cx: &mut Context<Self>,
 6387    ) {
 6388        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6389            return;
 6390        };
 6391        if self.selections.count() != 1 {
 6392            return;
 6393        }
 6394
 6395        self.report_inline_completion_event(
 6396            active_inline_completion.completion_id.clone(),
 6397            true,
 6398            cx,
 6399        );
 6400
 6401        match &active_inline_completion.completion {
 6402            InlineCompletion::Move { target, .. } => {
 6403                let target = *target;
 6404                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6405                    selections.select_anchor_ranges([target..target]);
 6406                });
 6407            }
 6408            InlineCompletion::Edit { edits, .. } => {
 6409                // Find an insertion that starts at the cursor position.
 6410                let snapshot = self.buffer.read(cx).snapshot(cx);
 6411                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6412                let insertion = edits.iter().find_map(|(range, text)| {
 6413                    let range = range.to_offset(&snapshot);
 6414                    if range.is_empty() && range.start == cursor_offset {
 6415                        Some(text)
 6416                    } else {
 6417                        None
 6418                    }
 6419                });
 6420
 6421                if let Some(text) = insertion {
 6422                    let mut partial_completion = text
 6423                        .chars()
 6424                        .by_ref()
 6425                        .take_while(|c| c.is_alphabetic())
 6426                        .collect::<String>();
 6427                    if partial_completion.is_empty() {
 6428                        partial_completion = text
 6429                            .chars()
 6430                            .by_ref()
 6431                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6432                            .collect::<String>();
 6433                    }
 6434
 6435                    cx.emit(EditorEvent::InputHandled {
 6436                        utf16_range_to_replace: None,
 6437                        text: partial_completion.clone().into(),
 6438                    });
 6439
 6440                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6441
 6442                    self.refresh_inline_completion(true, true, window, cx);
 6443                    cx.notify();
 6444                } else {
 6445                    self.accept_edit_prediction(&Default::default(), window, cx);
 6446                }
 6447            }
 6448        }
 6449    }
 6450
 6451    fn discard_inline_completion(
 6452        &mut self,
 6453        should_report_inline_completion_event: bool,
 6454        cx: &mut Context<Self>,
 6455    ) -> bool {
 6456        if should_report_inline_completion_event {
 6457            let completion_id = self
 6458                .active_inline_completion
 6459                .as_ref()
 6460                .and_then(|active_completion| active_completion.completion_id.clone());
 6461
 6462            self.report_inline_completion_event(completion_id, false, cx);
 6463        }
 6464
 6465        if let Some(provider) = self.edit_prediction_provider() {
 6466            provider.discard(cx);
 6467        }
 6468
 6469        self.take_active_inline_completion(cx)
 6470    }
 6471
 6472    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6473        let Some(provider) = self.edit_prediction_provider() else {
 6474            return;
 6475        };
 6476
 6477        let Some((_, buffer, _)) = self
 6478            .buffer
 6479            .read(cx)
 6480            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6481        else {
 6482            return;
 6483        };
 6484
 6485        let extension = buffer
 6486            .read(cx)
 6487            .file()
 6488            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6489
 6490        let event_type = match accepted {
 6491            true => "Edit Prediction Accepted",
 6492            false => "Edit Prediction Discarded",
 6493        };
 6494        telemetry::event!(
 6495            event_type,
 6496            provider = provider.name(),
 6497            prediction_id = id,
 6498            suggestion_accepted = accepted,
 6499            file_extension = extension,
 6500        );
 6501    }
 6502
 6503    pub fn has_active_inline_completion(&self) -> bool {
 6504        self.active_inline_completion.is_some()
 6505    }
 6506
 6507    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6508        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6509            return false;
 6510        };
 6511
 6512        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6513        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6514        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6515        true
 6516    }
 6517
 6518    /// Returns true when we're displaying the edit prediction popover below the cursor
 6519    /// like we are not previewing and the LSP autocomplete menu is visible
 6520    /// or we are in `when_holding_modifier` mode.
 6521    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6522        if self.edit_prediction_preview_is_active()
 6523            || !self.show_edit_predictions_in_menu()
 6524            || !self.edit_predictions_enabled()
 6525        {
 6526            return false;
 6527        }
 6528
 6529        if self.has_visible_completions_menu() {
 6530            return true;
 6531        }
 6532
 6533        has_completion && self.edit_prediction_requires_modifier()
 6534    }
 6535
 6536    fn handle_modifiers_changed(
 6537        &mut self,
 6538        modifiers: Modifiers,
 6539        position_map: &PositionMap,
 6540        window: &mut Window,
 6541        cx: &mut Context<Self>,
 6542    ) {
 6543        if self.show_edit_predictions_in_menu() {
 6544            self.update_edit_prediction_preview(&modifiers, window, cx);
 6545        }
 6546
 6547        self.update_selection_mode(&modifiers, position_map, window, cx);
 6548
 6549        let mouse_position = window.mouse_position();
 6550        if !position_map.text_hitbox.is_hovered(window) {
 6551            return;
 6552        }
 6553
 6554        self.update_hovered_link(
 6555            position_map.point_for_position(mouse_position),
 6556            &position_map.snapshot,
 6557            modifiers,
 6558            window,
 6559            cx,
 6560        )
 6561    }
 6562
 6563    fn update_selection_mode(
 6564        &mut self,
 6565        modifiers: &Modifiers,
 6566        position_map: &PositionMap,
 6567        window: &mut Window,
 6568        cx: &mut Context<Self>,
 6569    ) {
 6570        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6571            return;
 6572        }
 6573
 6574        let mouse_position = window.mouse_position();
 6575        let point_for_position = position_map.point_for_position(mouse_position);
 6576        let position = point_for_position.previous_valid;
 6577
 6578        self.select(
 6579            SelectPhase::BeginColumnar {
 6580                position,
 6581                reset: false,
 6582                goal_column: point_for_position.exact_unclipped.column(),
 6583            },
 6584            window,
 6585            cx,
 6586        );
 6587    }
 6588
 6589    fn update_edit_prediction_preview(
 6590        &mut self,
 6591        modifiers: &Modifiers,
 6592        window: &mut Window,
 6593        cx: &mut Context<Self>,
 6594    ) {
 6595        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6596        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6597            return;
 6598        };
 6599
 6600        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6601            if matches!(
 6602                self.edit_prediction_preview,
 6603                EditPredictionPreview::Inactive { .. }
 6604            ) {
 6605                self.edit_prediction_preview = EditPredictionPreview::Active {
 6606                    previous_scroll_position: None,
 6607                    since: Instant::now(),
 6608                };
 6609
 6610                self.update_visible_inline_completion(window, cx);
 6611                cx.notify();
 6612            }
 6613        } else if let EditPredictionPreview::Active {
 6614            previous_scroll_position,
 6615            since,
 6616        } = self.edit_prediction_preview
 6617        {
 6618            if let (Some(previous_scroll_position), Some(position_map)) =
 6619                (previous_scroll_position, self.last_position_map.as_ref())
 6620            {
 6621                self.set_scroll_position(
 6622                    previous_scroll_position
 6623                        .scroll_position(&position_map.snapshot.display_snapshot),
 6624                    window,
 6625                    cx,
 6626                );
 6627            }
 6628
 6629            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6630                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6631            };
 6632            self.clear_row_highlights::<EditPredictionPreview>();
 6633            self.update_visible_inline_completion(window, cx);
 6634            cx.notify();
 6635        }
 6636    }
 6637
 6638    fn update_visible_inline_completion(
 6639        &mut self,
 6640        _window: &mut Window,
 6641        cx: &mut Context<Self>,
 6642    ) -> Option<()> {
 6643        let selection = self.selections.newest_anchor();
 6644        let cursor = selection.head();
 6645        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6646        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6647        let excerpt_id = cursor.excerpt_id;
 6648
 6649        let show_in_menu = self.show_edit_predictions_in_menu();
 6650        let completions_menu_has_precedence = !show_in_menu
 6651            && (self.context_menu.borrow().is_some()
 6652                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6653
 6654        if completions_menu_has_precedence
 6655            || !offset_selection.is_empty()
 6656            || self
 6657                .active_inline_completion
 6658                .as_ref()
 6659                .map_or(false, |completion| {
 6660                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6661                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6662                    !invalidation_range.contains(&offset_selection.head())
 6663                })
 6664        {
 6665            self.discard_inline_completion(false, cx);
 6666            return None;
 6667        }
 6668
 6669        self.take_active_inline_completion(cx);
 6670        let Some(provider) = self.edit_prediction_provider() else {
 6671            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6672            return None;
 6673        };
 6674
 6675        let (buffer, cursor_buffer_position) =
 6676            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6677
 6678        self.edit_prediction_settings =
 6679            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6680
 6681        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6682
 6683        if self.edit_prediction_indent_conflict {
 6684            let cursor_point = cursor.to_point(&multibuffer);
 6685
 6686            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6687
 6688            if let Some((_, indent)) = indents.iter().next() {
 6689                if indent.len == cursor_point.column {
 6690                    self.edit_prediction_indent_conflict = false;
 6691                }
 6692            }
 6693        }
 6694
 6695        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6696        let edits = inline_completion
 6697            .edits
 6698            .into_iter()
 6699            .flat_map(|(range, new_text)| {
 6700                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6701                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6702                Some((start..end, new_text))
 6703            })
 6704            .collect::<Vec<_>>();
 6705        if edits.is_empty() {
 6706            return None;
 6707        }
 6708
 6709        let first_edit_start = edits.first().unwrap().0.start;
 6710        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6711        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6712
 6713        let last_edit_end = edits.last().unwrap().0.end;
 6714        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6715        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6716
 6717        let cursor_row = cursor.to_point(&multibuffer).row;
 6718
 6719        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6720
 6721        let mut inlay_ids = Vec::new();
 6722        let invalidation_row_range;
 6723        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6724            Some(cursor_row..edit_end_row)
 6725        } else if cursor_row > edit_end_row {
 6726            Some(edit_start_row..cursor_row)
 6727        } else {
 6728            None
 6729        };
 6730        let is_move =
 6731            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6732        let completion = if is_move {
 6733            invalidation_row_range =
 6734                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6735            let target = first_edit_start;
 6736            InlineCompletion::Move { target, snapshot }
 6737        } else {
 6738            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6739                && !self.inline_completions_hidden_for_vim_mode;
 6740
 6741            if show_completions_in_buffer {
 6742                if edits
 6743                    .iter()
 6744                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6745                {
 6746                    let mut inlays = Vec::new();
 6747                    for (range, new_text) in &edits {
 6748                        let inlay = Inlay::inline_completion(
 6749                            post_inc(&mut self.next_inlay_id),
 6750                            range.start,
 6751                            new_text.as_str(),
 6752                        );
 6753                        inlay_ids.push(inlay.id);
 6754                        inlays.push(inlay);
 6755                    }
 6756
 6757                    self.splice_inlays(&[], inlays, cx);
 6758                } else {
 6759                    let background_color = cx.theme().status().deleted_background;
 6760                    self.highlight_text::<InlineCompletionHighlight>(
 6761                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6762                        HighlightStyle {
 6763                            background_color: Some(background_color),
 6764                            ..Default::default()
 6765                        },
 6766                        cx,
 6767                    );
 6768                }
 6769            }
 6770
 6771            invalidation_row_range = edit_start_row..edit_end_row;
 6772
 6773            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6774                if provider.show_tab_accept_marker() {
 6775                    EditDisplayMode::TabAccept
 6776                } else {
 6777                    EditDisplayMode::Inline
 6778                }
 6779            } else {
 6780                EditDisplayMode::DiffPopover
 6781            };
 6782
 6783            InlineCompletion::Edit {
 6784                edits,
 6785                edit_preview: inline_completion.edit_preview,
 6786                display_mode,
 6787                snapshot,
 6788            }
 6789        };
 6790
 6791        let invalidation_range = multibuffer
 6792            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6793            ..multibuffer.anchor_after(Point::new(
 6794                invalidation_row_range.end,
 6795                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6796            ));
 6797
 6798        self.stale_inline_completion_in_menu = None;
 6799        self.active_inline_completion = Some(InlineCompletionState {
 6800            inlay_ids,
 6801            completion,
 6802            completion_id: inline_completion.id,
 6803            invalidation_range,
 6804        });
 6805
 6806        cx.notify();
 6807
 6808        Some(())
 6809    }
 6810
 6811    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6812        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6813    }
 6814
 6815    fn clear_tasks(&mut self) {
 6816        self.tasks.clear()
 6817    }
 6818
 6819    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6820        if self.tasks.insert(key, value).is_some() {
 6821            // This case should hopefully be rare, but just in case...
 6822            log::error!(
 6823                "multiple different run targets found on a single line, only the last target will be rendered"
 6824            )
 6825        }
 6826    }
 6827
 6828    /// Get all display points of breakpoints that will be rendered within editor
 6829    ///
 6830    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6831    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6832    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6833    fn active_breakpoints(
 6834        &self,
 6835        range: Range<DisplayRow>,
 6836        window: &mut Window,
 6837        cx: &mut Context<Self>,
 6838    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6839        let mut breakpoint_display_points = HashMap::default();
 6840
 6841        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6842            return breakpoint_display_points;
 6843        };
 6844
 6845        let snapshot = self.snapshot(window, cx);
 6846
 6847        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6848        let Some(project) = self.project.as_ref() else {
 6849            return breakpoint_display_points;
 6850        };
 6851
 6852        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6853            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6854
 6855        for (buffer_snapshot, range, excerpt_id) in
 6856            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6857        {
 6858            let Some(buffer) = project.read_with(cx, |this, cx| {
 6859                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6860            }) else {
 6861                continue;
 6862            };
 6863            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6864                &buffer,
 6865                Some(
 6866                    buffer_snapshot.anchor_before(range.start)
 6867                        ..buffer_snapshot.anchor_after(range.end),
 6868                ),
 6869                buffer_snapshot,
 6870                cx,
 6871            );
 6872            for (anchor, breakpoint) in breakpoints {
 6873                let multi_buffer_anchor =
 6874                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6875                let position = multi_buffer_anchor
 6876                    .to_point(&multi_buffer_snapshot)
 6877                    .to_display_point(&snapshot);
 6878
 6879                breakpoint_display_points
 6880                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6881            }
 6882        }
 6883
 6884        breakpoint_display_points
 6885    }
 6886
 6887    fn breakpoint_context_menu(
 6888        &self,
 6889        anchor: Anchor,
 6890        window: &mut Window,
 6891        cx: &mut Context<Self>,
 6892    ) -> Entity<ui::ContextMenu> {
 6893        let weak_editor = cx.weak_entity();
 6894        let focus_handle = self.focus_handle(cx);
 6895
 6896        let row = self
 6897            .buffer
 6898            .read(cx)
 6899            .snapshot(cx)
 6900            .summary_for_anchor::<Point>(&anchor)
 6901            .row;
 6902
 6903        let breakpoint = self
 6904            .breakpoint_at_row(row, window, cx)
 6905            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6906
 6907        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6908            "Edit Log Breakpoint"
 6909        } else {
 6910            "Set Log Breakpoint"
 6911        };
 6912
 6913        let condition_breakpoint_msg = if breakpoint
 6914            .as_ref()
 6915            .is_some_and(|bp| bp.1.condition.is_some())
 6916        {
 6917            "Edit Condition Breakpoint"
 6918        } else {
 6919            "Set Condition Breakpoint"
 6920        };
 6921
 6922        let hit_condition_breakpoint_msg = if breakpoint
 6923            .as_ref()
 6924            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6925        {
 6926            "Edit Hit Condition Breakpoint"
 6927        } else {
 6928            "Set Hit Condition Breakpoint"
 6929        };
 6930
 6931        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6932            "Unset Breakpoint"
 6933        } else {
 6934            "Set Breakpoint"
 6935        };
 6936
 6937        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6938            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6939
 6940        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6941            BreakpointState::Enabled => Some("Disable"),
 6942            BreakpointState::Disabled => Some("Enable"),
 6943        });
 6944
 6945        let (anchor, breakpoint) =
 6946            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6947
 6948        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6949            menu.on_blur_subscription(Subscription::new(|| {}))
 6950                .context(focus_handle)
 6951                .when(run_to_cursor, |this| {
 6952                    let weak_editor = weak_editor.clone();
 6953                    this.entry("Run to cursor", None, move |window, cx| {
 6954                        weak_editor
 6955                            .update(cx, |editor, cx| {
 6956                                editor.change_selections(None, window, cx, |s| {
 6957                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6958                                });
 6959                            })
 6960                            .ok();
 6961
 6962                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6963                    })
 6964                    .separator()
 6965                })
 6966                .when_some(toggle_state_msg, |this, msg| {
 6967                    this.entry(msg, None, {
 6968                        let weak_editor = weak_editor.clone();
 6969                        let breakpoint = breakpoint.clone();
 6970                        move |_window, cx| {
 6971                            weak_editor
 6972                                .update(cx, |this, cx| {
 6973                                    this.edit_breakpoint_at_anchor(
 6974                                        anchor,
 6975                                        breakpoint.as_ref().clone(),
 6976                                        BreakpointEditAction::InvertState,
 6977                                        cx,
 6978                                    );
 6979                                })
 6980                                .log_err();
 6981                        }
 6982                    })
 6983                })
 6984                .entry(set_breakpoint_msg, None, {
 6985                    let weak_editor = weak_editor.clone();
 6986                    let breakpoint = breakpoint.clone();
 6987                    move |_window, cx| {
 6988                        weak_editor
 6989                            .update(cx, |this, cx| {
 6990                                this.edit_breakpoint_at_anchor(
 6991                                    anchor,
 6992                                    breakpoint.as_ref().clone(),
 6993                                    BreakpointEditAction::Toggle,
 6994                                    cx,
 6995                                );
 6996                            })
 6997                            .log_err();
 6998                    }
 6999                })
 7000                .entry(log_breakpoint_msg, None, {
 7001                    let breakpoint = breakpoint.clone();
 7002                    let weak_editor = weak_editor.clone();
 7003                    move |window, cx| {
 7004                        weak_editor
 7005                            .update(cx, |this, cx| {
 7006                                this.add_edit_breakpoint_block(
 7007                                    anchor,
 7008                                    breakpoint.as_ref(),
 7009                                    BreakpointPromptEditAction::Log,
 7010                                    window,
 7011                                    cx,
 7012                                );
 7013                            })
 7014                            .log_err();
 7015                    }
 7016                })
 7017                .entry(condition_breakpoint_msg, None, {
 7018                    let breakpoint = breakpoint.clone();
 7019                    let weak_editor = weak_editor.clone();
 7020                    move |window, cx| {
 7021                        weak_editor
 7022                            .update(cx, |this, cx| {
 7023                                this.add_edit_breakpoint_block(
 7024                                    anchor,
 7025                                    breakpoint.as_ref(),
 7026                                    BreakpointPromptEditAction::Condition,
 7027                                    window,
 7028                                    cx,
 7029                                );
 7030                            })
 7031                            .log_err();
 7032                    }
 7033                })
 7034                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 7035                    weak_editor
 7036                        .update(cx, |this, cx| {
 7037                            this.add_edit_breakpoint_block(
 7038                                anchor,
 7039                                breakpoint.as_ref(),
 7040                                BreakpointPromptEditAction::HitCondition,
 7041                                window,
 7042                                cx,
 7043                            );
 7044                        })
 7045                        .log_err();
 7046                })
 7047        })
 7048    }
 7049
 7050    fn render_breakpoint(
 7051        &self,
 7052        position: Anchor,
 7053        row: DisplayRow,
 7054        breakpoint: &Breakpoint,
 7055        cx: &mut Context<Self>,
 7056    ) -> IconButton {
 7057        // Is it a breakpoint that shows up when hovering over gutter?
 7058        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 7059            (false, false),
 7060            |PhantomBreakpointIndicator {
 7061                 is_active,
 7062                 display_row,
 7063                 collides_with_existing_breakpoint,
 7064             }| {
 7065                (
 7066                    is_active && display_row == row,
 7067                    collides_with_existing_breakpoint,
 7068                )
 7069            },
 7070        );
 7071
 7072        let (color, icon) = {
 7073            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 7074                (false, false) => ui::IconName::DebugBreakpoint,
 7075                (true, false) => ui::IconName::DebugLogBreakpoint,
 7076                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 7077                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 7078            };
 7079
 7080            let color = if is_phantom {
 7081                Color::Hint
 7082            } else {
 7083                Color::Debugger
 7084            };
 7085
 7086            (color, icon)
 7087        };
 7088
 7089        let breakpoint = Arc::from(breakpoint.clone());
 7090
 7091        let alt_as_text = gpui::Keystroke {
 7092            modifiers: Modifiers::secondary_key(),
 7093            ..Default::default()
 7094        };
 7095        let primary_action_text = if breakpoint.is_disabled() {
 7096            "enable"
 7097        } else if is_phantom && !collides_with_existing {
 7098            "set"
 7099        } else {
 7100            "unset"
 7101        };
 7102        let mut primary_text = format!("Click to {primary_action_text}");
 7103        if collides_with_existing && !breakpoint.is_disabled() {
 7104            use std::fmt::Write;
 7105            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7106        }
 7107        let primary_text = SharedString::from(primary_text);
 7108        let focus_handle = self.focus_handle.clone();
 7109        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7110            .icon_size(IconSize::XSmall)
 7111            .size(ui::ButtonSize::None)
 7112            .icon_color(color)
 7113            .style(ButtonStyle::Transparent)
 7114            .on_click(cx.listener({
 7115                let breakpoint = breakpoint.clone();
 7116
 7117                move |editor, event: &ClickEvent, window, cx| {
 7118                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7119                        BreakpointEditAction::InvertState
 7120                    } else {
 7121                        BreakpointEditAction::Toggle
 7122                    };
 7123
 7124                    window.focus(&editor.focus_handle(cx));
 7125                    editor.edit_breakpoint_at_anchor(
 7126                        position,
 7127                        breakpoint.as_ref().clone(),
 7128                        edit_action,
 7129                        cx,
 7130                    );
 7131                }
 7132            }))
 7133            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7134                editor.set_breakpoint_context_menu(
 7135                    row,
 7136                    Some(position),
 7137                    event.down.position,
 7138                    window,
 7139                    cx,
 7140                );
 7141            }))
 7142            .tooltip(move |window, cx| {
 7143                Tooltip::with_meta_in(
 7144                    primary_text.clone(),
 7145                    None,
 7146                    "Right-click for more options",
 7147                    &focus_handle,
 7148                    window,
 7149                    cx,
 7150                )
 7151            })
 7152    }
 7153
 7154    fn build_tasks_context(
 7155        project: &Entity<Project>,
 7156        buffer: &Entity<Buffer>,
 7157        buffer_row: u32,
 7158        tasks: &Arc<RunnableTasks>,
 7159        cx: &mut Context<Self>,
 7160    ) -> Task<Option<task::TaskContext>> {
 7161        let position = Point::new(buffer_row, tasks.column);
 7162        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7163        let location = Location {
 7164            buffer: buffer.clone(),
 7165            range: range_start..range_start,
 7166        };
 7167        // Fill in the environmental variables from the tree-sitter captures
 7168        let mut captured_task_variables = TaskVariables::default();
 7169        for (capture_name, value) in tasks.extra_variables.clone() {
 7170            captured_task_variables.insert(
 7171                task::VariableName::Custom(capture_name.into()),
 7172                value.clone(),
 7173            );
 7174        }
 7175        project.update(cx, |project, cx| {
 7176            project.task_store().update(cx, |task_store, cx| {
 7177                task_store.task_context_for_location(captured_task_variables, location, cx)
 7178            })
 7179        })
 7180    }
 7181
 7182    pub fn spawn_nearest_task(
 7183        &mut self,
 7184        action: &SpawnNearestTask,
 7185        window: &mut Window,
 7186        cx: &mut Context<Self>,
 7187    ) {
 7188        let Some((workspace, _)) = self.workspace.clone() else {
 7189            return;
 7190        };
 7191        let Some(project) = self.project.clone() else {
 7192            return;
 7193        };
 7194
 7195        // Try to find a closest, enclosing node using tree-sitter that has a
 7196        // task
 7197        let Some((buffer, buffer_row, tasks)) = self
 7198            .find_enclosing_node_task(cx)
 7199            // Or find the task that's closest in row-distance.
 7200            .or_else(|| self.find_closest_task(cx))
 7201        else {
 7202            return;
 7203        };
 7204
 7205        let reveal_strategy = action.reveal;
 7206        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7207        cx.spawn_in(window, async move |_, cx| {
 7208            let context = task_context.await?;
 7209            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7210
 7211            let resolved = &mut resolved_task.resolved;
 7212            resolved.reveal = reveal_strategy;
 7213
 7214            workspace
 7215                .update_in(cx, |workspace, window, cx| {
 7216                    workspace.schedule_resolved_task(
 7217                        task_source_kind,
 7218                        resolved_task,
 7219                        false,
 7220                        window,
 7221                        cx,
 7222                    );
 7223                })
 7224                .ok()
 7225        })
 7226        .detach();
 7227    }
 7228
 7229    fn find_closest_task(
 7230        &mut self,
 7231        cx: &mut Context<Self>,
 7232    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7233        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7234
 7235        let ((buffer_id, row), tasks) = self
 7236            .tasks
 7237            .iter()
 7238            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7239
 7240        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7241        let tasks = Arc::new(tasks.to_owned());
 7242        Some((buffer, *row, tasks))
 7243    }
 7244
 7245    fn find_enclosing_node_task(
 7246        &mut self,
 7247        cx: &mut Context<Self>,
 7248    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7249        let snapshot = self.buffer.read(cx).snapshot(cx);
 7250        let offset = self.selections.newest::<usize>(cx).head();
 7251        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7252        let buffer_id = excerpt.buffer().remote_id();
 7253
 7254        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7255        let mut cursor = layer.node().walk();
 7256
 7257        while cursor.goto_first_child_for_byte(offset).is_some() {
 7258            if cursor.node().end_byte() == offset {
 7259                cursor.goto_next_sibling();
 7260            }
 7261        }
 7262
 7263        // Ascend to the smallest ancestor that contains the range and has a task.
 7264        loop {
 7265            let node = cursor.node();
 7266            let node_range = node.byte_range();
 7267            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7268
 7269            // Check if this node contains our offset
 7270            if node_range.start <= offset && node_range.end >= offset {
 7271                // If it contains offset, check for task
 7272                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7273                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7274                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7275                }
 7276            }
 7277
 7278            if !cursor.goto_parent() {
 7279                break;
 7280            }
 7281        }
 7282        None
 7283    }
 7284
 7285    fn render_run_indicator(
 7286        &self,
 7287        _style: &EditorStyle,
 7288        is_active: bool,
 7289        row: DisplayRow,
 7290        breakpoint: Option<(Anchor, Breakpoint)>,
 7291        cx: &mut Context<Self>,
 7292    ) -> IconButton {
 7293        let color = Color::Muted;
 7294        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7295
 7296        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7297            .shape(ui::IconButtonShape::Square)
 7298            .icon_size(IconSize::XSmall)
 7299            .icon_color(color)
 7300            .toggle_state(is_active)
 7301            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7302                let quick_launch = e.down.button == MouseButton::Left;
 7303                window.focus(&editor.focus_handle(cx));
 7304                editor.toggle_code_actions(
 7305                    &ToggleCodeActions {
 7306                        deployed_from_indicator: Some(row),
 7307                        quick_launch,
 7308                    },
 7309                    window,
 7310                    cx,
 7311                );
 7312            }))
 7313            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7314                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7315            }))
 7316    }
 7317
 7318    pub fn context_menu_visible(&self) -> bool {
 7319        !self.edit_prediction_preview_is_active()
 7320            && self
 7321                .context_menu
 7322                .borrow()
 7323                .as_ref()
 7324                .map_or(false, |menu| menu.visible())
 7325    }
 7326
 7327    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7328        self.context_menu
 7329            .borrow()
 7330            .as_ref()
 7331            .map(|menu| menu.origin())
 7332    }
 7333
 7334    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7335        self.context_menu_options = Some(options);
 7336    }
 7337
 7338    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7339    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7340
 7341    fn render_edit_prediction_popover(
 7342        &mut self,
 7343        text_bounds: &Bounds<Pixels>,
 7344        content_origin: gpui::Point<Pixels>,
 7345        right_margin: Pixels,
 7346        editor_snapshot: &EditorSnapshot,
 7347        visible_row_range: Range<DisplayRow>,
 7348        scroll_top: f32,
 7349        scroll_bottom: f32,
 7350        line_layouts: &[LineWithInvisibles],
 7351        line_height: Pixels,
 7352        scroll_pixel_position: gpui::Point<Pixels>,
 7353        newest_selection_head: Option<DisplayPoint>,
 7354        editor_width: Pixels,
 7355        style: &EditorStyle,
 7356        window: &mut Window,
 7357        cx: &mut App,
 7358    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7359        if self.mode().is_minimap() {
 7360            return None;
 7361        }
 7362        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7363
 7364        if self.edit_prediction_visible_in_cursor_popover(true) {
 7365            return None;
 7366        }
 7367
 7368        match &active_inline_completion.completion {
 7369            InlineCompletion::Move { target, .. } => {
 7370                let target_display_point = target.to_display_point(editor_snapshot);
 7371
 7372                if self.edit_prediction_requires_modifier() {
 7373                    if !self.edit_prediction_preview_is_active() {
 7374                        return None;
 7375                    }
 7376
 7377                    self.render_edit_prediction_modifier_jump_popover(
 7378                        text_bounds,
 7379                        content_origin,
 7380                        visible_row_range,
 7381                        line_layouts,
 7382                        line_height,
 7383                        scroll_pixel_position,
 7384                        newest_selection_head,
 7385                        target_display_point,
 7386                        window,
 7387                        cx,
 7388                    )
 7389                } else {
 7390                    self.render_edit_prediction_eager_jump_popover(
 7391                        text_bounds,
 7392                        content_origin,
 7393                        editor_snapshot,
 7394                        visible_row_range,
 7395                        scroll_top,
 7396                        scroll_bottom,
 7397                        line_height,
 7398                        scroll_pixel_position,
 7399                        target_display_point,
 7400                        editor_width,
 7401                        window,
 7402                        cx,
 7403                    )
 7404                }
 7405            }
 7406            InlineCompletion::Edit {
 7407                display_mode: EditDisplayMode::Inline,
 7408                ..
 7409            } => None,
 7410            InlineCompletion::Edit {
 7411                display_mode: EditDisplayMode::TabAccept,
 7412                edits,
 7413                ..
 7414            } => {
 7415                let range = &edits.first()?.0;
 7416                let target_display_point = range.end.to_display_point(editor_snapshot);
 7417
 7418                self.render_edit_prediction_end_of_line_popover(
 7419                    "Accept",
 7420                    editor_snapshot,
 7421                    visible_row_range,
 7422                    target_display_point,
 7423                    line_height,
 7424                    scroll_pixel_position,
 7425                    content_origin,
 7426                    editor_width,
 7427                    window,
 7428                    cx,
 7429                )
 7430            }
 7431            InlineCompletion::Edit {
 7432                edits,
 7433                edit_preview,
 7434                display_mode: EditDisplayMode::DiffPopover,
 7435                snapshot,
 7436            } => self.render_edit_prediction_diff_popover(
 7437                text_bounds,
 7438                content_origin,
 7439                right_margin,
 7440                editor_snapshot,
 7441                visible_row_range,
 7442                line_layouts,
 7443                line_height,
 7444                scroll_pixel_position,
 7445                newest_selection_head,
 7446                editor_width,
 7447                style,
 7448                edits,
 7449                edit_preview,
 7450                snapshot,
 7451                window,
 7452                cx,
 7453            ),
 7454        }
 7455    }
 7456
 7457    fn render_edit_prediction_modifier_jump_popover(
 7458        &mut self,
 7459        text_bounds: &Bounds<Pixels>,
 7460        content_origin: gpui::Point<Pixels>,
 7461        visible_row_range: Range<DisplayRow>,
 7462        line_layouts: &[LineWithInvisibles],
 7463        line_height: Pixels,
 7464        scroll_pixel_position: gpui::Point<Pixels>,
 7465        newest_selection_head: Option<DisplayPoint>,
 7466        target_display_point: DisplayPoint,
 7467        window: &mut Window,
 7468        cx: &mut App,
 7469    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7470        let scrolled_content_origin =
 7471            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7472
 7473        const SCROLL_PADDING_Y: Pixels = px(12.);
 7474
 7475        if target_display_point.row() < visible_row_range.start {
 7476            return self.render_edit_prediction_scroll_popover(
 7477                |_| SCROLL_PADDING_Y,
 7478                IconName::ArrowUp,
 7479                visible_row_range,
 7480                line_layouts,
 7481                newest_selection_head,
 7482                scrolled_content_origin,
 7483                window,
 7484                cx,
 7485            );
 7486        } else if target_display_point.row() >= visible_row_range.end {
 7487            return self.render_edit_prediction_scroll_popover(
 7488                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7489                IconName::ArrowDown,
 7490                visible_row_range,
 7491                line_layouts,
 7492                newest_selection_head,
 7493                scrolled_content_origin,
 7494                window,
 7495                cx,
 7496            );
 7497        }
 7498
 7499        const POLE_WIDTH: Pixels = px(2.);
 7500
 7501        let line_layout =
 7502            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7503        let target_column = target_display_point.column() as usize;
 7504
 7505        let target_x = line_layout.x_for_index(target_column);
 7506        let target_y =
 7507            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7508
 7509        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7510
 7511        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7512        border_color.l += 0.001;
 7513
 7514        let mut element = v_flex()
 7515            .items_end()
 7516            .when(flag_on_right, |el| el.items_start())
 7517            .child(if flag_on_right {
 7518                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7519                    .rounded_bl(px(0.))
 7520                    .rounded_tl(px(0.))
 7521                    .border_l_2()
 7522                    .border_color(border_color)
 7523            } else {
 7524                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7525                    .rounded_br(px(0.))
 7526                    .rounded_tr(px(0.))
 7527                    .border_r_2()
 7528                    .border_color(border_color)
 7529            })
 7530            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7531            .into_any();
 7532
 7533        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7534
 7535        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7536            - point(
 7537                if flag_on_right {
 7538                    POLE_WIDTH
 7539                } else {
 7540                    size.width - POLE_WIDTH
 7541                },
 7542                size.height - line_height,
 7543            );
 7544
 7545        origin.x = origin.x.max(content_origin.x);
 7546
 7547        element.prepaint_at(origin, window, cx);
 7548
 7549        Some((element, origin))
 7550    }
 7551
 7552    fn render_edit_prediction_scroll_popover(
 7553        &mut self,
 7554        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7555        scroll_icon: IconName,
 7556        visible_row_range: Range<DisplayRow>,
 7557        line_layouts: &[LineWithInvisibles],
 7558        newest_selection_head: Option<DisplayPoint>,
 7559        scrolled_content_origin: gpui::Point<Pixels>,
 7560        window: &mut Window,
 7561        cx: &mut App,
 7562    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7563        let mut element = self
 7564            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7565            .into_any();
 7566
 7567        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7568
 7569        let cursor = newest_selection_head?;
 7570        let cursor_row_layout =
 7571            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7572        let cursor_column = cursor.column() as usize;
 7573
 7574        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7575
 7576        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7577
 7578        element.prepaint_at(origin, window, cx);
 7579        Some((element, origin))
 7580    }
 7581
 7582    fn render_edit_prediction_eager_jump_popover(
 7583        &mut self,
 7584        text_bounds: &Bounds<Pixels>,
 7585        content_origin: gpui::Point<Pixels>,
 7586        editor_snapshot: &EditorSnapshot,
 7587        visible_row_range: Range<DisplayRow>,
 7588        scroll_top: f32,
 7589        scroll_bottom: f32,
 7590        line_height: Pixels,
 7591        scroll_pixel_position: gpui::Point<Pixels>,
 7592        target_display_point: DisplayPoint,
 7593        editor_width: Pixels,
 7594        window: &mut Window,
 7595        cx: &mut App,
 7596    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7597        if target_display_point.row().as_f32() < scroll_top {
 7598            let mut element = self
 7599                .render_edit_prediction_line_popover(
 7600                    "Jump to Edit",
 7601                    Some(IconName::ArrowUp),
 7602                    window,
 7603                    cx,
 7604                )?
 7605                .into_any();
 7606
 7607            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7608            let offset = point(
 7609                (text_bounds.size.width - size.width) / 2.,
 7610                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7611            );
 7612
 7613            let origin = text_bounds.origin + offset;
 7614            element.prepaint_at(origin, window, cx);
 7615            Some((element, origin))
 7616        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7617            let mut element = self
 7618                .render_edit_prediction_line_popover(
 7619                    "Jump to Edit",
 7620                    Some(IconName::ArrowDown),
 7621                    window,
 7622                    cx,
 7623                )?
 7624                .into_any();
 7625
 7626            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7627            let offset = point(
 7628                (text_bounds.size.width - size.width) / 2.,
 7629                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7630            );
 7631
 7632            let origin = text_bounds.origin + offset;
 7633            element.prepaint_at(origin, window, cx);
 7634            Some((element, origin))
 7635        } else {
 7636            self.render_edit_prediction_end_of_line_popover(
 7637                "Jump to Edit",
 7638                editor_snapshot,
 7639                visible_row_range,
 7640                target_display_point,
 7641                line_height,
 7642                scroll_pixel_position,
 7643                content_origin,
 7644                editor_width,
 7645                window,
 7646                cx,
 7647            )
 7648        }
 7649    }
 7650
 7651    fn render_edit_prediction_end_of_line_popover(
 7652        self: &mut Editor,
 7653        label: &'static str,
 7654        editor_snapshot: &EditorSnapshot,
 7655        visible_row_range: Range<DisplayRow>,
 7656        target_display_point: DisplayPoint,
 7657        line_height: Pixels,
 7658        scroll_pixel_position: gpui::Point<Pixels>,
 7659        content_origin: gpui::Point<Pixels>,
 7660        editor_width: Pixels,
 7661        window: &mut Window,
 7662        cx: &mut App,
 7663    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7664        let target_line_end = DisplayPoint::new(
 7665            target_display_point.row(),
 7666            editor_snapshot.line_len(target_display_point.row()),
 7667        );
 7668
 7669        let mut element = self
 7670            .render_edit_prediction_line_popover(label, None, window, cx)?
 7671            .into_any();
 7672
 7673        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7674
 7675        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7676
 7677        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7678        let mut origin = start_point
 7679            + line_origin
 7680            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7681        origin.x = origin.x.max(content_origin.x);
 7682
 7683        let max_x = content_origin.x + editor_width - size.width;
 7684
 7685        if origin.x > max_x {
 7686            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7687
 7688            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7689                origin.y += offset;
 7690                IconName::ArrowUp
 7691            } else {
 7692                origin.y -= offset;
 7693                IconName::ArrowDown
 7694            };
 7695
 7696            element = self
 7697                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7698                .into_any();
 7699
 7700            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7701
 7702            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7703        }
 7704
 7705        element.prepaint_at(origin, window, cx);
 7706        Some((element, origin))
 7707    }
 7708
 7709    fn render_edit_prediction_diff_popover(
 7710        self: &Editor,
 7711        text_bounds: &Bounds<Pixels>,
 7712        content_origin: gpui::Point<Pixels>,
 7713        right_margin: Pixels,
 7714        editor_snapshot: &EditorSnapshot,
 7715        visible_row_range: Range<DisplayRow>,
 7716        line_layouts: &[LineWithInvisibles],
 7717        line_height: Pixels,
 7718        scroll_pixel_position: gpui::Point<Pixels>,
 7719        newest_selection_head: Option<DisplayPoint>,
 7720        editor_width: Pixels,
 7721        style: &EditorStyle,
 7722        edits: &Vec<(Range<Anchor>, String)>,
 7723        edit_preview: &Option<language::EditPreview>,
 7724        snapshot: &language::BufferSnapshot,
 7725        window: &mut Window,
 7726        cx: &mut App,
 7727    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7728        let edit_start = edits
 7729            .first()
 7730            .unwrap()
 7731            .0
 7732            .start
 7733            .to_display_point(editor_snapshot);
 7734        let edit_end = edits
 7735            .last()
 7736            .unwrap()
 7737            .0
 7738            .end
 7739            .to_display_point(editor_snapshot);
 7740
 7741        let is_visible = visible_row_range.contains(&edit_start.row())
 7742            || visible_row_range.contains(&edit_end.row());
 7743        if !is_visible {
 7744            return None;
 7745        }
 7746
 7747        let highlighted_edits =
 7748            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7749
 7750        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7751        let line_count = highlighted_edits.text.lines().count();
 7752
 7753        const BORDER_WIDTH: Pixels = px(1.);
 7754
 7755        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7756        let has_keybind = keybind.is_some();
 7757
 7758        let mut element = h_flex()
 7759            .items_start()
 7760            .child(
 7761                h_flex()
 7762                    .bg(cx.theme().colors().editor_background)
 7763                    .border(BORDER_WIDTH)
 7764                    .shadow_sm()
 7765                    .border_color(cx.theme().colors().border)
 7766                    .rounded_l_lg()
 7767                    .when(line_count > 1, |el| el.rounded_br_lg())
 7768                    .pr_1()
 7769                    .child(styled_text),
 7770            )
 7771            .child(
 7772                h_flex()
 7773                    .h(line_height + BORDER_WIDTH * 2.)
 7774                    .px_1p5()
 7775                    .gap_1()
 7776                    // Workaround: For some reason, there's a gap if we don't do this
 7777                    .ml(-BORDER_WIDTH)
 7778                    .shadow(smallvec![gpui::BoxShadow {
 7779                        color: gpui::black().opacity(0.05),
 7780                        offset: point(px(1.), px(1.)),
 7781                        blur_radius: px(2.),
 7782                        spread_radius: px(0.),
 7783                    }])
 7784                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7785                    .border(BORDER_WIDTH)
 7786                    .border_color(cx.theme().colors().border)
 7787                    .rounded_r_lg()
 7788                    .id("edit_prediction_diff_popover_keybind")
 7789                    .when(!has_keybind, |el| {
 7790                        let status_colors = cx.theme().status();
 7791
 7792                        el.bg(status_colors.error_background)
 7793                            .border_color(status_colors.error.opacity(0.6))
 7794                            .child(Icon::new(IconName::Info).color(Color::Error))
 7795                            .cursor_default()
 7796                            .hoverable_tooltip(move |_window, cx| {
 7797                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7798                            })
 7799                    })
 7800                    .children(keybind),
 7801            )
 7802            .into_any();
 7803
 7804        let longest_row =
 7805            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7806        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7807            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7808        } else {
 7809            layout_line(
 7810                longest_row,
 7811                editor_snapshot,
 7812                style,
 7813                editor_width,
 7814                |_| false,
 7815                window,
 7816                cx,
 7817            )
 7818            .width
 7819        };
 7820
 7821        let viewport_bounds =
 7822            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7823                right: -right_margin,
 7824                ..Default::default()
 7825            });
 7826
 7827        let x_after_longest =
 7828            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7829                - scroll_pixel_position.x;
 7830
 7831        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7832
 7833        // Fully visible if it can be displayed within the window (allow overlapping other
 7834        // panes). However, this is only allowed if the popover starts within text_bounds.
 7835        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7836            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7837
 7838        let mut origin = if can_position_to_the_right {
 7839            point(
 7840                x_after_longest,
 7841                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7842                    - scroll_pixel_position.y,
 7843            )
 7844        } else {
 7845            let cursor_row = newest_selection_head.map(|head| head.row());
 7846            let above_edit = edit_start
 7847                .row()
 7848                .0
 7849                .checked_sub(line_count as u32)
 7850                .map(DisplayRow);
 7851            let below_edit = Some(edit_end.row() + 1);
 7852            let above_cursor =
 7853                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7854            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7855
 7856            // Place the edit popover adjacent to the edit if there is a location
 7857            // available that is onscreen and does not obscure the cursor. Otherwise,
 7858            // place it adjacent to the cursor.
 7859            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7860                .into_iter()
 7861                .flatten()
 7862                .find(|&start_row| {
 7863                    let end_row = start_row + line_count as u32;
 7864                    visible_row_range.contains(&start_row)
 7865                        && visible_row_range.contains(&end_row)
 7866                        && cursor_row.map_or(true, |cursor_row| {
 7867                            !((start_row..end_row).contains(&cursor_row))
 7868                        })
 7869                })?;
 7870
 7871            content_origin
 7872                + point(
 7873                    -scroll_pixel_position.x,
 7874                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7875                )
 7876        };
 7877
 7878        origin.x -= BORDER_WIDTH;
 7879
 7880        window.defer_draw(element, origin, 1);
 7881
 7882        // Do not return an element, since it will already be drawn due to defer_draw.
 7883        None
 7884    }
 7885
 7886    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7887        px(30.)
 7888    }
 7889
 7890    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7891        if self.read_only(cx) {
 7892            cx.theme().players().read_only()
 7893        } else {
 7894            self.style.as_ref().unwrap().local_player
 7895        }
 7896    }
 7897
 7898    fn render_edit_prediction_accept_keybind(
 7899        &self,
 7900        window: &mut Window,
 7901        cx: &App,
 7902    ) -> Option<AnyElement> {
 7903        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7904        let accept_keystroke = accept_binding.keystroke()?;
 7905
 7906        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7907
 7908        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7909            Color::Accent
 7910        } else {
 7911            Color::Muted
 7912        };
 7913
 7914        h_flex()
 7915            .px_0p5()
 7916            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7917            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7918            .text_size(TextSize::XSmall.rems(cx))
 7919            .child(h_flex().children(ui::render_modifiers(
 7920                &accept_keystroke.modifiers,
 7921                PlatformStyle::platform(),
 7922                Some(modifiers_color),
 7923                Some(IconSize::XSmall.rems().into()),
 7924                true,
 7925            )))
 7926            .when(is_platform_style_mac, |parent| {
 7927                parent.child(accept_keystroke.key.clone())
 7928            })
 7929            .when(!is_platform_style_mac, |parent| {
 7930                parent.child(
 7931                    Key::new(
 7932                        util::capitalize(&accept_keystroke.key),
 7933                        Some(Color::Default),
 7934                    )
 7935                    .size(Some(IconSize::XSmall.rems().into())),
 7936                )
 7937            })
 7938            .into_any()
 7939            .into()
 7940    }
 7941
 7942    fn render_edit_prediction_line_popover(
 7943        &self,
 7944        label: impl Into<SharedString>,
 7945        icon: Option<IconName>,
 7946        window: &mut Window,
 7947        cx: &App,
 7948    ) -> Option<Stateful<Div>> {
 7949        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7950
 7951        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7952        let has_keybind = keybind.is_some();
 7953
 7954        let result = h_flex()
 7955            .id("ep-line-popover")
 7956            .py_0p5()
 7957            .pl_1()
 7958            .pr(padding_right)
 7959            .gap_1()
 7960            .rounded_md()
 7961            .border_1()
 7962            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7963            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7964            .shadow_sm()
 7965            .when(!has_keybind, |el| {
 7966                let status_colors = cx.theme().status();
 7967
 7968                el.bg(status_colors.error_background)
 7969                    .border_color(status_colors.error.opacity(0.6))
 7970                    .pl_2()
 7971                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7972                    .cursor_default()
 7973                    .hoverable_tooltip(move |_window, cx| {
 7974                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7975                    })
 7976            })
 7977            .children(keybind)
 7978            .child(
 7979                Label::new(label)
 7980                    .size(LabelSize::Small)
 7981                    .when(!has_keybind, |el| {
 7982                        el.color(cx.theme().status().error.into()).strikethrough()
 7983                    }),
 7984            )
 7985            .when(!has_keybind, |el| {
 7986                el.child(
 7987                    h_flex().ml_1().child(
 7988                        Icon::new(IconName::Info)
 7989                            .size(IconSize::Small)
 7990                            .color(cx.theme().status().error.into()),
 7991                    ),
 7992                )
 7993            })
 7994            .when_some(icon, |element, icon| {
 7995                element.child(
 7996                    div()
 7997                        .mt(px(1.5))
 7998                        .child(Icon::new(icon).size(IconSize::Small)),
 7999                )
 8000            });
 8001
 8002        Some(result)
 8003    }
 8004
 8005    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 8006        let accent_color = cx.theme().colors().text_accent;
 8007        let editor_bg_color = cx.theme().colors().editor_background;
 8008        editor_bg_color.blend(accent_color.opacity(0.1))
 8009    }
 8010
 8011    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 8012        let accent_color = cx.theme().colors().text_accent;
 8013        let editor_bg_color = cx.theme().colors().editor_background;
 8014        editor_bg_color.blend(accent_color.opacity(0.6))
 8015    }
 8016
 8017    fn render_edit_prediction_cursor_popover(
 8018        &self,
 8019        min_width: Pixels,
 8020        max_width: Pixels,
 8021        cursor_point: Point,
 8022        style: &EditorStyle,
 8023        accept_keystroke: Option<&gpui::Keystroke>,
 8024        _window: &Window,
 8025        cx: &mut Context<Editor>,
 8026    ) -> Option<AnyElement> {
 8027        let provider = self.edit_prediction_provider.as_ref()?;
 8028
 8029        if provider.provider.needs_terms_acceptance(cx) {
 8030            return Some(
 8031                h_flex()
 8032                    .min_w(min_width)
 8033                    .flex_1()
 8034                    .px_2()
 8035                    .py_1()
 8036                    .gap_3()
 8037                    .elevation_2(cx)
 8038                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 8039                    .id("accept-terms")
 8040                    .cursor_pointer()
 8041                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 8042                    .on_click(cx.listener(|this, _event, window, cx| {
 8043                        cx.stop_propagation();
 8044                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 8045                        window.dispatch_action(
 8046                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 8047                            cx,
 8048                        );
 8049                    }))
 8050                    .child(
 8051                        h_flex()
 8052                            .flex_1()
 8053                            .gap_2()
 8054                            .child(Icon::new(IconName::ZedPredict))
 8055                            .child(Label::new("Accept Terms of Service"))
 8056                            .child(div().w_full())
 8057                            .child(
 8058                                Icon::new(IconName::ArrowUpRight)
 8059                                    .color(Color::Muted)
 8060                                    .size(IconSize::Small),
 8061                            )
 8062                            .into_any_element(),
 8063                    )
 8064                    .into_any(),
 8065            );
 8066        }
 8067
 8068        let is_refreshing = provider.provider.is_refreshing(cx);
 8069
 8070        fn pending_completion_container() -> Div {
 8071            h_flex()
 8072                .h_full()
 8073                .flex_1()
 8074                .gap_2()
 8075                .child(Icon::new(IconName::ZedPredict))
 8076        }
 8077
 8078        let completion = match &self.active_inline_completion {
 8079            Some(prediction) => {
 8080                if !self.has_visible_completions_menu() {
 8081                    const RADIUS: Pixels = px(6.);
 8082                    const BORDER_WIDTH: Pixels = px(1.);
 8083
 8084                    return Some(
 8085                        h_flex()
 8086                            .elevation_2(cx)
 8087                            .border(BORDER_WIDTH)
 8088                            .border_color(cx.theme().colors().border)
 8089                            .when(accept_keystroke.is_none(), |el| {
 8090                                el.border_color(cx.theme().status().error)
 8091                            })
 8092                            .rounded(RADIUS)
 8093                            .rounded_tl(px(0.))
 8094                            .overflow_hidden()
 8095                            .child(div().px_1p5().child(match &prediction.completion {
 8096                                InlineCompletion::Move { target, snapshot } => {
 8097                                    use text::ToPoint as _;
 8098                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 8099                                    {
 8100                                        Icon::new(IconName::ZedPredictDown)
 8101                                    } else {
 8102                                        Icon::new(IconName::ZedPredictUp)
 8103                                    }
 8104                                }
 8105                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 8106                            }))
 8107                            .child(
 8108                                h_flex()
 8109                                    .gap_1()
 8110                                    .py_1()
 8111                                    .px_2()
 8112                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8113                                    .border_l_1()
 8114                                    .border_color(cx.theme().colors().border)
 8115                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8116                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8117                                        el.child(
 8118                                            Label::new("Hold")
 8119                                                .size(LabelSize::Small)
 8120                                                .when(accept_keystroke.is_none(), |el| {
 8121                                                    el.strikethrough()
 8122                                                })
 8123                                                .line_height_style(LineHeightStyle::UiLabel),
 8124                                        )
 8125                                    })
 8126                                    .id("edit_prediction_cursor_popover_keybind")
 8127                                    .when(accept_keystroke.is_none(), |el| {
 8128                                        let status_colors = cx.theme().status();
 8129
 8130                                        el.bg(status_colors.error_background)
 8131                                            .border_color(status_colors.error.opacity(0.6))
 8132                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8133                                            .cursor_default()
 8134                                            .hoverable_tooltip(move |_window, cx| {
 8135                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8136                                                    .into()
 8137                                            })
 8138                                    })
 8139                                    .when_some(
 8140                                        accept_keystroke.as_ref(),
 8141                                        |el, accept_keystroke| {
 8142                                            el.child(h_flex().children(ui::render_modifiers(
 8143                                                &accept_keystroke.modifiers,
 8144                                                PlatformStyle::platform(),
 8145                                                Some(Color::Default),
 8146                                                Some(IconSize::XSmall.rems().into()),
 8147                                                false,
 8148                                            )))
 8149                                        },
 8150                                    ),
 8151                            )
 8152                            .into_any(),
 8153                    );
 8154                }
 8155
 8156                self.render_edit_prediction_cursor_popover_preview(
 8157                    prediction,
 8158                    cursor_point,
 8159                    style,
 8160                    cx,
 8161                )?
 8162            }
 8163
 8164            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8165                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8166                    stale_completion,
 8167                    cursor_point,
 8168                    style,
 8169                    cx,
 8170                )?,
 8171
 8172                None => {
 8173                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8174                }
 8175            },
 8176
 8177            None => pending_completion_container().child(Label::new("No Prediction")),
 8178        };
 8179
 8180        let completion = if is_refreshing {
 8181            completion
 8182                .with_animation(
 8183                    "loading-completion",
 8184                    Animation::new(Duration::from_secs(2))
 8185                        .repeat()
 8186                        .with_easing(pulsating_between(0.4, 0.8)),
 8187                    |label, delta| label.opacity(delta),
 8188                )
 8189                .into_any_element()
 8190        } else {
 8191            completion.into_any_element()
 8192        };
 8193
 8194        let has_completion = self.active_inline_completion.is_some();
 8195
 8196        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8197        Some(
 8198            h_flex()
 8199                .min_w(min_width)
 8200                .max_w(max_width)
 8201                .flex_1()
 8202                .elevation_2(cx)
 8203                .border_color(cx.theme().colors().border)
 8204                .child(
 8205                    div()
 8206                        .flex_1()
 8207                        .py_1()
 8208                        .px_2()
 8209                        .overflow_hidden()
 8210                        .child(completion),
 8211                )
 8212                .when_some(accept_keystroke, |el, accept_keystroke| {
 8213                    if !accept_keystroke.modifiers.modified() {
 8214                        return el;
 8215                    }
 8216
 8217                    el.child(
 8218                        h_flex()
 8219                            .h_full()
 8220                            .border_l_1()
 8221                            .rounded_r_lg()
 8222                            .border_color(cx.theme().colors().border)
 8223                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8224                            .gap_1()
 8225                            .py_1()
 8226                            .px_2()
 8227                            .child(
 8228                                h_flex()
 8229                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8230                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8231                                    .child(h_flex().children(ui::render_modifiers(
 8232                                        &accept_keystroke.modifiers,
 8233                                        PlatformStyle::platform(),
 8234                                        Some(if !has_completion {
 8235                                            Color::Muted
 8236                                        } else {
 8237                                            Color::Default
 8238                                        }),
 8239                                        None,
 8240                                        false,
 8241                                    ))),
 8242                            )
 8243                            .child(Label::new("Preview").into_any_element())
 8244                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8245                    )
 8246                })
 8247                .into_any(),
 8248        )
 8249    }
 8250
 8251    fn render_edit_prediction_cursor_popover_preview(
 8252        &self,
 8253        completion: &InlineCompletionState,
 8254        cursor_point: Point,
 8255        style: &EditorStyle,
 8256        cx: &mut Context<Editor>,
 8257    ) -> Option<Div> {
 8258        use text::ToPoint as _;
 8259
 8260        fn render_relative_row_jump(
 8261            prefix: impl Into<String>,
 8262            current_row: u32,
 8263            target_row: u32,
 8264        ) -> Div {
 8265            let (row_diff, arrow) = if target_row < current_row {
 8266                (current_row - target_row, IconName::ArrowUp)
 8267            } else {
 8268                (target_row - current_row, IconName::ArrowDown)
 8269            };
 8270
 8271            h_flex()
 8272                .child(
 8273                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8274                        .color(Color::Muted)
 8275                        .size(LabelSize::Small),
 8276                )
 8277                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8278        }
 8279
 8280        match &completion.completion {
 8281            InlineCompletion::Move {
 8282                target, snapshot, ..
 8283            } => Some(
 8284                h_flex()
 8285                    .px_2()
 8286                    .gap_2()
 8287                    .flex_1()
 8288                    .child(
 8289                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8290                            Icon::new(IconName::ZedPredictDown)
 8291                        } else {
 8292                            Icon::new(IconName::ZedPredictUp)
 8293                        },
 8294                    )
 8295                    .child(Label::new("Jump to Edit")),
 8296            ),
 8297
 8298            InlineCompletion::Edit {
 8299                edits,
 8300                edit_preview,
 8301                snapshot,
 8302                display_mode: _,
 8303            } => {
 8304                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8305
 8306                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8307                    &snapshot,
 8308                    &edits,
 8309                    edit_preview.as_ref()?,
 8310                    true,
 8311                    cx,
 8312                )
 8313                .first_line_preview();
 8314
 8315                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8316                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8317
 8318                let preview = h_flex()
 8319                    .gap_1()
 8320                    .min_w_16()
 8321                    .child(styled_text)
 8322                    .when(has_more_lines, |parent| parent.child(""));
 8323
 8324                let left = if first_edit_row != cursor_point.row {
 8325                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8326                        .into_any_element()
 8327                } else {
 8328                    Icon::new(IconName::ZedPredict).into_any_element()
 8329                };
 8330
 8331                Some(
 8332                    h_flex()
 8333                        .h_full()
 8334                        .flex_1()
 8335                        .gap_2()
 8336                        .pr_1()
 8337                        .overflow_x_hidden()
 8338                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8339                        .child(left)
 8340                        .child(preview),
 8341                )
 8342            }
 8343        }
 8344    }
 8345
 8346    fn render_context_menu(
 8347        &self,
 8348        style: &EditorStyle,
 8349        max_height_in_lines: u32,
 8350        window: &mut Window,
 8351        cx: &mut Context<Editor>,
 8352    ) -> Option<AnyElement> {
 8353        let menu = self.context_menu.borrow();
 8354        let menu = menu.as_ref()?;
 8355        if !menu.visible() {
 8356            return None;
 8357        };
 8358        Some(menu.render(style, max_height_in_lines, window, cx))
 8359    }
 8360
 8361    fn render_context_menu_aside(
 8362        &mut self,
 8363        max_size: Size<Pixels>,
 8364        window: &mut Window,
 8365        cx: &mut Context<Editor>,
 8366    ) -> Option<AnyElement> {
 8367        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8368            if menu.visible() {
 8369                menu.render_aside(self, max_size, window, cx)
 8370            } else {
 8371                None
 8372            }
 8373        })
 8374    }
 8375
 8376    fn hide_context_menu(
 8377        &mut self,
 8378        window: &mut Window,
 8379        cx: &mut Context<Self>,
 8380    ) -> Option<CodeContextMenu> {
 8381        cx.notify();
 8382        self.completion_tasks.clear();
 8383        let context_menu = self.context_menu.borrow_mut().take();
 8384        self.stale_inline_completion_in_menu.take();
 8385        self.update_visible_inline_completion(window, cx);
 8386        context_menu
 8387    }
 8388
 8389    fn show_snippet_choices(
 8390        &mut self,
 8391        choices: &Vec<String>,
 8392        selection: Range<Anchor>,
 8393        cx: &mut Context<Self>,
 8394    ) {
 8395        if selection.start.buffer_id.is_none() {
 8396            return;
 8397        }
 8398        let buffer_id = selection.start.buffer_id.unwrap();
 8399        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8400        let id = post_inc(&mut self.next_completion_id);
 8401        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8402
 8403        if let Some(buffer) = buffer {
 8404            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8405                CompletionsMenu::new_snippet_choices(
 8406                    id,
 8407                    true,
 8408                    choices,
 8409                    selection,
 8410                    buffer,
 8411                    snippet_sort_order,
 8412                ),
 8413            ));
 8414        }
 8415    }
 8416
 8417    pub fn insert_snippet(
 8418        &mut self,
 8419        insertion_ranges: &[Range<usize>],
 8420        snippet: Snippet,
 8421        window: &mut Window,
 8422        cx: &mut Context<Self>,
 8423    ) -> Result<()> {
 8424        struct Tabstop<T> {
 8425            is_end_tabstop: bool,
 8426            ranges: Vec<Range<T>>,
 8427            choices: Option<Vec<String>>,
 8428        }
 8429
 8430        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8431            let snippet_text: Arc<str> = snippet.text.clone().into();
 8432            let edits = insertion_ranges
 8433                .iter()
 8434                .cloned()
 8435                .map(|range| (range, snippet_text.clone()));
 8436            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8437
 8438            let snapshot = &*buffer.read(cx);
 8439            let snippet = &snippet;
 8440            snippet
 8441                .tabstops
 8442                .iter()
 8443                .map(|tabstop| {
 8444                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8445                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8446                    });
 8447                    let mut tabstop_ranges = tabstop
 8448                        .ranges
 8449                        .iter()
 8450                        .flat_map(|tabstop_range| {
 8451                            let mut delta = 0_isize;
 8452                            insertion_ranges.iter().map(move |insertion_range| {
 8453                                let insertion_start = insertion_range.start as isize + delta;
 8454                                delta +=
 8455                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8456
 8457                                let start = ((insertion_start + tabstop_range.start) as usize)
 8458                                    .min(snapshot.len());
 8459                                let end = ((insertion_start + tabstop_range.end) as usize)
 8460                                    .min(snapshot.len());
 8461                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8462                            })
 8463                        })
 8464                        .collect::<Vec<_>>();
 8465                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8466
 8467                    Tabstop {
 8468                        is_end_tabstop,
 8469                        ranges: tabstop_ranges,
 8470                        choices: tabstop.choices.clone(),
 8471                    }
 8472                })
 8473                .collect::<Vec<_>>()
 8474        });
 8475        if let Some(tabstop) = tabstops.first() {
 8476            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8477                s.select_ranges(tabstop.ranges.iter().cloned());
 8478            });
 8479
 8480            if let Some(choices) = &tabstop.choices {
 8481                if let Some(selection) = tabstop.ranges.first() {
 8482                    self.show_snippet_choices(choices, selection.clone(), cx)
 8483                }
 8484            }
 8485
 8486            // If we're already at the last tabstop and it's at the end of the snippet,
 8487            // we're done, we don't need to keep the state around.
 8488            if !tabstop.is_end_tabstop {
 8489                let choices = tabstops
 8490                    .iter()
 8491                    .map(|tabstop| tabstop.choices.clone())
 8492                    .collect();
 8493
 8494                let ranges = tabstops
 8495                    .into_iter()
 8496                    .map(|tabstop| tabstop.ranges)
 8497                    .collect::<Vec<_>>();
 8498
 8499                self.snippet_stack.push(SnippetState {
 8500                    active_index: 0,
 8501                    ranges,
 8502                    choices,
 8503                });
 8504            }
 8505
 8506            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8507            if self.autoclose_regions.is_empty() {
 8508                let snapshot = self.buffer.read(cx).snapshot(cx);
 8509                for selection in &mut self.selections.all::<Point>(cx) {
 8510                    let selection_head = selection.head();
 8511                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8512                        continue;
 8513                    };
 8514
 8515                    let mut bracket_pair = None;
 8516                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8517                    let prev_chars = snapshot
 8518                        .reversed_chars_at(selection_head)
 8519                        .collect::<String>();
 8520                    for (pair, enabled) in scope.brackets() {
 8521                        if enabled
 8522                            && pair.close
 8523                            && prev_chars.starts_with(pair.start.as_str())
 8524                            && next_chars.starts_with(pair.end.as_str())
 8525                        {
 8526                            bracket_pair = Some(pair.clone());
 8527                            break;
 8528                        }
 8529                    }
 8530                    if let Some(pair) = bracket_pair {
 8531                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8532                        let autoclose_enabled =
 8533                            self.use_autoclose && snapshot_settings.use_autoclose;
 8534                        if autoclose_enabled {
 8535                            let start = snapshot.anchor_after(selection_head);
 8536                            let end = snapshot.anchor_after(selection_head);
 8537                            self.autoclose_regions.push(AutocloseRegion {
 8538                                selection_id: selection.id,
 8539                                range: start..end,
 8540                                pair,
 8541                            });
 8542                        }
 8543                    }
 8544                }
 8545            }
 8546        }
 8547        Ok(())
 8548    }
 8549
 8550    pub fn move_to_next_snippet_tabstop(
 8551        &mut self,
 8552        window: &mut Window,
 8553        cx: &mut Context<Self>,
 8554    ) -> bool {
 8555        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8556    }
 8557
 8558    pub fn move_to_prev_snippet_tabstop(
 8559        &mut self,
 8560        window: &mut Window,
 8561        cx: &mut Context<Self>,
 8562    ) -> bool {
 8563        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8564    }
 8565
 8566    pub fn move_to_snippet_tabstop(
 8567        &mut self,
 8568        bias: Bias,
 8569        window: &mut Window,
 8570        cx: &mut Context<Self>,
 8571    ) -> bool {
 8572        if let Some(mut snippet) = self.snippet_stack.pop() {
 8573            match bias {
 8574                Bias::Left => {
 8575                    if snippet.active_index > 0 {
 8576                        snippet.active_index -= 1;
 8577                    } else {
 8578                        self.snippet_stack.push(snippet);
 8579                        return false;
 8580                    }
 8581                }
 8582                Bias::Right => {
 8583                    if snippet.active_index + 1 < snippet.ranges.len() {
 8584                        snippet.active_index += 1;
 8585                    } else {
 8586                        self.snippet_stack.push(snippet);
 8587                        return false;
 8588                    }
 8589                }
 8590            }
 8591            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8592                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8593                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8594                });
 8595
 8596                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8597                    if let Some(selection) = current_ranges.first() {
 8598                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8599                    }
 8600                }
 8601
 8602                // If snippet state is not at the last tabstop, push it back on the stack
 8603                if snippet.active_index + 1 < snippet.ranges.len() {
 8604                    self.snippet_stack.push(snippet);
 8605                }
 8606                return true;
 8607            }
 8608        }
 8609
 8610        false
 8611    }
 8612
 8613    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8614        self.transact(window, cx, |this, window, cx| {
 8615            this.select_all(&SelectAll, window, cx);
 8616            this.insert("", window, cx);
 8617        });
 8618    }
 8619
 8620    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8621        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8622        self.transact(window, cx, |this, window, cx| {
 8623            this.select_autoclose_pair(window, cx);
 8624            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8625            if !this.linked_edit_ranges.is_empty() {
 8626                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8627                let snapshot = this.buffer.read(cx).snapshot(cx);
 8628
 8629                for selection in selections.iter() {
 8630                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8631                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8632                    if selection_start.buffer_id != selection_end.buffer_id {
 8633                        continue;
 8634                    }
 8635                    if let Some(ranges) =
 8636                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8637                    {
 8638                        for (buffer, entries) in ranges {
 8639                            linked_ranges.entry(buffer).or_default().extend(entries);
 8640                        }
 8641                    }
 8642                }
 8643            }
 8644
 8645            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8646            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8647            for selection in &mut selections {
 8648                if selection.is_empty() {
 8649                    let old_head = selection.head();
 8650                    let mut new_head =
 8651                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8652                            .to_point(&display_map);
 8653                    if let Some((buffer, line_buffer_range)) = display_map
 8654                        .buffer_snapshot
 8655                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8656                    {
 8657                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8658                        let indent_len = match indent_size.kind {
 8659                            IndentKind::Space => {
 8660                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8661                            }
 8662                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8663                        };
 8664                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8665                            let indent_len = indent_len.get();
 8666                            new_head = cmp::min(
 8667                                new_head,
 8668                                MultiBufferPoint::new(
 8669                                    old_head.row,
 8670                                    ((old_head.column - 1) / indent_len) * indent_len,
 8671                                ),
 8672                            );
 8673                        }
 8674                    }
 8675
 8676                    selection.set_head(new_head, SelectionGoal::None);
 8677                }
 8678            }
 8679
 8680            this.signature_help_state.set_backspace_pressed(true);
 8681            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8682                s.select(selections)
 8683            });
 8684            this.insert("", window, cx);
 8685            let empty_str: Arc<str> = Arc::from("");
 8686            for (buffer, edits) in linked_ranges {
 8687                let snapshot = buffer.read(cx).snapshot();
 8688                use text::ToPoint as TP;
 8689
 8690                let edits = edits
 8691                    .into_iter()
 8692                    .map(|range| {
 8693                        let end_point = TP::to_point(&range.end, &snapshot);
 8694                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8695
 8696                        if end_point == start_point {
 8697                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8698                                .saturating_sub(1);
 8699                            start_point =
 8700                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8701                        };
 8702
 8703                        (start_point..end_point, empty_str.clone())
 8704                    })
 8705                    .sorted_by_key(|(range, _)| range.start)
 8706                    .collect::<Vec<_>>();
 8707                buffer.update(cx, |this, cx| {
 8708                    this.edit(edits, None, cx);
 8709                })
 8710            }
 8711            this.refresh_inline_completion(true, false, window, cx);
 8712            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8713        });
 8714    }
 8715
 8716    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8717        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8718        self.transact(window, cx, |this, window, cx| {
 8719            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8720                s.move_with(|map, selection| {
 8721                    if selection.is_empty() {
 8722                        let cursor = movement::right(map, selection.head());
 8723                        selection.end = cursor;
 8724                        selection.reversed = true;
 8725                        selection.goal = SelectionGoal::None;
 8726                    }
 8727                })
 8728            });
 8729            this.insert("", window, cx);
 8730            this.refresh_inline_completion(true, false, window, cx);
 8731        });
 8732    }
 8733
 8734    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8735        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8736        if self.move_to_prev_snippet_tabstop(window, cx) {
 8737            return;
 8738        }
 8739        self.outdent(&Outdent, window, cx);
 8740    }
 8741
 8742    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8743        if self.move_to_next_snippet_tabstop(window, cx) {
 8744            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8745            return;
 8746        }
 8747        if self.read_only(cx) {
 8748            return;
 8749        }
 8750        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8751        let mut selections = self.selections.all_adjusted(cx);
 8752        let buffer = self.buffer.read(cx);
 8753        let snapshot = buffer.snapshot(cx);
 8754        let rows_iter = selections.iter().map(|s| s.head().row);
 8755        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8756
 8757        let has_some_cursor_in_whitespace = selections
 8758            .iter()
 8759            .filter(|selection| selection.is_empty())
 8760            .any(|selection| {
 8761                let cursor = selection.head();
 8762                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8763                cursor.column < current_indent.len
 8764            });
 8765
 8766        let mut edits = Vec::new();
 8767        let mut prev_edited_row = 0;
 8768        let mut row_delta = 0;
 8769        for selection in &mut selections {
 8770            if selection.start.row != prev_edited_row {
 8771                row_delta = 0;
 8772            }
 8773            prev_edited_row = selection.end.row;
 8774
 8775            // If the selection is non-empty, then increase the indentation of the selected lines.
 8776            if !selection.is_empty() {
 8777                row_delta =
 8778                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8779                continue;
 8780            }
 8781
 8782            let cursor = selection.head();
 8783            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8784            if let Some(suggested_indent) =
 8785                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8786            {
 8787                // Don't do anything if already at suggested indent
 8788                // and there is any other cursor which is not
 8789                if has_some_cursor_in_whitespace
 8790                    && cursor.column == current_indent.len
 8791                    && current_indent.len == suggested_indent.len
 8792                {
 8793                    continue;
 8794                }
 8795
 8796                // Adjust line and move cursor to suggested indent
 8797                // if cursor is not at suggested indent
 8798                if cursor.column < suggested_indent.len
 8799                    && cursor.column <= current_indent.len
 8800                    && current_indent.len <= suggested_indent.len
 8801                {
 8802                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8803                    selection.end = selection.start;
 8804                    if row_delta == 0 {
 8805                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8806                            cursor.row,
 8807                            current_indent,
 8808                            suggested_indent,
 8809                        ));
 8810                        row_delta = suggested_indent.len - current_indent.len;
 8811                    }
 8812                    continue;
 8813                }
 8814
 8815                // If current indent is more than suggested indent
 8816                // only move cursor to current indent and skip indent
 8817                if cursor.column < current_indent.len && current_indent.len > suggested_indent.len {
 8818                    selection.start = Point::new(cursor.row, current_indent.len);
 8819                    selection.end = selection.start;
 8820                    continue;
 8821                }
 8822            }
 8823
 8824            // Otherwise, insert a hard or soft tab.
 8825            let settings = buffer.language_settings_at(cursor, cx);
 8826            let tab_size = if settings.hard_tabs {
 8827                IndentSize::tab()
 8828            } else {
 8829                let tab_size = settings.tab_size.get();
 8830                let indent_remainder = snapshot
 8831                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8832                    .flat_map(str::chars)
 8833                    .fold(row_delta % tab_size, |counter: u32, c| {
 8834                        if c == '\t' {
 8835                            0
 8836                        } else {
 8837                            (counter + 1) % tab_size
 8838                        }
 8839                    });
 8840
 8841                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8842                IndentSize::spaces(chars_to_next_tab_stop)
 8843            };
 8844            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8845            selection.end = selection.start;
 8846            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8847            row_delta += tab_size.len;
 8848        }
 8849
 8850        self.transact(window, cx, |this, window, cx| {
 8851            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8852            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8853                s.select(selections)
 8854            });
 8855            this.refresh_inline_completion(true, false, window, cx);
 8856        });
 8857    }
 8858
 8859    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8860        if self.read_only(cx) {
 8861            return;
 8862        }
 8863        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8864        let mut selections = self.selections.all::<Point>(cx);
 8865        let mut prev_edited_row = 0;
 8866        let mut row_delta = 0;
 8867        let mut edits = Vec::new();
 8868        let buffer = self.buffer.read(cx);
 8869        let snapshot = buffer.snapshot(cx);
 8870        for selection in &mut selections {
 8871            if selection.start.row != prev_edited_row {
 8872                row_delta = 0;
 8873            }
 8874            prev_edited_row = selection.end.row;
 8875
 8876            row_delta =
 8877                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8878        }
 8879
 8880        self.transact(window, cx, |this, window, cx| {
 8881            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8882            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8883                s.select(selections)
 8884            });
 8885        });
 8886    }
 8887
 8888    fn indent_selection(
 8889        buffer: &MultiBuffer,
 8890        snapshot: &MultiBufferSnapshot,
 8891        selection: &mut Selection<Point>,
 8892        edits: &mut Vec<(Range<Point>, String)>,
 8893        delta_for_start_row: u32,
 8894        cx: &App,
 8895    ) -> u32 {
 8896        let settings = buffer.language_settings_at(selection.start, cx);
 8897        let tab_size = settings.tab_size.get();
 8898        let indent_kind = if settings.hard_tabs {
 8899            IndentKind::Tab
 8900        } else {
 8901            IndentKind::Space
 8902        };
 8903        let mut start_row = selection.start.row;
 8904        let mut end_row = selection.end.row + 1;
 8905
 8906        // If a selection ends at the beginning of a line, don't indent
 8907        // that last line.
 8908        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8909            end_row -= 1;
 8910        }
 8911
 8912        // Avoid re-indenting a row that has already been indented by a
 8913        // previous selection, but still update this selection's column
 8914        // to reflect that indentation.
 8915        if delta_for_start_row > 0 {
 8916            start_row += 1;
 8917            selection.start.column += delta_for_start_row;
 8918            if selection.end.row == selection.start.row {
 8919                selection.end.column += delta_for_start_row;
 8920            }
 8921        }
 8922
 8923        let mut delta_for_end_row = 0;
 8924        let has_multiple_rows = start_row + 1 != end_row;
 8925        for row in start_row..end_row {
 8926            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8927            let indent_delta = match (current_indent.kind, indent_kind) {
 8928                (IndentKind::Space, IndentKind::Space) => {
 8929                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8930                    IndentSize::spaces(columns_to_next_tab_stop)
 8931                }
 8932                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8933                (_, IndentKind::Tab) => IndentSize::tab(),
 8934            };
 8935
 8936            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8937                0
 8938            } else {
 8939                selection.start.column
 8940            };
 8941            let row_start = Point::new(row, start);
 8942            edits.push((
 8943                row_start..row_start,
 8944                indent_delta.chars().collect::<String>(),
 8945            ));
 8946
 8947            // Update this selection's endpoints to reflect the indentation.
 8948            if row == selection.start.row {
 8949                selection.start.column += indent_delta.len;
 8950            }
 8951            if row == selection.end.row {
 8952                selection.end.column += indent_delta.len;
 8953                delta_for_end_row = indent_delta.len;
 8954            }
 8955        }
 8956
 8957        if selection.start.row == selection.end.row {
 8958            delta_for_start_row + delta_for_end_row
 8959        } else {
 8960            delta_for_end_row
 8961        }
 8962    }
 8963
 8964    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8965        if self.read_only(cx) {
 8966            return;
 8967        }
 8968        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8969        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8970        let selections = self.selections.all::<Point>(cx);
 8971        let mut deletion_ranges = Vec::new();
 8972        let mut last_outdent = None;
 8973        {
 8974            let buffer = self.buffer.read(cx);
 8975            let snapshot = buffer.snapshot(cx);
 8976            for selection in &selections {
 8977                let settings = buffer.language_settings_at(selection.start, cx);
 8978                let tab_size = settings.tab_size.get();
 8979                let mut rows = selection.spanned_rows(false, &display_map);
 8980
 8981                // Avoid re-outdenting a row that has already been outdented by a
 8982                // previous selection.
 8983                if let Some(last_row) = last_outdent {
 8984                    if last_row == rows.start {
 8985                        rows.start = rows.start.next_row();
 8986                    }
 8987                }
 8988                let has_multiple_rows = rows.len() > 1;
 8989                for row in rows.iter_rows() {
 8990                    let indent_size = snapshot.indent_size_for_line(row);
 8991                    if indent_size.len > 0 {
 8992                        let deletion_len = match indent_size.kind {
 8993                            IndentKind::Space => {
 8994                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8995                                if columns_to_prev_tab_stop == 0 {
 8996                                    tab_size
 8997                                } else {
 8998                                    columns_to_prev_tab_stop
 8999                                }
 9000                            }
 9001                            IndentKind::Tab => 1,
 9002                        };
 9003                        let start = if has_multiple_rows
 9004                            || deletion_len > selection.start.column
 9005                            || indent_size.len < selection.start.column
 9006                        {
 9007                            0
 9008                        } else {
 9009                            selection.start.column - deletion_len
 9010                        };
 9011                        deletion_ranges.push(
 9012                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 9013                        );
 9014                        last_outdent = Some(row);
 9015                    }
 9016                }
 9017            }
 9018        }
 9019
 9020        self.transact(window, cx, |this, window, cx| {
 9021            this.buffer.update(cx, |buffer, cx| {
 9022                let empty_str: Arc<str> = Arc::default();
 9023                buffer.edit(
 9024                    deletion_ranges
 9025                        .into_iter()
 9026                        .map(|range| (range, empty_str.clone())),
 9027                    None,
 9028                    cx,
 9029                );
 9030            });
 9031            let selections = this.selections.all::<usize>(cx);
 9032            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9033                s.select(selections)
 9034            });
 9035        });
 9036    }
 9037
 9038    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 9039        if self.read_only(cx) {
 9040            return;
 9041        }
 9042        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9043        let selections = self
 9044            .selections
 9045            .all::<usize>(cx)
 9046            .into_iter()
 9047            .map(|s| s.range());
 9048
 9049        self.transact(window, cx, |this, window, cx| {
 9050            this.buffer.update(cx, |buffer, cx| {
 9051                buffer.autoindent_ranges(selections, cx);
 9052            });
 9053            let selections = this.selections.all::<usize>(cx);
 9054            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9055                s.select(selections)
 9056            });
 9057        });
 9058    }
 9059
 9060    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 9061        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9062        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9063        let selections = self.selections.all::<Point>(cx);
 9064
 9065        let mut new_cursors = Vec::new();
 9066        let mut edit_ranges = Vec::new();
 9067        let mut selections = selections.iter().peekable();
 9068        while let Some(selection) = selections.next() {
 9069            let mut rows = selection.spanned_rows(false, &display_map);
 9070            let goal_display_column = selection.head().to_display_point(&display_map).column();
 9071
 9072            // Accumulate contiguous regions of rows that we want to delete.
 9073            while let Some(next_selection) = selections.peek() {
 9074                let next_rows = next_selection.spanned_rows(false, &display_map);
 9075                if next_rows.start <= rows.end {
 9076                    rows.end = next_rows.end;
 9077                    selections.next().unwrap();
 9078                } else {
 9079                    break;
 9080                }
 9081            }
 9082
 9083            let buffer = &display_map.buffer_snapshot;
 9084            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 9085            let edit_end;
 9086            let cursor_buffer_row;
 9087            if buffer.max_point().row >= rows.end.0 {
 9088                // If there's a line after the range, delete the \n from the end of the row range
 9089                // and position the cursor on the next line.
 9090                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 9091                cursor_buffer_row = rows.end;
 9092            } else {
 9093                // If there isn't a line after the range, delete the \n from the line before the
 9094                // start of the row range and position the cursor there.
 9095                edit_start = edit_start.saturating_sub(1);
 9096                edit_end = buffer.len();
 9097                cursor_buffer_row = rows.start.previous_row();
 9098            }
 9099
 9100            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 9101            *cursor.column_mut() =
 9102                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 9103
 9104            new_cursors.push((
 9105                selection.id,
 9106                buffer.anchor_after(cursor.to_point(&display_map)),
 9107            ));
 9108            edit_ranges.push(edit_start..edit_end);
 9109        }
 9110
 9111        self.transact(window, cx, |this, window, cx| {
 9112            let buffer = this.buffer.update(cx, |buffer, cx| {
 9113                let empty_str: Arc<str> = Arc::default();
 9114                buffer.edit(
 9115                    edit_ranges
 9116                        .into_iter()
 9117                        .map(|range| (range, empty_str.clone())),
 9118                    None,
 9119                    cx,
 9120                );
 9121                buffer.snapshot(cx)
 9122            });
 9123            let new_selections = new_cursors
 9124                .into_iter()
 9125                .map(|(id, cursor)| {
 9126                    let cursor = cursor.to_point(&buffer);
 9127                    Selection {
 9128                        id,
 9129                        start: cursor,
 9130                        end: cursor,
 9131                        reversed: false,
 9132                        goal: SelectionGoal::None,
 9133                    }
 9134                })
 9135                .collect();
 9136
 9137            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9138                s.select(new_selections);
 9139            });
 9140        });
 9141    }
 9142
 9143    pub fn join_lines_impl(
 9144        &mut self,
 9145        insert_whitespace: bool,
 9146        window: &mut Window,
 9147        cx: &mut Context<Self>,
 9148    ) {
 9149        if self.read_only(cx) {
 9150            return;
 9151        }
 9152        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9153        for selection in self.selections.all::<Point>(cx) {
 9154            let start = MultiBufferRow(selection.start.row);
 9155            // Treat single line selections as if they include the next line. Otherwise this action
 9156            // would do nothing for single line selections individual cursors.
 9157            let end = if selection.start.row == selection.end.row {
 9158                MultiBufferRow(selection.start.row + 1)
 9159            } else {
 9160                MultiBufferRow(selection.end.row)
 9161            };
 9162
 9163            if let Some(last_row_range) = row_ranges.last_mut() {
 9164                if start <= last_row_range.end {
 9165                    last_row_range.end = end;
 9166                    continue;
 9167                }
 9168            }
 9169            row_ranges.push(start..end);
 9170        }
 9171
 9172        let snapshot = self.buffer.read(cx).snapshot(cx);
 9173        let mut cursor_positions = Vec::new();
 9174        for row_range in &row_ranges {
 9175            let anchor = snapshot.anchor_before(Point::new(
 9176                row_range.end.previous_row().0,
 9177                snapshot.line_len(row_range.end.previous_row()),
 9178            ));
 9179            cursor_positions.push(anchor..anchor);
 9180        }
 9181
 9182        self.transact(window, cx, |this, window, cx| {
 9183            for row_range in row_ranges.into_iter().rev() {
 9184                for row in row_range.iter_rows().rev() {
 9185                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9186                    let next_line_row = row.next_row();
 9187                    let indent = snapshot.indent_size_for_line(next_line_row);
 9188                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9189
 9190                    let replace =
 9191                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9192                            " "
 9193                        } else {
 9194                            ""
 9195                        };
 9196
 9197                    this.buffer.update(cx, |buffer, cx| {
 9198                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9199                    });
 9200                }
 9201            }
 9202
 9203            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9204                s.select_anchor_ranges(cursor_positions)
 9205            });
 9206        });
 9207    }
 9208
 9209    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9210        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9211        self.join_lines_impl(true, window, cx);
 9212    }
 9213
 9214    pub fn sort_lines_case_sensitive(
 9215        &mut self,
 9216        _: &SortLinesCaseSensitive,
 9217        window: &mut Window,
 9218        cx: &mut Context<Self>,
 9219    ) {
 9220        self.manipulate_lines(window, cx, |lines| lines.sort())
 9221    }
 9222
 9223    pub fn sort_lines_case_insensitive(
 9224        &mut self,
 9225        _: &SortLinesCaseInsensitive,
 9226        window: &mut Window,
 9227        cx: &mut Context<Self>,
 9228    ) {
 9229        self.manipulate_lines(window, cx, |lines| {
 9230            lines.sort_by_key(|line| line.to_lowercase())
 9231        })
 9232    }
 9233
 9234    pub fn unique_lines_case_insensitive(
 9235        &mut self,
 9236        _: &UniqueLinesCaseInsensitive,
 9237        window: &mut Window,
 9238        cx: &mut Context<Self>,
 9239    ) {
 9240        self.manipulate_lines(window, cx, |lines| {
 9241            let mut seen = HashSet::default();
 9242            lines.retain(|line| seen.insert(line.to_lowercase()));
 9243        })
 9244    }
 9245
 9246    pub fn unique_lines_case_sensitive(
 9247        &mut self,
 9248        _: &UniqueLinesCaseSensitive,
 9249        window: &mut Window,
 9250        cx: &mut Context<Self>,
 9251    ) {
 9252        self.manipulate_lines(window, cx, |lines| {
 9253            let mut seen = HashSet::default();
 9254            lines.retain(|line| seen.insert(*line));
 9255        })
 9256    }
 9257
 9258    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9259        let Some(project) = self.project.clone() else {
 9260            return;
 9261        };
 9262        self.reload(project, window, cx)
 9263            .detach_and_notify_err(window, cx);
 9264    }
 9265
 9266    pub fn restore_file(
 9267        &mut self,
 9268        _: &::git::RestoreFile,
 9269        window: &mut Window,
 9270        cx: &mut Context<Self>,
 9271    ) {
 9272        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9273        let mut buffer_ids = HashSet::default();
 9274        let snapshot = self.buffer().read(cx).snapshot(cx);
 9275        for selection in self.selections.all::<usize>(cx) {
 9276            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9277        }
 9278
 9279        let buffer = self.buffer().read(cx);
 9280        let ranges = buffer_ids
 9281            .into_iter()
 9282            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9283            .collect::<Vec<_>>();
 9284
 9285        self.restore_hunks_in_ranges(ranges, window, cx);
 9286    }
 9287
 9288    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9289        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9290        let selections = self
 9291            .selections
 9292            .all(cx)
 9293            .into_iter()
 9294            .map(|s| s.range())
 9295            .collect();
 9296        self.restore_hunks_in_ranges(selections, window, cx);
 9297    }
 9298
 9299    pub fn restore_hunks_in_ranges(
 9300        &mut self,
 9301        ranges: Vec<Range<Point>>,
 9302        window: &mut Window,
 9303        cx: &mut Context<Editor>,
 9304    ) {
 9305        let mut revert_changes = HashMap::default();
 9306        let chunk_by = self
 9307            .snapshot(window, cx)
 9308            .hunks_for_ranges(ranges)
 9309            .into_iter()
 9310            .chunk_by(|hunk| hunk.buffer_id);
 9311        for (buffer_id, hunks) in &chunk_by {
 9312            let hunks = hunks.collect::<Vec<_>>();
 9313            for hunk in &hunks {
 9314                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9315            }
 9316            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9317        }
 9318        drop(chunk_by);
 9319        if !revert_changes.is_empty() {
 9320            self.transact(window, cx, |editor, window, cx| {
 9321                editor.restore(revert_changes, window, cx);
 9322            });
 9323        }
 9324    }
 9325
 9326    pub fn open_active_item_in_terminal(
 9327        &mut self,
 9328        _: &OpenInTerminal,
 9329        window: &mut Window,
 9330        cx: &mut Context<Self>,
 9331    ) {
 9332        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9333            let project_path = buffer.read(cx).project_path(cx)?;
 9334            let project = self.project.as_ref()?.read(cx);
 9335            let entry = project.entry_for_path(&project_path, cx)?;
 9336            let parent = match &entry.canonical_path {
 9337                Some(canonical_path) => canonical_path.to_path_buf(),
 9338                None => project.absolute_path(&project_path, cx)?,
 9339            }
 9340            .parent()?
 9341            .to_path_buf();
 9342            Some(parent)
 9343        }) {
 9344            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9345        }
 9346    }
 9347
 9348    fn set_breakpoint_context_menu(
 9349        &mut self,
 9350        display_row: DisplayRow,
 9351        position: Option<Anchor>,
 9352        clicked_point: gpui::Point<Pixels>,
 9353        window: &mut Window,
 9354        cx: &mut Context<Self>,
 9355    ) {
 9356        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9357            return;
 9358        }
 9359        let source = self
 9360            .buffer
 9361            .read(cx)
 9362            .snapshot(cx)
 9363            .anchor_before(Point::new(display_row.0, 0u32));
 9364
 9365        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9366
 9367        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9368            self,
 9369            source,
 9370            clicked_point,
 9371            context_menu,
 9372            window,
 9373            cx,
 9374        );
 9375    }
 9376
 9377    fn add_edit_breakpoint_block(
 9378        &mut self,
 9379        anchor: Anchor,
 9380        breakpoint: &Breakpoint,
 9381        edit_action: BreakpointPromptEditAction,
 9382        window: &mut Window,
 9383        cx: &mut Context<Self>,
 9384    ) {
 9385        let weak_editor = cx.weak_entity();
 9386        let bp_prompt = cx.new(|cx| {
 9387            BreakpointPromptEditor::new(
 9388                weak_editor,
 9389                anchor,
 9390                breakpoint.clone(),
 9391                edit_action,
 9392                window,
 9393                cx,
 9394            )
 9395        });
 9396
 9397        let height = bp_prompt.update(cx, |this, cx| {
 9398            this.prompt
 9399                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9400        });
 9401        let cloned_prompt = bp_prompt.clone();
 9402        let blocks = vec![BlockProperties {
 9403            style: BlockStyle::Sticky,
 9404            placement: BlockPlacement::Above(anchor),
 9405            height: Some(height),
 9406            render: Arc::new(move |cx| {
 9407                *cloned_prompt.read(cx).editor_margins.lock() = *cx.margins;
 9408                cloned_prompt.clone().into_any_element()
 9409            }),
 9410            priority: 0,
 9411            render_in_minimap: true,
 9412        }];
 9413
 9414        let focus_handle = bp_prompt.focus_handle(cx);
 9415        window.focus(&focus_handle);
 9416
 9417        let block_ids = self.insert_blocks(blocks, None, cx);
 9418        bp_prompt.update(cx, |prompt, _| {
 9419            prompt.add_block_ids(block_ids);
 9420        });
 9421    }
 9422
 9423    pub(crate) fn breakpoint_at_row(
 9424        &self,
 9425        row: u32,
 9426        window: &mut Window,
 9427        cx: &mut Context<Self>,
 9428    ) -> Option<(Anchor, Breakpoint)> {
 9429        let snapshot = self.snapshot(window, cx);
 9430        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9431
 9432        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9433    }
 9434
 9435    pub(crate) fn breakpoint_at_anchor(
 9436        &self,
 9437        breakpoint_position: Anchor,
 9438        snapshot: &EditorSnapshot,
 9439        cx: &mut Context<Self>,
 9440    ) -> Option<(Anchor, Breakpoint)> {
 9441        let project = self.project.clone()?;
 9442
 9443        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9444            snapshot
 9445                .buffer_snapshot
 9446                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9447        })?;
 9448
 9449        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9450        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9451        let buffer_snapshot = buffer.read(cx).snapshot();
 9452
 9453        let row = buffer_snapshot
 9454            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9455            .row;
 9456
 9457        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9458        let anchor_end = snapshot
 9459            .buffer_snapshot
 9460            .anchor_after(Point::new(row, line_len));
 9461
 9462        let bp = self
 9463            .breakpoint_store
 9464            .as_ref()?
 9465            .read_with(cx, |breakpoint_store, cx| {
 9466                breakpoint_store
 9467                    .breakpoints(
 9468                        &buffer,
 9469                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9470                        &buffer_snapshot,
 9471                        cx,
 9472                    )
 9473                    .next()
 9474                    .and_then(|(anchor, bp)| {
 9475                        let breakpoint_row = buffer_snapshot
 9476                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9477                            .row;
 9478
 9479                        if breakpoint_row == row {
 9480                            snapshot
 9481                                .buffer_snapshot
 9482                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9483                                .map(|anchor| (anchor, bp.clone()))
 9484                        } else {
 9485                            None
 9486                        }
 9487                    })
 9488            });
 9489        bp
 9490    }
 9491
 9492    pub fn edit_log_breakpoint(
 9493        &mut self,
 9494        _: &EditLogBreakpoint,
 9495        window: &mut Window,
 9496        cx: &mut Context<Self>,
 9497    ) {
 9498        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9499            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9500                message: None,
 9501                state: BreakpointState::Enabled,
 9502                condition: None,
 9503                hit_condition: None,
 9504            });
 9505
 9506            self.add_edit_breakpoint_block(
 9507                anchor,
 9508                &breakpoint,
 9509                BreakpointPromptEditAction::Log,
 9510                window,
 9511                cx,
 9512            );
 9513        }
 9514    }
 9515
 9516    fn breakpoints_at_cursors(
 9517        &self,
 9518        window: &mut Window,
 9519        cx: &mut Context<Self>,
 9520    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9521        let snapshot = self.snapshot(window, cx);
 9522        let cursors = self
 9523            .selections
 9524            .disjoint_anchors()
 9525            .into_iter()
 9526            .map(|selection| {
 9527                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9528
 9529                let breakpoint_position = self
 9530                    .breakpoint_at_row(cursor_position.row, window, cx)
 9531                    .map(|bp| bp.0)
 9532                    .unwrap_or_else(|| {
 9533                        snapshot
 9534                            .display_snapshot
 9535                            .buffer_snapshot
 9536                            .anchor_after(Point::new(cursor_position.row, 0))
 9537                    });
 9538
 9539                let breakpoint = self
 9540                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9541                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9542
 9543                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9544            })
 9545            // 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.
 9546            .collect::<HashMap<Anchor, _>>();
 9547
 9548        cursors.into_iter().collect()
 9549    }
 9550
 9551    pub fn enable_breakpoint(
 9552        &mut self,
 9553        _: &crate::actions::EnableBreakpoint,
 9554        window: &mut Window,
 9555        cx: &mut Context<Self>,
 9556    ) {
 9557        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9558            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9559                continue;
 9560            };
 9561            self.edit_breakpoint_at_anchor(
 9562                anchor,
 9563                breakpoint,
 9564                BreakpointEditAction::InvertState,
 9565                cx,
 9566            );
 9567        }
 9568    }
 9569
 9570    pub fn disable_breakpoint(
 9571        &mut self,
 9572        _: &crate::actions::DisableBreakpoint,
 9573        window: &mut Window,
 9574        cx: &mut Context<Self>,
 9575    ) {
 9576        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9577            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9578                continue;
 9579            };
 9580            self.edit_breakpoint_at_anchor(
 9581                anchor,
 9582                breakpoint,
 9583                BreakpointEditAction::InvertState,
 9584                cx,
 9585            );
 9586        }
 9587    }
 9588
 9589    pub fn toggle_breakpoint(
 9590        &mut self,
 9591        _: &crate::actions::ToggleBreakpoint,
 9592        window: &mut Window,
 9593        cx: &mut Context<Self>,
 9594    ) {
 9595        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9596            if let Some(breakpoint) = breakpoint {
 9597                self.edit_breakpoint_at_anchor(
 9598                    anchor,
 9599                    breakpoint,
 9600                    BreakpointEditAction::Toggle,
 9601                    cx,
 9602                );
 9603            } else {
 9604                self.edit_breakpoint_at_anchor(
 9605                    anchor,
 9606                    Breakpoint::new_standard(),
 9607                    BreakpointEditAction::Toggle,
 9608                    cx,
 9609                );
 9610            }
 9611        }
 9612    }
 9613
 9614    pub fn edit_breakpoint_at_anchor(
 9615        &mut self,
 9616        breakpoint_position: Anchor,
 9617        breakpoint: Breakpoint,
 9618        edit_action: BreakpointEditAction,
 9619        cx: &mut Context<Self>,
 9620    ) {
 9621        let Some(breakpoint_store) = &self.breakpoint_store else {
 9622            return;
 9623        };
 9624
 9625        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9626            if breakpoint_position == Anchor::min() {
 9627                self.buffer()
 9628                    .read(cx)
 9629                    .excerpt_buffer_ids()
 9630                    .into_iter()
 9631                    .next()
 9632            } else {
 9633                None
 9634            }
 9635        }) else {
 9636            return;
 9637        };
 9638
 9639        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9640            return;
 9641        };
 9642
 9643        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9644            breakpoint_store.toggle_breakpoint(
 9645                buffer,
 9646                (breakpoint_position.text_anchor, breakpoint),
 9647                edit_action,
 9648                cx,
 9649            );
 9650        });
 9651
 9652        cx.notify();
 9653    }
 9654
 9655    #[cfg(any(test, feature = "test-support"))]
 9656    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9657        self.breakpoint_store.clone()
 9658    }
 9659
 9660    pub fn prepare_restore_change(
 9661        &self,
 9662        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9663        hunk: &MultiBufferDiffHunk,
 9664        cx: &mut App,
 9665    ) -> Option<()> {
 9666        if hunk.is_created_file() {
 9667            return None;
 9668        }
 9669        let buffer = self.buffer.read(cx);
 9670        let diff = buffer.diff_for(hunk.buffer_id)?;
 9671        let buffer = buffer.buffer(hunk.buffer_id)?;
 9672        let buffer = buffer.read(cx);
 9673        let original_text = diff
 9674            .read(cx)
 9675            .base_text()
 9676            .as_rope()
 9677            .slice(hunk.diff_base_byte_range.clone());
 9678        let buffer_snapshot = buffer.snapshot();
 9679        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9680        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9681            probe
 9682                .0
 9683                .start
 9684                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9685                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9686        }) {
 9687            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9688            Some(())
 9689        } else {
 9690            None
 9691        }
 9692    }
 9693
 9694    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9695        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9696    }
 9697
 9698    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9699        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9700    }
 9701
 9702    fn manipulate_lines<Fn>(
 9703        &mut self,
 9704        window: &mut Window,
 9705        cx: &mut Context<Self>,
 9706        mut callback: Fn,
 9707    ) where
 9708        Fn: FnMut(&mut Vec<&str>),
 9709    {
 9710        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9711
 9712        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9713        let buffer = self.buffer.read(cx).snapshot(cx);
 9714
 9715        let mut edits = Vec::new();
 9716
 9717        let selections = self.selections.all::<Point>(cx);
 9718        let mut selections = selections.iter().peekable();
 9719        let mut contiguous_row_selections = Vec::new();
 9720        let mut new_selections = Vec::new();
 9721        let mut added_lines = 0;
 9722        let mut removed_lines = 0;
 9723
 9724        while let Some(selection) = selections.next() {
 9725            let (start_row, end_row) = consume_contiguous_rows(
 9726                &mut contiguous_row_selections,
 9727                selection,
 9728                &display_map,
 9729                &mut selections,
 9730            );
 9731
 9732            let start_point = Point::new(start_row.0, 0);
 9733            let end_point = Point::new(
 9734                end_row.previous_row().0,
 9735                buffer.line_len(end_row.previous_row()),
 9736            );
 9737            let text = buffer
 9738                .text_for_range(start_point..end_point)
 9739                .collect::<String>();
 9740
 9741            let mut lines = text.split('\n').collect_vec();
 9742
 9743            let lines_before = lines.len();
 9744            callback(&mut lines);
 9745            let lines_after = lines.len();
 9746
 9747            edits.push((start_point..end_point, lines.join("\n")));
 9748
 9749            // Selections must change based on added and removed line count
 9750            let start_row =
 9751                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9752            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9753            new_selections.push(Selection {
 9754                id: selection.id,
 9755                start: start_row,
 9756                end: end_row,
 9757                goal: SelectionGoal::None,
 9758                reversed: selection.reversed,
 9759            });
 9760
 9761            if lines_after > lines_before {
 9762                added_lines += lines_after - lines_before;
 9763            } else if lines_before > lines_after {
 9764                removed_lines += lines_before - lines_after;
 9765            }
 9766        }
 9767
 9768        self.transact(window, cx, |this, window, cx| {
 9769            let buffer = this.buffer.update(cx, |buffer, cx| {
 9770                buffer.edit(edits, None, cx);
 9771                buffer.snapshot(cx)
 9772            });
 9773
 9774            // Recalculate offsets on newly edited buffer
 9775            let new_selections = new_selections
 9776                .iter()
 9777                .map(|s| {
 9778                    let start_point = Point::new(s.start.0, 0);
 9779                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9780                    Selection {
 9781                        id: s.id,
 9782                        start: buffer.point_to_offset(start_point),
 9783                        end: buffer.point_to_offset(end_point),
 9784                        goal: s.goal,
 9785                        reversed: s.reversed,
 9786                    }
 9787                })
 9788                .collect();
 9789
 9790            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9791                s.select(new_selections);
 9792            });
 9793
 9794            this.request_autoscroll(Autoscroll::fit(), cx);
 9795        });
 9796    }
 9797
 9798    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9799        self.manipulate_text(window, cx, |text| {
 9800            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9801            if has_upper_case_characters {
 9802                text.to_lowercase()
 9803            } else {
 9804                text.to_uppercase()
 9805            }
 9806        })
 9807    }
 9808
 9809    pub fn convert_to_upper_case(
 9810        &mut self,
 9811        _: &ConvertToUpperCase,
 9812        window: &mut Window,
 9813        cx: &mut Context<Self>,
 9814    ) {
 9815        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9816    }
 9817
 9818    pub fn convert_to_lower_case(
 9819        &mut self,
 9820        _: &ConvertToLowerCase,
 9821        window: &mut Window,
 9822        cx: &mut Context<Self>,
 9823    ) {
 9824        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9825    }
 9826
 9827    pub fn convert_to_title_case(
 9828        &mut self,
 9829        _: &ConvertToTitleCase,
 9830        window: &mut Window,
 9831        cx: &mut Context<Self>,
 9832    ) {
 9833        self.manipulate_text(window, cx, |text| {
 9834            text.split('\n')
 9835                .map(|line| line.to_case(Case::Title))
 9836                .join("\n")
 9837        })
 9838    }
 9839
 9840    pub fn convert_to_snake_case(
 9841        &mut self,
 9842        _: &ConvertToSnakeCase,
 9843        window: &mut Window,
 9844        cx: &mut Context<Self>,
 9845    ) {
 9846        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9847    }
 9848
 9849    pub fn convert_to_kebab_case(
 9850        &mut self,
 9851        _: &ConvertToKebabCase,
 9852        window: &mut Window,
 9853        cx: &mut Context<Self>,
 9854    ) {
 9855        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9856    }
 9857
 9858    pub fn convert_to_upper_camel_case(
 9859        &mut self,
 9860        _: &ConvertToUpperCamelCase,
 9861        window: &mut Window,
 9862        cx: &mut Context<Self>,
 9863    ) {
 9864        self.manipulate_text(window, cx, |text| {
 9865            text.split('\n')
 9866                .map(|line| line.to_case(Case::UpperCamel))
 9867                .join("\n")
 9868        })
 9869    }
 9870
 9871    pub fn convert_to_lower_camel_case(
 9872        &mut self,
 9873        _: &ConvertToLowerCamelCase,
 9874        window: &mut Window,
 9875        cx: &mut Context<Self>,
 9876    ) {
 9877        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9878    }
 9879
 9880    pub fn convert_to_opposite_case(
 9881        &mut self,
 9882        _: &ConvertToOppositeCase,
 9883        window: &mut Window,
 9884        cx: &mut Context<Self>,
 9885    ) {
 9886        self.manipulate_text(window, cx, |text| {
 9887            text.chars()
 9888                .fold(String::with_capacity(text.len()), |mut t, c| {
 9889                    if c.is_uppercase() {
 9890                        t.extend(c.to_lowercase());
 9891                    } else {
 9892                        t.extend(c.to_uppercase());
 9893                    }
 9894                    t
 9895                })
 9896        })
 9897    }
 9898
 9899    pub fn convert_to_rot13(
 9900        &mut self,
 9901        _: &ConvertToRot13,
 9902        window: &mut Window,
 9903        cx: &mut Context<Self>,
 9904    ) {
 9905        self.manipulate_text(window, cx, |text| {
 9906            text.chars()
 9907                .map(|c| match c {
 9908                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9909                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9910                    _ => c,
 9911                })
 9912                .collect()
 9913        })
 9914    }
 9915
 9916    pub fn convert_to_rot47(
 9917        &mut self,
 9918        _: &ConvertToRot47,
 9919        window: &mut Window,
 9920        cx: &mut Context<Self>,
 9921    ) {
 9922        self.manipulate_text(window, cx, |text| {
 9923            text.chars()
 9924                .map(|c| {
 9925                    let code_point = c as u32;
 9926                    if code_point >= 33 && code_point <= 126 {
 9927                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9928                    }
 9929                    c
 9930                })
 9931                .collect()
 9932        })
 9933    }
 9934
 9935    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9936    where
 9937        Fn: FnMut(&str) -> String,
 9938    {
 9939        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9940        let buffer = self.buffer.read(cx).snapshot(cx);
 9941
 9942        let mut new_selections = Vec::new();
 9943        let mut edits = Vec::new();
 9944        let mut selection_adjustment = 0i32;
 9945
 9946        for selection in self.selections.all::<usize>(cx) {
 9947            let selection_is_empty = selection.is_empty();
 9948
 9949            let (start, end) = if selection_is_empty {
 9950                let word_range = movement::surrounding_word(
 9951                    &display_map,
 9952                    selection.start.to_display_point(&display_map),
 9953                );
 9954                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9955                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9956                (start, end)
 9957            } else {
 9958                (selection.start, selection.end)
 9959            };
 9960
 9961            let text = buffer.text_for_range(start..end).collect::<String>();
 9962            let old_length = text.len() as i32;
 9963            let text = callback(&text);
 9964
 9965            new_selections.push(Selection {
 9966                start: (start as i32 - selection_adjustment) as usize,
 9967                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9968                goal: SelectionGoal::None,
 9969                ..selection
 9970            });
 9971
 9972            selection_adjustment += old_length - text.len() as i32;
 9973
 9974            edits.push((start..end, text));
 9975        }
 9976
 9977        self.transact(window, cx, |this, window, cx| {
 9978            this.buffer.update(cx, |buffer, cx| {
 9979                buffer.edit(edits, None, cx);
 9980            });
 9981
 9982            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9983                s.select(new_selections);
 9984            });
 9985
 9986            this.request_autoscroll(Autoscroll::fit(), cx);
 9987        });
 9988    }
 9989
 9990    pub fn duplicate(
 9991        &mut self,
 9992        upwards: bool,
 9993        whole_lines: bool,
 9994        window: &mut Window,
 9995        cx: &mut Context<Self>,
 9996    ) {
 9997        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9998
 9999        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10000        let buffer = &display_map.buffer_snapshot;
10001        let selections = self.selections.all::<Point>(cx);
10002
10003        let mut edits = Vec::new();
10004        let mut selections_iter = selections.iter().peekable();
10005        while let Some(selection) = selections_iter.next() {
10006            let mut rows = selection.spanned_rows(false, &display_map);
10007            // duplicate line-wise
10008            if whole_lines || selection.start == selection.end {
10009                // Avoid duplicating the same lines twice.
10010                while let Some(next_selection) = selections_iter.peek() {
10011                    let next_rows = next_selection.spanned_rows(false, &display_map);
10012                    if next_rows.start < rows.end {
10013                        rows.end = next_rows.end;
10014                        selections_iter.next().unwrap();
10015                    } else {
10016                        break;
10017                    }
10018                }
10019
10020                // Copy the text from the selected row region and splice it either at the start
10021                // or end of the region.
10022                let start = Point::new(rows.start.0, 0);
10023                let end = Point::new(
10024                    rows.end.previous_row().0,
10025                    buffer.line_len(rows.end.previous_row()),
10026                );
10027                let text = buffer
10028                    .text_for_range(start..end)
10029                    .chain(Some("\n"))
10030                    .collect::<String>();
10031                let insert_location = if upwards {
10032                    Point::new(rows.end.0, 0)
10033                } else {
10034                    start
10035                };
10036                edits.push((insert_location..insert_location, text));
10037            } else {
10038                // duplicate character-wise
10039                let start = selection.start;
10040                let end = selection.end;
10041                let text = buffer.text_for_range(start..end).collect::<String>();
10042                edits.push((selection.end..selection.end, text));
10043            }
10044        }
10045
10046        self.transact(window, cx, |this, _, cx| {
10047            this.buffer.update(cx, |buffer, cx| {
10048                buffer.edit(edits, None, cx);
10049            });
10050
10051            this.request_autoscroll(Autoscroll::fit(), cx);
10052        });
10053    }
10054
10055    pub fn duplicate_line_up(
10056        &mut self,
10057        _: &DuplicateLineUp,
10058        window: &mut Window,
10059        cx: &mut Context<Self>,
10060    ) {
10061        self.duplicate(true, true, window, cx);
10062    }
10063
10064    pub fn duplicate_line_down(
10065        &mut self,
10066        _: &DuplicateLineDown,
10067        window: &mut Window,
10068        cx: &mut Context<Self>,
10069    ) {
10070        self.duplicate(false, true, window, cx);
10071    }
10072
10073    pub fn duplicate_selection(
10074        &mut self,
10075        _: &DuplicateSelection,
10076        window: &mut Window,
10077        cx: &mut Context<Self>,
10078    ) {
10079        self.duplicate(false, false, window, cx);
10080    }
10081
10082    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10083        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10084
10085        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10086        let buffer = self.buffer.read(cx).snapshot(cx);
10087
10088        let mut edits = Vec::new();
10089        let mut unfold_ranges = Vec::new();
10090        let mut refold_creases = Vec::new();
10091
10092        let selections = self.selections.all::<Point>(cx);
10093        let mut selections = selections.iter().peekable();
10094        let mut contiguous_row_selections = Vec::new();
10095        let mut new_selections = Vec::new();
10096
10097        while let Some(selection) = selections.next() {
10098            // Find all the selections that span a contiguous row range
10099            let (start_row, end_row) = consume_contiguous_rows(
10100                &mut contiguous_row_selections,
10101                selection,
10102                &display_map,
10103                &mut selections,
10104            );
10105
10106            // Move the text spanned by the row range to be before the line preceding the row range
10107            if start_row.0 > 0 {
10108                let range_to_move = Point::new(
10109                    start_row.previous_row().0,
10110                    buffer.line_len(start_row.previous_row()),
10111                )
10112                    ..Point::new(
10113                        end_row.previous_row().0,
10114                        buffer.line_len(end_row.previous_row()),
10115                    );
10116                let insertion_point = display_map
10117                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10118                    .0;
10119
10120                // Don't move lines across excerpts
10121                if buffer
10122                    .excerpt_containing(insertion_point..range_to_move.end)
10123                    .is_some()
10124                {
10125                    let text = buffer
10126                        .text_for_range(range_to_move.clone())
10127                        .flat_map(|s| s.chars())
10128                        .skip(1)
10129                        .chain(['\n'])
10130                        .collect::<String>();
10131
10132                    edits.push((
10133                        buffer.anchor_after(range_to_move.start)
10134                            ..buffer.anchor_before(range_to_move.end),
10135                        String::new(),
10136                    ));
10137                    let insertion_anchor = buffer.anchor_after(insertion_point);
10138                    edits.push((insertion_anchor..insertion_anchor, text));
10139
10140                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10141
10142                    // Move selections up
10143                    new_selections.extend(contiguous_row_selections.drain(..).map(
10144                        |mut selection| {
10145                            selection.start.row -= row_delta;
10146                            selection.end.row -= row_delta;
10147                            selection
10148                        },
10149                    ));
10150
10151                    // Move folds up
10152                    unfold_ranges.push(range_to_move.clone());
10153                    for fold in display_map.folds_in_range(
10154                        buffer.anchor_before(range_to_move.start)
10155                            ..buffer.anchor_after(range_to_move.end),
10156                    ) {
10157                        let mut start = fold.range.start.to_point(&buffer);
10158                        let mut end = fold.range.end.to_point(&buffer);
10159                        start.row -= row_delta;
10160                        end.row -= row_delta;
10161                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10162                    }
10163                }
10164            }
10165
10166            // If we didn't move line(s), preserve the existing selections
10167            new_selections.append(&mut contiguous_row_selections);
10168        }
10169
10170        self.transact(window, cx, |this, window, cx| {
10171            this.unfold_ranges(&unfold_ranges, true, true, cx);
10172            this.buffer.update(cx, |buffer, cx| {
10173                for (range, text) in edits {
10174                    buffer.edit([(range, text)], None, cx);
10175                }
10176            });
10177            this.fold_creases(refold_creases, true, window, cx);
10178            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10179                s.select(new_selections);
10180            })
10181        });
10182    }
10183
10184    pub fn move_line_down(
10185        &mut self,
10186        _: &MoveLineDown,
10187        window: &mut Window,
10188        cx: &mut Context<Self>,
10189    ) {
10190        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10191
10192        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10193        let buffer = self.buffer.read(cx).snapshot(cx);
10194
10195        let mut edits = Vec::new();
10196        let mut unfold_ranges = Vec::new();
10197        let mut refold_creases = Vec::new();
10198
10199        let selections = self.selections.all::<Point>(cx);
10200        let mut selections = selections.iter().peekable();
10201        let mut contiguous_row_selections = Vec::new();
10202        let mut new_selections = Vec::new();
10203
10204        while let Some(selection) = selections.next() {
10205            // Find all the selections that span a contiguous row range
10206            let (start_row, end_row) = consume_contiguous_rows(
10207                &mut contiguous_row_selections,
10208                selection,
10209                &display_map,
10210                &mut selections,
10211            );
10212
10213            // Move the text spanned by the row range to be after the last line of the row range
10214            if end_row.0 <= buffer.max_point().row {
10215                let range_to_move =
10216                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10217                let insertion_point = display_map
10218                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10219                    .0;
10220
10221                // Don't move lines across excerpt boundaries
10222                if buffer
10223                    .excerpt_containing(range_to_move.start..insertion_point)
10224                    .is_some()
10225                {
10226                    let mut text = String::from("\n");
10227                    text.extend(buffer.text_for_range(range_to_move.clone()));
10228                    text.pop(); // Drop trailing newline
10229                    edits.push((
10230                        buffer.anchor_after(range_to_move.start)
10231                            ..buffer.anchor_before(range_to_move.end),
10232                        String::new(),
10233                    ));
10234                    let insertion_anchor = buffer.anchor_after(insertion_point);
10235                    edits.push((insertion_anchor..insertion_anchor, text));
10236
10237                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10238
10239                    // Move selections down
10240                    new_selections.extend(contiguous_row_selections.drain(..).map(
10241                        |mut selection| {
10242                            selection.start.row += row_delta;
10243                            selection.end.row += row_delta;
10244                            selection
10245                        },
10246                    ));
10247
10248                    // Move folds down
10249                    unfold_ranges.push(range_to_move.clone());
10250                    for fold in display_map.folds_in_range(
10251                        buffer.anchor_before(range_to_move.start)
10252                            ..buffer.anchor_after(range_to_move.end),
10253                    ) {
10254                        let mut start = fold.range.start.to_point(&buffer);
10255                        let mut end = fold.range.end.to_point(&buffer);
10256                        start.row += row_delta;
10257                        end.row += row_delta;
10258                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10259                    }
10260                }
10261            }
10262
10263            // If we didn't move line(s), preserve the existing selections
10264            new_selections.append(&mut contiguous_row_selections);
10265        }
10266
10267        self.transact(window, cx, |this, window, cx| {
10268            this.unfold_ranges(&unfold_ranges, true, true, cx);
10269            this.buffer.update(cx, |buffer, cx| {
10270                for (range, text) in edits {
10271                    buffer.edit([(range, text)], None, cx);
10272                }
10273            });
10274            this.fold_creases(refold_creases, true, window, cx);
10275            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10276                s.select(new_selections)
10277            });
10278        });
10279    }
10280
10281    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10282        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10283        let text_layout_details = &self.text_layout_details(window);
10284        self.transact(window, cx, |this, window, cx| {
10285            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10286                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10287                s.move_with(|display_map, selection| {
10288                    if !selection.is_empty() {
10289                        return;
10290                    }
10291
10292                    let mut head = selection.head();
10293                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10294                    if head.column() == display_map.line_len(head.row()) {
10295                        transpose_offset = display_map
10296                            .buffer_snapshot
10297                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10298                    }
10299
10300                    if transpose_offset == 0 {
10301                        return;
10302                    }
10303
10304                    *head.column_mut() += 1;
10305                    head = display_map.clip_point(head, Bias::Right);
10306                    let goal = SelectionGoal::HorizontalPosition(
10307                        display_map
10308                            .x_for_display_point(head, text_layout_details)
10309                            .into(),
10310                    );
10311                    selection.collapse_to(head, goal);
10312
10313                    let transpose_start = display_map
10314                        .buffer_snapshot
10315                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10316                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10317                        let transpose_end = display_map
10318                            .buffer_snapshot
10319                            .clip_offset(transpose_offset + 1, Bias::Right);
10320                        if let Some(ch) =
10321                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10322                        {
10323                            edits.push((transpose_start..transpose_offset, String::new()));
10324                            edits.push((transpose_end..transpose_end, ch.to_string()));
10325                        }
10326                    }
10327                });
10328                edits
10329            });
10330            this.buffer
10331                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10332            let selections = this.selections.all::<usize>(cx);
10333            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10334                s.select(selections);
10335            });
10336        });
10337    }
10338
10339    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10340        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10341        self.rewrap_impl(RewrapOptions::default(), cx)
10342    }
10343
10344    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10345        let buffer = self.buffer.read(cx).snapshot(cx);
10346        let selections = self.selections.all::<Point>(cx);
10347        let mut selections = selections.iter().peekable();
10348
10349        let mut edits = Vec::new();
10350        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10351
10352        while let Some(selection) = selections.next() {
10353            let mut start_row = selection.start.row;
10354            let mut end_row = selection.end.row;
10355
10356            // Skip selections that overlap with a range that has already been rewrapped.
10357            let selection_range = start_row..end_row;
10358            if rewrapped_row_ranges
10359                .iter()
10360                .any(|range| range.overlaps(&selection_range))
10361            {
10362                continue;
10363            }
10364
10365            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10366
10367            // Since not all lines in the selection may be at the same indent
10368            // level, choose the indent size that is the most common between all
10369            // of the lines.
10370            //
10371            // If there is a tie, we use the deepest indent.
10372            let (indent_size, indent_end) = {
10373                let mut indent_size_occurrences = HashMap::default();
10374                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10375
10376                for row in start_row..=end_row {
10377                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10378                    rows_by_indent_size.entry(indent).or_default().push(row);
10379                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10380                }
10381
10382                let indent_size = indent_size_occurrences
10383                    .into_iter()
10384                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10385                    .map(|(indent, _)| indent)
10386                    .unwrap_or_default();
10387                let row = rows_by_indent_size[&indent_size][0];
10388                let indent_end = Point::new(row, indent_size.len);
10389
10390                (indent_size, indent_end)
10391            };
10392
10393            let mut line_prefix = indent_size.chars().collect::<String>();
10394
10395            let mut inside_comment = false;
10396            if let Some(comment_prefix) =
10397                buffer
10398                    .language_scope_at(selection.head())
10399                    .and_then(|language| {
10400                        language
10401                            .line_comment_prefixes()
10402                            .iter()
10403                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10404                            .cloned()
10405                    })
10406            {
10407                line_prefix.push_str(&comment_prefix);
10408                inside_comment = true;
10409            }
10410
10411            let language_settings = buffer.language_settings_at(selection.head(), cx);
10412            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10413                RewrapBehavior::InComments => inside_comment,
10414                RewrapBehavior::InSelections => !selection.is_empty(),
10415                RewrapBehavior::Anywhere => true,
10416            };
10417
10418            let should_rewrap = options.override_language_settings
10419                || allow_rewrap_based_on_language
10420                || self.hard_wrap.is_some();
10421            if !should_rewrap {
10422                continue;
10423            }
10424
10425            if selection.is_empty() {
10426                'expand_upwards: while start_row > 0 {
10427                    let prev_row = start_row - 1;
10428                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10429                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10430                    {
10431                        start_row = prev_row;
10432                    } else {
10433                        break 'expand_upwards;
10434                    }
10435                }
10436
10437                'expand_downwards: while end_row < buffer.max_point().row {
10438                    let next_row = end_row + 1;
10439                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10440                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10441                    {
10442                        end_row = next_row;
10443                    } else {
10444                        break 'expand_downwards;
10445                    }
10446                }
10447            }
10448
10449            let start = Point::new(start_row, 0);
10450            let start_offset = start.to_offset(&buffer);
10451            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10452            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10453            let Some(lines_without_prefixes) = selection_text
10454                .lines()
10455                .map(|line| {
10456                    line.strip_prefix(&line_prefix)
10457                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10458                        .ok_or_else(|| {
10459                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10460                        })
10461                })
10462                .collect::<Result<Vec<_>, _>>()
10463                .log_err()
10464            else {
10465                continue;
10466            };
10467
10468            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10469                buffer
10470                    .language_settings_at(Point::new(start_row, 0), cx)
10471                    .preferred_line_length as usize
10472            });
10473            let wrapped_text = wrap_with_prefix(
10474                line_prefix,
10475                lines_without_prefixes.join("\n"),
10476                wrap_column,
10477                tab_size,
10478                options.preserve_existing_whitespace,
10479            );
10480
10481            // TODO: should always use char-based diff while still supporting cursor behavior that
10482            // matches vim.
10483            let mut diff_options = DiffOptions::default();
10484            if options.override_language_settings {
10485                diff_options.max_word_diff_len = 0;
10486                diff_options.max_word_diff_line_count = 0;
10487            } else {
10488                diff_options.max_word_diff_len = usize::MAX;
10489                diff_options.max_word_diff_line_count = usize::MAX;
10490            }
10491
10492            for (old_range, new_text) in
10493                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10494            {
10495                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10496                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10497                edits.push((edit_start..edit_end, new_text));
10498            }
10499
10500            rewrapped_row_ranges.push(start_row..=end_row);
10501        }
10502
10503        self.buffer
10504            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10505    }
10506
10507    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10508        let mut text = String::new();
10509        let buffer = self.buffer.read(cx).snapshot(cx);
10510        let mut selections = self.selections.all::<Point>(cx);
10511        let mut clipboard_selections = Vec::with_capacity(selections.len());
10512        {
10513            let max_point = buffer.max_point();
10514            let mut is_first = true;
10515            for selection in &mut selections {
10516                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10517                if is_entire_line {
10518                    selection.start = Point::new(selection.start.row, 0);
10519                    if !selection.is_empty() && selection.end.column == 0 {
10520                        selection.end = cmp::min(max_point, selection.end);
10521                    } else {
10522                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10523                    }
10524                    selection.goal = SelectionGoal::None;
10525                }
10526                if is_first {
10527                    is_first = false;
10528                } else {
10529                    text += "\n";
10530                }
10531                let mut len = 0;
10532                for chunk in buffer.text_for_range(selection.start..selection.end) {
10533                    text.push_str(chunk);
10534                    len += chunk.len();
10535                }
10536                clipboard_selections.push(ClipboardSelection {
10537                    len,
10538                    is_entire_line,
10539                    first_line_indent: buffer
10540                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10541                        .len,
10542                });
10543            }
10544        }
10545
10546        self.transact(window, cx, |this, window, cx| {
10547            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10548                s.select(selections);
10549            });
10550            this.insert("", window, cx);
10551        });
10552        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10553    }
10554
10555    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10556        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10557        let item = self.cut_common(window, cx);
10558        cx.write_to_clipboard(item);
10559    }
10560
10561    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10562        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10563        self.change_selections(None, window, cx, |s| {
10564            s.move_with(|snapshot, sel| {
10565                if sel.is_empty() {
10566                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10567                }
10568            });
10569        });
10570        let item = self.cut_common(window, cx);
10571        cx.set_global(KillRing(item))
10572    }
10573
10574    pub fn kill_ring_yank(
10575        &mut self,
10576        _: &KillRingYank,
10577        window: &mut Window,
10578        cx: &mut Context<Self>,
10579    ) {
10580        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10581        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10582            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10583                (kill_ring.text().to_string(), kill_ring.metadata_json())
10584            } else {
10585                return;
10586            }
10587        } else {
10588            return;
10589        };
10590        self.do_paste(&text, metadata, false, window, cx);
10591    }
10592
10593    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10594        self.do_copy(true, cx);
10595    }
10596
10597    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10598        self.do_copy(false, cx);
10599    }
10600
10601    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10602        let selections = self.selections.all::<Point>(cx);
10603        let buffer = self.buffer.read(cx).read(cx);
10604        let mut text = String::new();
10605
10606        let mut clipboard_selections = Vec::with_capacity(selections.len());
10607        {
10608            let max_point = buffer.max_point();
10609            let mut is_first = true;
10610            for selection in &selections {
10611                let mut start = selection.start;
10612                let mut end = selection.end;
10613                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10614                if is_entire_line {
10615                    start = Point::new(start.row, 0);
10616                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10617                }
10618
10619                let mut trimmed_selections = Vec::new();
10620                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10621                    let row = MultiBufferRow(start.row);
10622                    let first_indent = buffer.indent_size_for_line(row);
10623                    if first_indent.len == 0 || start.column > first_indent.len {
10624                        trimmed_selections.push(start..end);
10625                    } else {
10626                        trimmed_selections.push(
10627                            Point::new(row.0, first_indent.len)
10628                                ..Point::new(row.0, buffer.line_len(row)),
10629                        );
10630                        for row in start.row + 1..=end.row {
10631                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10632                            if row == end.row {
10633                                line_len = end.column;
10634                            }
10635                            if line_len == 0 {
10636                                trimmed_selections
10637                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10638                                continue;
10639                            }
10640                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10641                            if row_indent_size.len >= first_indent.len {
10642                                trimmed_selections.push(
10643                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10644                                );
10645                            } else {
10646                                trimmed_selections.clear();
10647                                trimmed_selections.push(start..end);
10648                                break;
10649                            }
10650                        }
10651                    }
10652                } else {
10653                    trimmed_selections.push(start..end);
10654                }
10655
10656                for trimmed_range in trimmed_selections {
10657                    if is_first {
10658                        is_first = false;
10659                    } else {
10660                        text += "\n";
10661                    }
10662                    let mut len = 0;
10663                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10664                        text.push_str(chunk);
10665                        len += chunk.len();
10666                    }
10667                    clipboard_selections.push(ClipboardSelection {
10668                        len,
10669                        is_entire_line,
10670                        first_line_indent: buffer
10671                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10672                            .len,
10673                    });
10674                }
10675            }
10676        }
10677
10678        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10679            text,
10680            clipboard_selections,
10681        ));
10682    }
10683
10684    pub fn do_paste(
10685        &mut self,
10686        text: &String,
10687        clipboard_selections: Option<Vec<ClipboardSelection>>,
10688        handle_entire_lines: bool,
10689        window: &mut Window,
10690        cx: &mut Context<Self>,
10691    ) {
10692        if self.read_only(cx) {
10693            return;
10694        }
10695
10696        let clipboard_text = Cow::Borrowed(text);
10697
10698        self.transact(window, cx, |this, window, cx| {
10699            if let Some(mut clipboard_selections) = clipboard_selections {
10700                let old_selections = this.selections.all::<usize>(cx);
10701                let all_selections_were_entire_line =
10702                    clipboard_selections.iter().all(|s| s.is_entire_line);
10703                let first_selection_indent_column =
10704                    clipboard_selections.first().map(|s| s.first_line_indent);
10705                if clipboard_selections.len() != old_selections.len() {
10706                    clipboard_selections.drain(..);
10707                }
10708                let cursor_offset = this.selections.last::<usize>(cx).head();
10709                let mut auto_indent_on_paste = true;
10710
10711                this.buffer.update(cx, |buffer, cx| {
10712                    let snapshot = buffer.read(cx);
10713                    auto_indent_on_paste = snapshot
10714                        .language_settings_at(cursor_offset, cx)
10715                        .auto_indent_on_paste;
10716
10717                    let mut start_offset = 0;
10718                    let mut edits = Vec::new();
10719                    let mut original_indent_columns = Vec::new();
10720                    for (ix, selection) in old_selections.iter().enumerate() {
10721                        let to_insert;
10722                        let entire_line;
10723                        let original_indent_column;
10724                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10725                            let end_offset = start_offset + clipboard_selection.len;
10726                            to_insert = &clipboard_text[start_offset..end_offset];
10727                            entire_line = clipboard_selection.is_entire_line;
10728                            start_offset = end_offset + 1;
10729                            original_indent_column = Some(clipboard_selection.first_line_indent);
10730                        } else {
10731                            to_insert = clipboard_text.as_str();
10732                            entire_line = all_selections_were_entire_line;
10733                            original_indent_column = first_selection_indent_column
10734                        }
10735
10736                        // If the corresponding selection was empty when this slice of the
10737                        // clipboard text was written, then the entire line containing the
10738                        // selection was copied. If this selection is also currently empty,
10739                        // then paste the line before the current line of the buffer.
10740                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10741                            let column = selection.start.to_point(&snapshot).column as usize;
10742                            let line_start = selection.start - column;
10743                            line_start..line_start
10744                        } else {
10745                            selection.range()
10746                        };
10747
10748                        edits.push((range, to_insert));
10749                        original_indent_columns.push(original_indent_column);
10750                    }
10751                    drop(snapshot);
10752
10753                    buffer.edit(
10754                        edits,
10755                        if auto_indent_on_paste {
10756                            Some(AutoindentMode::Block {
10757                                original_indent_columns,
10758                            })
10759                        } else {
10760                            None
10761                        },
10762                        cx,
10763                    );
10764                });
10765
10766                let selections = this.selections.all::<usize>(cx);
10767                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10768                    s.select(selections)
10769                });
10770            } else {
10771                this.insert(&clipboard_text, window, cx);
10772            }
10773        });
10774    }
10775
10776    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10777        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10778        if let Some(item) = cx.read_from_clipboard() {
10779            let entries = item.entries();
10780
10781            match entries.first() {
10782                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10783                // of all the pasted entries.
10784                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10785                    .do_paste(
10786                        clipboard_string.text(),
10787                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10788                        true,
10789                        window,
10790                        cx,
10791                    ),
10792                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10793            }
10794        }
10795    }
10796
10797    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10798        if self.read_only(cx) {
10799            return;
10800        }
10801
10802        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10803
10804        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10805            if let Some((selections, _)) =
10806                self.selection_history.transaction(transaction_id).cloned()
10807            {
10808                self.change_selections(None, window, cx, |s| {
10809                    s.select_anchors(selections.to_vec());
10810                });
10811            } else {
10812                log::error!(
10813                    "No entry in selection_history found for undo. \
10814                     This may correspond to a bug where undo does not update the selection. \
10815                     If this is occurring, please add details to \
10816                     https://github.com/zed-industries/zed/issues/22692"
10817                );
10818            }
10819            self.request_autoscroll(Autoscroll::fit(), cx);
10820            self.unmark_text(window, cx);
10821            self.refresh_inline_completion(true, false, window, cx);
10822            cx.emit(EditorEvent::Edited { transaction_id });
10823            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10824        }
10825    }
10826
10827    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10828        if self.read_only(cx) {
10829            return;
10830        }
10831
10832        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10833
10834        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10835            if let Some((_, Some(selections))) =
10836                self.selection_history.transaction(transaction_id).cloned()
10837            {
10838                self.change_selections(None, window, cx, |s| {
10839                    s.select_anchors(selections.to_vec());
10840                });
10841            } else {
10842                log::error!(
10843                    "No entry in selection_history found for redo. \
10844                     This may correspond to a bug where undo does not update the selection. \
10845                     If this is occurring, please add details to \
10846                     https://github.com/zed-industries/zed/issues/22692"
10847                );
10848            }
10849            self.request_autoscroll(Autoscroll::fit(), cx);
10850            self.unmark_text(window, cx);
10851            self.refresh_inline_completion(true, false, window, cx);
10852            cx.emit(EditorEvent::Edited { transaction_id });
10853        }
10854    }
10855
10856    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10857        self.buffer
10858            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10859    }
10860
10861    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10862        self.buffer
10863            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10864    }
10865
10866    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10867        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10868        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10869            s.move_with(|map, selection| {
10870                let cursor = if selection.is_empty() {
10871                    movement::left(map, selection.start)
10872                } else {
10873                    selection.start
10874                };
10875                selection.collapse_to(cursor, SelectionGoal::None);
10876            });
10877        })
10878    }
10879
10880    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10881        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10884        })
10885    }
10886
10887    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10888        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10889        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10890            s.move_with(|map, selection| {
10891                let cursor = if selection.is_empty() {
10892                    movement::right(map, selection.end)
10893                } else {
10894                    selection.end
10895                };
10896                selection.collapse_to(cursor, SelectionGoal::None)
10897            });
10898        })
10899    }
10900
10901    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10902        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10903        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10904            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10905        })
10906    }
10907
10908    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10909        if self.take_rename(true, window, cx).is_some() {
10910            return;
10911        }
10912
10913        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10914            cx.propagate();
10915            return;
10916        }
10917
10918        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10919
10920        let text_layout_details = &self.text_layout_details(window);
10921        let selection_count = self.selections.count();
10922        let first_selection = self.selections.first_anchor();
10923
10924        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10925            s.move_with(|map, selection| {
10926                if !selection.is_empty() {
10927                    selection.goal = SelectionGoal::None;
10928                }
10929                let (cursor, goal) = movement::up(
10930                    map,
10931                    selection.start,
10932                    selection.goal,
10933                    false,
10934                    text_layout_details,
10935                );
10936                selection.collapse_to(cursor, goal);
10937            });
10938        });
10939
10940        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10941        {
10942            cx.propagate();
10943        }
10944    }
10945
10946    pub fn move_up_by_lines(
10947        &mut self,
10948        action: &MoveUpByLines,
10949        window: &mut Window,
10950        cx: &mut Context<Self>,
10951    ) {
10952        if self.take_rename(true, window, cx).is_some() {
10953            return;
10954        }
10955
10956        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10957            cx.propagate();
10958            return;
10959        }
10960
10961        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10962
10963        let text_layout_details = &self.text_layout_details(window);
10964
10965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10966            s.move_with(|map, selection| {
10967                if !selection.is_empty() {
10968                    selection.goal = SelectionGoal::None;
10969                }
10970                let (cursor, goal) = movement::up_by_rows(
10971                    map,
10972                    selection.start,
10973                    action.lines,
10974                    selection.goal,
10975                    false,
10976                    text_layout_details,
10977                );
10978                selection.collapse_to(cursor, goal);
10979            });
10980        })
10981    }
10982
10983    pub fn move_down_by_lines(
10984        &mut self,
10985        action: &MoveDownByLines,
10986        window: &mut Window,
10987        cx: &mut Context<Self>,
10988    ) {
10989        if self.take_rename(true, window, cx).is_some() {
10990            return;
10991        }
10992
10993        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10994            cx.propagate();
10995            return;
10996        }
10997
10998        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10999
11000        let text_layout_details = &self.text_layout_details(window);
11001
11002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11003            s.move_with(|map, selection| {
11004                if !selection.is_empty() {
11005                    selection.goal = SelectionGoal::None;
11006                }
11007                let (cursor, goal) = movement::down_by_rows(
11008                    map,
11009                    selection.start,
11010                    action.lines,
11011                    selection.goal,
11012                    false,
11013                    text_layout_details,
11014                );
11015                selection.collapse_to(cursor, goal);
11016            });
11017        })
11018    }
11019
11020    pub fn select_down_by_lines(
11021        &mut self,
11022        action: &SelectDownByLines,
11023        window: &mut Window,
11024        cx: &mut Context<Self>,
11025    ) {
11026        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11027        let text_layout_details = &self.text_layout_details(window);
11028        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11029            s.move_heads_with(|map, head, goal| {
11030                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
11031            })
11032        })
11033    }
11034
11035    pub fn select_up_by_lines(
11036        &mut self,
11037        action: &SelectUpByLines,
11038        window: &mut Window,
11039        cx: &mut Context<Self>,
11040    ) {
11041        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11042        let text_layout_details = &self.text_layout_details(window);
11043        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11044            s.move_heads_with(|map, head, goal| {
11045                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
11046            })
11047        })
11048    }
11049
11050    pub fn select_page_up(
11051        &mut self,
11052        _: &SelectPageUp,
11053        window: &mut Window,
11054        cx: &mut Context<Self>,
11055    ) {
11056        let Some(row_count) = self.visible_row_count() else {
11057            return;
11058        };
11059
11060        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11061
11062        let text_layout_details = &self.text_layout_details(window);
11063
11064        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11065            s.move_heads_with(|map, head, goal| {
11066                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
11067            })
11068        })
11069    }
11070
11071    pub fn move_page_up(
11072        &mut self,
11073        action: &MovePageUp,
11074        window: &mut Window,
11075        cx: &mut Context<Self>,
11076    ) {
11077        if self.take_rename(true, window, cx).is_some() {
11078            return;
11079        }
11080
11081        if self
11082            .context_menu
11083            .borrow_mut()
11084            .as_mut()
11085            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11086            .unwrap_or(false)
11087        {
11088            return;
11089        }
11090
11091        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11092            cx.propagate();
11093            return;
11094        }
11095
11096        let Some(row_count) = self.visible_row_count() else {
11097            return;
11098        };
11099
11100        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11101
11102        let autoscroll = if action.center_cursor {
11103            Autoscroll::center()
11104        } else {
11105            Autoscroll::fit()
11106        };
11107
11108        let text_layout_details = &self.text_layout_details(window);
11109
11110        self.change_selections(Some(autoscroll), window, cx, |s| {
11111            s.move_with(|map, selection| {
11112                if !selection.is_empty() {
11113                    selection.goal = SelectionGoal::None;
11114                }
11115                let (cursor, goal) = movement::up_by_rows(
11116                    map,
11117                    selection.end,
11118                    row_count,
11119                    selection.goal,
11120                    false,
11121                    text_layout_details,
11122                );
11123                selection.collapse_to(cursor, goal);
11124            });
11125        });
11126    }
11127
11128    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11129        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11130        let text_layout_details = &self.text_layout_details(window);
11131        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11132            s.move_heads_with(|map, head, goal| {
11133                movement::up(map, head, goal, false, text_layout_details)
11134            })
11135        })
11136    }
11137
11138    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11139        self.take_rename(true, window, cx);
11140
11141        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11142            cx.propagate();
11143            return;
11144        }
11145
11146        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11147
11148        let text_layout_details = &self.text_layout_details(window);
11149        let selection_count = self.selections.count();
11150        let first_selection = self.selections.first_anchor();
11151
11152        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11153            s.move_with(|map, selection| {
11154                if !selection.is_empty() {
11155                    selection.goal = SelectionGoal::None;
11156                }
11157                let (cursor, goal) = movement::down(
11158                    map,
11159                    selection.end,
11160                    selection.goal,
11161                    false,
11162                    text_layout_details,
11163                );
11164                selection.collapse_to(cursor, goal);
11165            });
11166        });
11167
11168        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11169        {
11170            cx.propagate();
11171        }
11172    }
11173
11174    pub fn select_page_down(
11175        &mut self,
11176        _: &SelectPageDown,
11177        window: &mut Window,
11178        cx: &mut Context<Self>,
11179    ) {
11180        let Some(row_count) = self.visible_row_count() else {
11181            return;
11182        };
11183
11184        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11185
11186        let text_layout_details = &self.text_layout_details(window);
11187
11188        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11189            s.move_heads_with(|map, head, goal| {
11190                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11191            })
11192        })
11193    }
11194
11195    pub fn move_page_down(
11196        &mut self,
11197        action: &MovePageDown,
11198        window: &mut Window,
11199        cx: &mut Context<Self>,
11200    ) {
11201        if self.take_rename(true, window, cx).is_some() {
11202            return;
11203        }
11204
11205        if self
11206            .context_menu
11207            .borrow_mut()
11208            .as_mut()
11209            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11210            .unwrap_or(false)
11211        {
11212            return;
11213        }
11214
11215        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11216            cx.propagate();
11217            return;
11218        }
11219
11220        let Some(row_count) = self.visible_row_count() else {
11221            return;
11222        };
11223
11224        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11225
11226        let autoscroll = if action.center_cursor {
11227            Autoscroll::center()
11228        } else {
11229            Autoscroll::fit()
11230        };
11231
11232        let text_layout_details = &self.text_layout_details(window);
11233        self.change_selections(Some(autoscroll), window, cx, |s| {
11234            s.move_with(|map, selection| {
11235                if !selection.is_empty() {
11236                    selection.goal = SelectionGoal::None;
11237                }
11238                let (cursor, goal) = movement::down_by_rows(
11239                    map,
11240                    selection.end,
11241                    row_count,
11242                    selection.goal,
11243                    false,
11244                    text_layout_details,
11245                );
11246                selection.collapse_to(cursor, goal);
11247            });
11248        });
11249    }
11250
11251    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11252        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11253        let text_layout_details = &self.text_layout_details(window);
11254        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11255            s.move_heads_with(|map, head, goal| {
11256                movement::down(map, head, goal, false, text_layout_details)
11257            })
11258        });
11259    }
11260
11261    pub fn context_menu_first(
11262        &mut self,
11263        _: &ContextMenuFirst,
11264        _window: &mut Window,
11265        cx: &mut Context<Self>,
11266    ) {
11267        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11268            context_menu.select_first(self.completion_provider.as_deref(), cx);
11269        }
11270    }
11271
11272    pub fn context_menu_prev(
11273        &mut self,
11274        _: &ContextMenuPrevious,
11275        _window: &mut Window,
11276        cx: &mut Context<Self>,
11277    ) {
11278        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11279            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11280        }
11281    }
11282
11283    pub fn context_menu_next(
11284        &mut self,
11285        _: &ContextMenuNext,
11286        _window: &mut Window,
11287        cx: &mut Context<Self>,
11288    ) {
11289        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11290            context_menu.select_next(self.completion_provider.as_deref(), cx);
11291        }
11292    }
11293
11294    pub fn context_menu_last(
11295        &mut self,
11296        _: &ContextMenuLast,
11297        _window: &mut Window,
11298        cx: &mut Context<Self>,
11299    ) {
11300        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11301            context_menu.select_last(self.completion_provider.as_deref(), cx);
11302        }
11303    }
11304
11305    pub fn move_to_previous_word_start(
11306        &mut self,
11307        _: &MoveToPreviousWordStart,
11308        window: &mut Window,
11309        cx: &mut Context<Self>,
11310    ) {
11311        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11312        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11313            s.move_cursors_with(|map, head, _| {
11314                (
11315                    movement::previous_word_start(map, head),
11316                    SelectionGoal::None,
11317                )
11318            });
11319        })
11320    }
11321
11322    pub fn move_to_previous_subword_start(
11323        &mut self,
11324        _: &MoveToPreviousSubwordStart,
11325        window: &mut Window,
11326        cx: &mut Context<Self>,
11327    ) {
11328        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11329        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11330            s.move_cursors_with(|map, head, _| {
11331                (
11332                    movement::previous_subword_start(map, head),
11333                    SelectionGoal::None,
11334                )
11335            });
11336        })
11337    }
11338
11339    pub fn select_to_previous_word_start(
11340        &mut self,
11341        _: &SelectToPreviousWordStart,
11342        window: &mut Window,
11343        cx: &mut Context<Self>,
11344    ) {
11345        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11346        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11347            s.move_heads_with(|map, head, _| {
11348                (
11349                    movement::previous_word_start(map, head),
11350                    SelectionGoal::None,
11351                )
11352            });
11353        })
11354    }
11355
11356    pub fn select_to_previous_subword_start(
11357        &mut self,
11358        _: &SelectToPreviousSubwordStart,
11359        window: &mut Window,
11360        cx: &mut Context<Self>,
11361    ) {
11362        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11363        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11364            s.move_heads_with(|map, head, _| {
11365                (
11366                    movement::previous_subword_start(map, head),
11367                    SelectionGoal::None,
11368                )
11369            });
11370        })
11371    }
11372
11373    pub fn delete_to_previous_word_start(
11374        &mut self,
11375        action: &DeleteToPreviousWordStart,
11376        window: &mut Window,
11377        cx: &mut Context<Self>,
11378    ) {
11379        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11380        self.transact(window, cx, |this, window, cx| {
11381            this.select_autoclose_pair(window, cx);
11382            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11383                s.move_with(|map, selection| {
11384                    if selection.is_empty() {
11385                        let cursor = if action.ignore_newlines {
11386                            movement::previous_word_start(map, selection.head())
11387                        } else {
11388                            movement::previous_word_start_or_newline(map, selection.head())
11389                        };
11390                        selection.set_head(cursor, SelectionGoal::None);
11391                    }
11392                });
11393            });
11394            this.insert("", window, cx);
11395        });
11396    }
11397
11398    pub fn delete_to_previous_subword_start(
11399        &mut self,
11400        _: &DeleteToPreviousSubwordStart,
11401        window: &mut Window,
11402        cx: &mut Context<Self>,
11403    ) {
11404        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11405        self.transact(window, cx, |this, window, cx| {
11406            this.select_autoclose_pair(window, cx);
11407            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11408                s.move_with(|map, selection| {
11409                    if selection.is_empty() {
11410                        let cursor = movement::previous_subword_start(map, selection.head());
11411                        selection.set_head(cursor, SelectionGoal::None);
11412                    }
11413                });
11414            });
11415            this.insert("", window, cx);
11416        });
11417    }
11418
11419    pub fn move_to_next_word_end(
11420        &mut self,
11421        _: &MoveToNextWordEnd,
11422        window: &mut Window,
11423        cx: &mut Context<Self>,
11424    ) {
11425        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11426        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11427            s.move_cursors_with(|map, head, _| {
11428                (movement::next_word_end(map, head), SelectionGoal::None)
11429            });
11430        })
11431    }
11432
11433    pub fn move_to_next_subword_end(
11434        &mut self,
11435        _: &MoveToNextSubwordEnd,
11436        window: &mut Window,
11437        cx: &mut Context<Self>,
11438    ) {
11439        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11440        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11441            s.move_cursors_with(|map, head, _| {
11442                (movement::next_subword_end(map, head), SelectionGoal::None)
11443            });
11444        })
11445    }
11446
11447    pub fn select_to_next_word_end(
11448        &mut self,
11449        _: &SelectToNextWordEnd,
11450        window: &mut Window,
11451        cx: &mut Context<Self>,
11452    ) {
11453        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11454        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11455            s.move_heads_with(|map, head, _| {
11456                (movement::next_word_end(map, head), SelectionGoal::None)
11457            });
11458        })
11459    }
11460
11461    pub fn select_to_next_subword_end(
11462        &mut self,
11463        _: &SelectToNextSubwordEnd,
11464        window: &mut Window,
11465        cx: &mut Context<Self>,
11466    ) {
11467        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11469            s.move_heads_with(|map, head, _| {
11470                (movement::next_subword_end(map, head), SelectionGoal::None)
11471            });
11472        })
11473    }
11474
11475    pub fn delete_to_next_word_end(
11476        &mut self,
11477        action: &DeleteToNextWordEnd,
11478        window: &mut Window,
11479        cx: &mut Context<Self>,
11480    ) {
11481        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11482        self.transact(window, cx, |this, window, cx| {
11483            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11484                s.move_with(|map, selection| {
11485                    if selection.is_empty() {
11486                        let cursor = if action.ignore_newlines {
11487                            movement::next_word_end(map, selection.head())
11488                        } else {
11489                            movement::next_word_end_or_newline(map, selection.head())
11490                        };
11491                        selection.set_head(cursor, SelectionGoal::None);
11492                    }
11493                });
11494            });
11495            this.insert("", window, cx);
11496        });
11497    }
11498
11499    pub fn delete_to_next_subword_end(
11500        &mut self,
11501        _: &DeleteToNextSubwordEnd,
11502        window: &mut Window,
11503        cx: &mut Context<Self>,
11504    ) {
11505        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11506        self.transact(window, cx, |this, window, cx| {
11507            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11508                s.move_with(|map, selection| {
11509                    if selection.is_empty() {
11510                        let cursor = movement::next_subword_end(map, selection.head());
11511                        selection.set_head(cursor, SelectionGoal::None);
11512                    }
11513                });
11514            });
11515            this.insert("", window, cx);
11516        });
11517    }
11518
11519    pub fn move_to_beginning_of_line(
11520        &mut self,
11521        action: &MoveToBeginningOfLine,
11522        window: &mut Window,
11523        cx: &mut Context<Self>,
11524    ) {
11525        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11527            s.move_cursors_with(|map, head, _| {
11528                (
11529                    movement::indented_line_beginning(
11530                        map,
11531                        head,
11532                        action.stop_at_soft_wraps,
11533                        action.stop_at_indent,
11534                    ),
11535                    SelectionGoal::None,
11536                )
11537            });
11538        })
11539    }
11540
11541    pub fn select_to_beginning_of_line(
11542        &mut self,
11543        action: &SelectToBeginningOfLine,
11544        window: &mut Window,
11545        cx: &mut Context<Self>,
11546    ) {
11547        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11548        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11549            s.move_heads_with(|map, head, _| {
11550                (
11551                    movement::indented_line_beginning(
11552                        map,
11553                        head,
11554                        action.stop_at_soft_wraps,
11555                        action.stop_at_indent,
11556                    ),
11557                    SelectionGoal::None,
11558                )
11559            });
11560        });
11561    }
11562
11563    pub fn delete_to_beginning_of_line(
11564        &mut self,
11565        action: &DeleteToBeginningOfLine,
11566        window: &mut Window,
11567        cx: &mut Context<Self>,
11568    ) {
11569        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11570        self.transact(window, cx, |this, window, cx| {
11571            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11572                s.move_with(|_, selection| {
11573                    selection.reversed = true;
11574                });
11575            });
11576
11577            this.select_to_beginning_of_line(
11578                &SelectToBeginningOfLine {
11579                    stop_at_soft_wraps: false,
11580                    stop_at_indent: action.stop_at_indent,
11581                },
11582                window,
11583                cx,
11584            );
11585            this.backspace(&Backspace, window, cx);
11586        });
11587    }
11588
11589    pub fn move_to_end_of_line(
11590        &mut self,
11591        action: &MoveToEndOfLine,
11592        window: &mut Window,
11593        cx: &mut Context<Self>,
11594    ) {
11595        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11596        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11597            s.move_cursors_with(|map, head, _| {
11598                (
11599                    movement::line_end(map, head, action.stop_at_soft_wraps),
11600                    SelectionGoal::None,
11601                )
11602            });
11603        })
11604    }
11605
11606    pub fn select_to_end_of_line(
11607        &mut self,
11608        action: &SelectToEndOfLine,
11609        window: &mut Window,
11610        cx: &mut Context<Self>,
11611    ) {
11612        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11613        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11614            s.move_heads_with(|map, head, _| {
11615                (
11616                    movement::line_end(map, head, action.stop_at_soft_wraps),
11617                    SelectionGoal::None,
11618                )
11619            });
11620        })
11621    }
11622
11623    pub fn delete_to_end_of_line(
11624        &mut self,
11625        _: &DeleteToEndOfLine,
11626        window: &mut Window,
11627        cx: &mut Context<Self>,
11628    ) {
11629        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11630        self.transact(window, cx, |this, window, cx| {
11631            this.select_to_end_of_line(
11632                &SelectToEndOfLine {
11633                    stop_at_soft_wraps: false,
11634                },
11635                window,
11636                cx,
11637            );
11638            this.delete(&Delete, window, cx);
11639        });
11640    }
11641
11642    pub fn cut_to_end_of_line(
11643        &mut self,
11644        _: &CutToEndOfLine,
11645        window: &mut Window,
11646        cx: &mut Context<Self>,
11647    ) {
11648        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11649        self.transact(window, cx, |this, window, cx| {
11650            this.select_to_end_of_line(
11651                &SelectToEndOfLine {
11652                    stop_at_soft_wraps: false,
11653                },
11654                window,
11655                cx,
11656            );
11657            this.cut(&Cut, window, cx);
11658        });
11659    }
11660
11661    pub fn move_to_start_of_paragraph(
11662        &mut self,
11663        _: &MoveToStartOfParagraph,
11664        window: &mut Window,
11665        cx: &mut Context<Self>,
11666    ) {
11667        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11668            cx.propagate();
11669            return;
11670        }
11671        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11672        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11673            s.move_with(|map, selection| {
11674                selection.collapse_to(
11675                    movement::start_of_paragraph(map, selection.head(), 1),
11676                    SelectionGoal::None,
11677                )
11678            });
11679        })
11680    }
11681
11682    pub fn move_to_end_of_paragraph(
11683        &mut self,
11684        _: &MoveToEndOfParagraph,
11685        window: &mut Window,
11686        cx: &mut Context<Self>,
11687    ) {
11688        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11689            cx.propagate();
11690            return;
11691        }
11692        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11693        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11694            s.move_with(|map, selection| {
11695                selection.collapse_to(
11696                    movement::end_of_paragraph(map, selection.head(), 1),
11697                    SelectionGoal::None,
11698                )
11699            });
11700        })
11701    }
11702
11703    pub fn select_to_start_of_paragraph(
11704        &mut self,
11705        _: &SelectToStartOfParagraph,
11706        window: &mut Window,
11707        cx: &mut Context<Self>,
11708    ) {
11709        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11710            cx.propagate();
11711            return;
11712        }
11713        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11714        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11715            s.move_heads_with(|map, head, _| {
11716                (
11717                    movement::start_of_paragraph(map, head, 1),
11718                    SelectionGoal::None,
11719                )
11720            });
11721        })
11722    }
11723
11724    pub fn select_to_end_of_paragraph(
11725        &mut self,
11726        _: &SelectToEndOfParagraph,
11727        window: &mut Window,
11728        cx: &mut Context<Self>,
11729    ) {
11730        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11731            cx.propagate();
11732            return;
11733        }
11734        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11735        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11736            s.move_heads_with(|map, head, _| {
11737                (
11738                    movement::end_of_paragraph(map, head, 1),
11739                    SelectionGoal::None,
11740                )
11741            });
11742        })
11743    }
11744
11745    pub fn move_to_start_of_excerpt(
11746        &mut self,
11747        _: &MoveToStartOfExcerpt,
11748        window: &mut Window,
11749        cx: &mut Context<Self>,
11750    ) {
11751        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11752            cx.propagate();
11753            return;
11754        }
11755        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11756        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11757            s.move_with(|map, selection| {
11758                selection.collapse_to(
11759                    movement::start_of_excerpt(
11760                        map,
11761                        selection.head(),
11762                        workspace::searchable::Direction::Prev,
11763                    ),
11764                    SelectionGoal::None,
11765                )
11766            });
11767        })
11768    }
11769
11770    pub fn move_to_start_of_next_excerpt(
11771        &mut self,
11772        _: &MoveToStartOfNextExcerpt,
11773        window: &mut Window,
11774        cx: &mut Context<Self>,
11775    ) {
11776        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11777            cx.propagate();
11778            return;
11779        }
11780
11781        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11782            s.move_with(|map, selection| {
11783                selection.collapse_to(
11784                    movement::start_of_excerpt(
11785                        map,
11786                        selection.head(),
11787                        workspace::searchable::Direction::Next,
11788                    ),
11789                    SelectionGoal::None,
11790                )
11791            });
11792        })
11793    }
11794
11795    pub fn move_to_end_of_excerpt(
11796        &mut self,
11797        _: &MoveToEndOfExcerpt,
11798        window: &mut Window,
11799        cx: &mut Context<Self>,
11800    ) {
11801        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11802            cx.propagate();
11803            return;
11804        }
11805        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11807            s.move_with(|map, selection| {
11808                selection.collapse_to(
11809                    movement::end_of_excerpt(
11810                        map,
11811                        selection.head(),
11812                        workspace::searchable::Direction::Next,
11813                    ),
11814                    SelectionGoal::None,
11815                )
11816            });
11817        })
11818    }
11819
11820    pub fn move_to_end_of_previous_excerpt(
11821        &mut self,
11822        _: &MoveToEndOfPreviousExcerpt,
11823        window: &mut Window,
11824        cx: &mut Context<Self>,
11825    ) {
11826        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11827            cx.propagate();
11828            return;
11829        }
11830        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11831        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11832            s.move_with(|map, selection| {
11833                selection.collapse_to(
11834                    movement::end_of_excerpt(
11835                        map,
11836                        selection.head(),
11837                        workspace::searchable::Direction::Prev,
11838                    ),
11839                    SelectionGoal::None,
11840                )
11841            });
11842        })
11843    }
11844
11845    pub fn select_to_start_of_excerpt(
11846        &mut self,
11847        _: &SelectToStartOfExcerpt,
11848        window: &mut Window,
11849        cx: &mut Context<Self>,
11850    ) {
11851        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11852            cx.propagate();
11853            return;
11854        }
11855        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11856        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11857            s.move_heads_with(|map, head, _| {
11858                (
11859                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11860                    SelectionGoal::None,
11861                )
11862            });
11863        })
11864    }
11865
11866    pub fn select_to_start_of_next_excerpt(
11867        &mut self,
11868        _: &SelectToStartOfNextExcerpt,
11869        window: &mut Window,
11870        cx: &mut Context<Self>,
11871    ) {
11872        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11873            cx.propagate();
11874            return;
11875        }
11876        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11877        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11878            s.move_heads_with(|map, head, _| {
11879                (
11880                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11881                    SelectionGoal::None,
11882                )
11883            });
11884        })
11885    }
11886
11887    pub fn select_to_end_of_excerpt(
11888        &mut self,
11889        _: &SelectToEndOfExcerpt,
11890        window: &mut Window,
11891        cx: &mut Context<Self>,
11892    ) {
11893        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11894            cx.propagate();
11895            return;
11896        }
11897        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11898        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11899            s.move_heads_with(|map, head, _| {
11900                (
11901                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11902                    SelectionGoal::None,
11903                )
11904            });
11905        })
11906    }
11907
11908    pub fn select_to_end_of_previous_excerpt(
11909        &mut self,
11910        _: &SelectToEndOfPreviousExcerpt,
11911        window: &mut Window,
11912        cx: &mut Context<Self>,
11913    ) {
11914        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11915            cx.propagate();
11916            return;
11917        }
11918        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11919        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11920            s.move_heads_with(|map, head, _| {
11921                (
11922                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11923                    SelectionGoal::None,
11924                )
11925            });
11926        })
11927    }
11928
11929    pub fn move_to_beginning(
11930        &mut self,
11931        _: &MoveToBeginning,
11932        window: &mut Window,
11933        cx: &mut Context<Self>,
11934    ) {
11935        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11936            cx.propagate();
11937            return;
11938        }
11939        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11941            s.select_ranges(vec![0..0]);
11942        });
11943    }
11944
11945    pub fn select_to_beginning(
11946        &mut self,
11947        _: &SelectToBeginning,
11948        window: &mut Window,
11949        cx: &mut Context<Self>,
11950    ) {
11951        let mut selection = self.selections.last::<Point>(cx);
11952        selection.set_head(Point::zero(), SelectionGoal::None);
11953        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11954        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11955            s.select(vec![selection]);
11956        });
11957    }
11958
11959    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11960        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11961            cx.propagate();
11962            return;
11963        }
11964        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11965        let cursor = self.buffer.read(cx).read(cx).len();
11966        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11967            s.select_ranges(vec![cursor..cursor])
11968        });
11969    }
11970
11971    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11972        self.nav_history = nav_history;
11973    }
11974
11975    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11976        self.nav_history.as_ref()
11977    }
11978
11979    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11980        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11981    }
11982
11983    fn push_to_nav_history(
11984        &mut self,
11985        cursor_anchor: Anchor,
11986        new_position: Option<Point>,
11987        is_deactivate: bool,
11988        cx: &mut Context<Self>,
11989    ) {
11990        if let Some(nav_history) = self.nav_history.as_mut() {
11991            let buffer = self.buffer.read(cx).read(cx);
11992            let cursor_position = cursor_anchor.to_point(&buffer);
11993            let scroll_state = self.scroll_manager.anchor();
11994            let scroll_top_row = scroll_state.top_row(&buffer);
11995            drop(buffer);
11996
11997            if let Some(new_position) = new_position {
11998                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11999                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
12000                    return;
12001                }
12002            }
12003
12004            nav_history.push(
12005                Some(NavigationData {
12006                    cursor_anchor,
12007                    cursor_position,
12008                    scroll_anchor: scroll_state,
12009                    scroll_top_row,
12010                }),
12011                cx,
12012            );
12013            cx.emit(EditorEvent::PushedToNavHistory {
12014                anchor: cursor_anchor,
12015                is_deactivate,
12016            })
12017        }
12018    }
12019
12020    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
12021        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12022        let buffer = self.buffer.read(cx).snapshot(cx);
12023        let mut selection = self.selections.first::<usize>(cx);
12024        selection.set_head(buffer.len(), SelectionGoal::None);
12025        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12026            s.select(vec![selection]);
12027        });
12028    }
12029
12030    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
12031        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12032        let end = self.buffer.read(cx).read(cx).len();
12033        self.change_selections(None, window, cx, |s| {
12034            s.select_ranges(vec![0..end]);
12035        });
12036    }
12037
12038    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
12039        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12040        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12041        let mut selections = self.selections.all::<Point>(cx);
12042        let max_point = display_map.buffer_snapshot.max_point();
12043        for selection in &mut selections {
12044            let rows = selection.spanned_rows(true, &display_map);
12045            selection.start = Point::new(rows.start.0, 0);
12046            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
12047            selection.reversed = false;
12048        }
12049        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12050            s.select(selections);
12051        });
12052    }
12053
12054    pub fn split_selection_into_lines(
12055        &mut self,
12056        _: &SplitSelectionIntoLines,
12057        window: &mut Window,
12058        cx: &mut Context<Self>,
12059    ) {
12060        let selections = self
12061            .selections
12062            .all::<Point>(cx)
12063            .into_iter()
12064            .map(|selection| selection.start..selection.end)
12065            .collect::<Vec<_>>();
12066        self.unfold_ranges(&selections, true, true, cx);
12067
12068        let mut new_selection_ranges = Vec::new();
12069        {
12070            let buffer = self.buffer.read(cx).read(cx);
12071            for selection in selections {
12072                for row in selection.start.row..selection.end.row {
12073                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12074                    new_selection_ranges.push(cursor..cursor);
12075                }
12076
12077                let is_multiline_selection = selection.start.row != selection.end.row;
12078                // Don't insert last one if it's a multi-line selection ending at the start of a line,
12079                // so this action feels more ergonomic when paired with other selection operations
12080                let should_skip_last = is_multiline_selection && selection.end.column == 0;
12081                if !should_skip_last {
12082                    new_selection_ranges.push(selection.end..selection.end);
12083                }
12084            }
12085        }
12086        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12087            s.select_ranges(new_selection_ranges);
12088        });
12089    }
12090
12091    pub fn add_selection_above(
12092        &mut self,
12093        _: &AddSelectionAbove,
12094        window: &mut Window,
12095        cx: &mut Context<Self>,
12096    ) {
12097        self.add_selection(true, window, cx);
12098    }
12099
12100    pub fn add_selection_below(
12101        &mut self,
12102        _: &AddSelectionBelow,
12103        window: &mut Window,
12104        cx: &mut Context<Self>,
12105    ) {
12106        self.add_selection(false, window, cx);
12107    }
12108
12109    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12110        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12111
12112        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12113        let mut selections = self.selections.all::<Point>(cx);
12114        let text_layout_details = self.text_layout_details(window);
12115        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12116            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12117            let range = oldest_selection.display_range(&display_map).sorted();
12118
12119            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12120            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12121            let positions = start_x.min(end_x)..start_x.max(end_x);
12122
12123            selections.clear();
12124            let mut stack = Vec::new();
12125            for row in range.start.row().0..=range.end.row().0 {
12126                if let Some(selection) = self.selections.build_columnar_selection(
12127                    &display_map,
12128                    DisplayRow(row),
12129                    &positions,
12130                    oldest_selection.reversed,
12131                    &text_layout_details,
12132                ) {
12133                    stack.push(selection.id);
12134                    selections.push(selection);
12135                }
12136            }
12137
12138            if above {
12139                stack.reverse();
12140            }
12141
12142            AddSelectionsState { above, stack }
12143        });
12144
12145        let last_added_selection = *state.stack.last().unwrap();
12146        let mut new_selections = Vec::new();
12147        if above == state.above {
12148            let end_row = if above {
12149                DisplayRow(0)
12150            } else {
12151                display_map.max_point().row()
12152            };
12153
12154            'outer: for selection in selections {
12155                if selection.id == last_added_selection {
12156                    let range = selection.display_range(&display_map).sorted();
12157                    debug_assert_eq!(range.start.row(), range.end.row());
12158                    let mut row = range.start.row();
12159                    let positions =
12160                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12161                            px(start)..px(end)
12162                        } else {
12163                            let start_x =
12164                                display_map.x_for_display_point(range.start, &text_layout_details);
12165                            let end_x =
12166                                display_map.x_for_display_point(range.end, &text_layout_details);
12167                            start_x.min(end_x)..start_x.max(end_x)
12168                        };
12169
12170                    while row != end_row {
12171                        if above {
12172                            row.0 -= 1;
12173                        } else {
12174                            row.0 += 1;
12175                        }
12176
12177                        if let Some(new_selection) = self.selections.build_columnar_selection(
12178                            &display_map,
12179                            row,
12180                            &positions,
12181                            selection.reversed,
12182                            &text_layout_details,
12183                        ) {
12184                            state.stack.push(new_selection.id);
12185                            if above {
12186                                new_selections.push(new_selection);
12187                                new_selections.push(selection);
12188                            } else {
12189                                new_selections.push(selection);
12190                                new_selections.push(new_selection);
12191                            }
12192
12193                            continue 'outer;
12194                        }
12195                    }
12196                }
12197
12198                new_selections.push(selection);
12199            }
12200        } else {
12201            new_selections = selections;
12202            new_selections.retain(|s| s.id != last_added_selection);
12203            state.stack.pop();
12204        }
12205
12206        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12207            s.select(new_selections);
12208        });
12209        if state.stack.len() > 1 {
12210            self.add_selections_state = Some(state);
12211        }
12212    }
12213
12214    fn select_match_ranges(
12215        &mut self,
12216        range: Range<usize>,
12217        reversed: bool,
12218        replace_newest: bool,
12219        auto_scroll: Option<Autoscroll>,
12220        window: &mut Window,
12221        cx: &mut Context<Editor>,
12222    ) {
12223        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12224        self.change_selections(auto_scroll, window, cx, |s| {
12225            if replace_newest {
12226                s.delete(s.newest_anchor().id);
12227            }
12228            if reversed {
12229                s.insert_range(range.end..range.start);
12230            } else {
12231                s.insert_range(range);
12232            }
12233        });
12234    }
12235
12236    pub fn select_next_match_internal(
12237        &mut self,
12238        display_map: &DisplaySnapshot,
12239        replace_newest: bool,
12240        autoscroll: Option<Autoscroll>,
12241        window: &mut Window,
12242        cx: &mut Context<Self>,
12243    ) -> Result<()> {
12244        let buffer = &display_map.buffer_snapshot;
12245        let mut selections = self.selections.all::<usize>(cx);
12246        if let Some(mut select_next_state) = self.select_next_state.take() {
12247            let query = &select_next_state.query;
12248            if !select_next_state.done {
12249                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12250                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12251                let mut next_selected_range = None;
12252
12253                let bytes_after_last_selection =
12254                    buffer.bytes_in_range(last_selection.end..buffer.len());
12255                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12256                let query_matches = query
12257                    .stream_find_iter(bytes_after_last_selection)
12258                    .map(|result| (last_selection.end, result))
12259                    .chain(
12260                        query
12261                            .stream_find_iter(bytes_before_first_selection)
12262                            .map(|result| (0, result)),
12263                    );
12264
12265                for (start_offset, query_match) in query_matches {
12266                    let query_match = query_match.unwrap(); // can only fail due to I/O
12267                    let offset_range =
12268                        start_offset + query_match.start()..start_offset + query_match.end();
12269                    let display_range = offset_range.start.to_display_point(display_map)
12270                        ..offset_range.end.to_display_point(display_map);
12271
12272                    if !select_next_state.wordwise
12273                        || (!movement::is_inside_word(display_map, display_range.start)
12274                            && !movement::is_inside_word(display_map, display_range.end))
12275                    {
12276                        // TODO: This is n^2, because we might check all the selections
12277                        if !selections
12278                            .iter()
12279                            .any(|selection| selection.range().overlaps(&offset_range))
12280                        {
12281                            next_selected_range = Some(offset_range);
12282                            break;
12283                        }
12284                    }
12285                }
12286
12287                if let Some(next_selected_range) = next_selected_range {
12288                    self.select_match_ranges(
12289                        next_selected_range,
12290                        last_selection.reversed,
12291                        replace_newest,
12292                        autoscroll,
12293                        window,
12294                        cx,
12295                    );
12296                } else {
12297                    select_next_state.done = true;
12298                }
12299            }
12300
12301            self.select_next_state = Some(select_next_state);
12302        } else {
12303            let mut only_carets = true;
12304            let mut same_text_selected = true;
12305            let mut selected_text = None;
12306
12307            let mut selections_iter = selections.iter().peekable();
12308            while let Some(selection) = selections_iter.next() {
12309                if selection.start != selection.end {
12310                    only_carets = false;
12311                }
12312
12313                if same_text_selected {
12314                    if selected_text.is_none() {
12315                        selected_text =
12316                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12317                    }
12318
12319                    if let Some(next_selection) = selections_iter.peek() {
12320                        if next_selection.range().len() == selection.range().len() {
12321                            let next_selected_text = buffer
12322                                .text_for_range(next_selection.range())
12323                                .collect::<String>();
12324                            if Some(next_selected_text) != selected_text {
12325                                same_text_selected = false;
12326                                selected_text = None;
12327                            }
12328                        } else {
12329                            same_text_selected = false;
12330                            selected_text = None;
12331                        }
12332                    }
12333                }
12334            }
12335
12336            if only_carets {
12337                for selection in &mut selections {
12338                    let word_range = movement::surrounding_word(
12339                        display_map,
12340                        selection.start.to_display_point(display_map),
12341                    );
12342                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12343                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12344                    selection.goal = SelectionGoal::None;
12345                    selection.reversed = false;
12346                    self.select_match_ranges(
12347                        selection.start..selection.end,
12348                        selection.reversed,
12349                        replace_newest,
12350                        autoscroll,
12351                        window,
12352                        cx,
12353                    );
12354                }
12355
12356                if selections.len() == 1 {
12357                    let selection = selections
12358                        .last()
12359                        .expect("ensured that there's only one selection");
12360                    let query = buffer
12361                        .text_for_range(selection.start..selection.end)
12362                        .collect::<String>();
12363                    let is_empty = query.is_empty();
12364                    let select_state = SelectNextState {
12365                        query: AhoCorasick::new(&[query])?,
12366                        wordwise: true,
12367                        done: is_empty,
12368                    };
12369                    self.select_next_state = Some(select_state);
12370                } else {
12371                    self.select_next_state = None;
12372                }
12373            } else if let Some(selected_text) = selected_text {
12374                self.select_next_state = Some(SelectNextState {
12375                    query: AhoCorasick::new(&[selected_text])?,
12376                    wordwise: false,
12377                    done: false,
12378                });
12379                self.select_next_match_internal(
12380                    display_map,
12381                    replace_newest,
12382                    autoscroll,
12383                    window,
12384                    cx,
12385                )?;
12386            }
12387        }
12388        Ok(())
12389    }
12390
12391    pub fn select_all_matches(
12392        &mut self,
12393        _action: &SelectAllMatches,
12394        window: &mut Window,
12395        cx: &mut Context<Self>,
12396    ) -> Result<()> {
12397        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12398
12399        self.push_to_selection_history();
12400        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12401
12402        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12403        let Some(select_next_state) = self.select_next_state.as_mut() else {
12404            return Ok(());
12405        };
12406        if select_next_state.done {
12407            return Ok(());
12408        }
12409
12410        let mut new_selections = Vec::new();
12411
12412        let reversed = self.selections.oldest::<usize>(cx).reversed;
12413        let buffer = &display_map.buffer_snapshot;
12414        let query_matches = select_next_state
12415            .query
12416            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12417
12418        for query_match in query_matches.into_iter() {
12419            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12420            let offset_range = if reversed {
12421                query_match.end()..query_match.start()
12422            } else {
12423                query_match.start()..query_match.end()
12424            };
12425            let display_range = offset_range.start.to_display_point(&display_map)
12426                ..offset_range.end.to_display_point(&display_map);
12427
12428            if !select_next_state.wordwise
12429                || (!movement::is_inside_word(&display_map, display_range.start)
12430                    && !movement::is_inside_word(&display_map, display_range.end))
12431            {
12432                new_selections.push(offset_range.start..offset_range.end);
12433            }
12434        }
12435
12436        select_next_state.done = true;
12437        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12438        self.change_selections(None, window, cx, |selections| {
12439            selections.select_ranges(new_selections)
12440        });
12441
12442        Ok(())
12443    }
12444
12445    pub fn select_next(
12446        &mut self,
12447        action: &SelectNext,
12448        window: &mut Window,
12449        cx: &mut Context<Self>,
12450    ) -> Result<()> {
12451        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12452        self.push_to_selection_history();
12453        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12454        self.select_next_match_internal(
12455            &display_map,
12456            action.replace_newest,
12457            Some(Autoscroll::newest()),
12458            window,
12459            cx,
12460        )?;
12461        Ok(())
12462    }
12463
12464    pub fn select_previous(
12465        &mut self,
12466        action: &SelectPrevious,
12467        window: &mut Window,
12468        cx: &mut Context<Self>,
12469    ) -> Result<()> {
12470        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12471        self.push_to_selection_history();
12472        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12473        let buffer = &display_map.buffer_snapshot;
12474        let mut selections = self.selections.all::<usize>(cx);
12475        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12476            let query = &select_prev_state.query;
12477            if !select_prev_state.done {
12478                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12479                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12480                let mut next_selected_range = None;
12481                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12482                let bytes_before_last_selection =
12483                    buffer.reversed_bytes_in_range(0..last_selection.start);
12484                let bytes_after_first_selection =
12485                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12486                let query_matches = query
12487                    .stream_find_iter(bytes_before_last_selection)
12488                    .map(|result| (last_selection.start, result))
12489                    .chain(
12490                        query
12491                            .stream_find_iter(bytes_after_first_selection)
12492                            .map(|result| (buffer.len(), result)),
12493                    );
12494                for (end_offset, query_match) in query_matches {
12495                    let query_match = query_match.unwrap(); // can only fail due to I/O
12496                    let offset_range =
12497                        end_offset - query_match.end()..end_offset - query_match.start();
12498                    let display_range = offset_range.start.to_display_point(&display_map)
12499                        ..offset_range.end.to_display_point(&display_map);
12500
12501                    if !select_prev_state.wordwise
12502                        || (!movement::is_inside_word(&display_map, display_range.start)
12503                            && !movement::is_inside_word(&display_map, display_range.end))
12504                    {
12505                        next_selected_range = Some(offset_range);
12506                        break;
12507                    }
12508                }
12509
12510                if let Some(next_selected_range) = next_selected_range {
12511                    self.select_match_ranges(
12512                        next_selected_range,
12513                        last_selection.reversed,
12514                        action.replace_newest,
12515                        Some(Autoscroll::newest()),
12516                        window,
12517                        cx,
12518                    );
12519                } else {
12520                    select_prev_state.done = true;
12521                }
12522            }
12523
12524            self.select_prev_state = Some(select_prev_state);
12525        } else {
12526            let mut only_carets = true;
12527            let mut same_text_selected = true;
12528            let mut selected_text = None;
12529
12530            let mut selections_iter = selections.iter().peekable();
12531            while let Some(selection) = selections_iter.next() {
12532                if selection.start != selection.end {
12533                    only_carets = false;
12534                }
12535
12536                if same_text_selected {
12537                    if selected_text.is_none() {
12538                        selected_text =
12539                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12540                    }
12541
12542                    if let Some(next_selection) = selections_iter.peek() {
12543                        if next_selection.range().len() == selection.range().len() {
12544                            let next_selected_text = buffer
12545                                .text_for_range(next_selection.range())
12546                                .collect::<String>();
12547                            if Some(next_selected_text) != selected_text {
12548                                same_text_selected = false;
12549                                selected_text = None;
12550                            }
12551                        } else {
12552                            same_text_selected = false;
12553                            selected_text = None;
12554                        }
12555                    }
12556                }
12557            }
12558
12559            if only_carets {
12560                for selection in &mut selections {
12561                    let word_range = movement::surrounding_word(
12562                        &display_map,
12563                        selection.start.to_display_point(&display_map),
12564                    );
12565                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12566                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12567                    selection.goal = SelectionGoal::None;
12568                    selection.reversed = false;
12569                    self.select_match_ranges(
12570                        selection.start..selection.end,
12571                        selection.reversed,
12572                        action.replace_newest,
12573                        Some(Autoscroll::newest()),
12574                        window,
12575                        cx,
12576                    );
12577                }
12578                if selections.len() == 1 {
12579                    let selection = selections
12580                        .last()
12581                        .expect("ensured that there's only one selection");
12582                    let query = buffer
12583                        .text_for_range(selection.start..selection.end)
12584                        .collect::<String>();
12585                    let is_empty = query.is_empty();
12586                    let select_state = SelectNextState {
12587                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12588                        wordwise: true,
12589                        done: is_empty,
12590                    };
12591                    self.select_prev_state = Some(select_state);
12592                } else {
12593                    self.select_prev_state = None;
12594                }
12595            } else if let Some(selected_text) = selected_text {
12596                self.select_prev_state = Some(SelectNextState {
12597                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12598                    wordwise: false,
12599                    done: false,
12600                });
12601                self.select_previous(action, window, cx)?;
12602            }
12603        }
12604        Ok(())
12605    }
12606
12607    pub fn find_next_match(
12608        &mut self,
12609        _: &FindNextMatch,
12610        window: &mut Window,
12611        cx: &mut Context<Self>,
12612    ) -> Result<()> {
12613        let selections = self.selections.disjoint_anchors();
12614        match selections.first() {
12615            Some(first) if selections.len() >= 2 => {
12616                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12617                    s.select_ranges([first.range()]);
12618                });
12619            }
12620            _ => self.select_next(
12621                &SelectNext {
12622                    replace_newest: true,
12623                },
12624                window,
12625                cx,
12626            )?,
12627        }
12628        Ok(())
12629    }
12630
12631    pub fn find_previous_match(
12632        &mut self,
12633        _: &FindPreviousMatch,
12634        window: &mut Window,
12635        cx: &mut Context<Self>,
12636    ) -> Result<()> {
12637        let selections = self.selections.disjoint_anchors();
12638        match selections.last() {
12639            Some(last) if selections.len() >= 2 => {
12640                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12641                    s.select_ranges([last.range()]);
12642                });
12643            }
12644            _ => self.select_previous(
12645                &SelectPrevious {
12646                    replace_newest: true,
12647                },
12648                window,
12649                cx,
12650            )?,
12651        }
12652        Ok(())
12653    }
12654
12655    pub fn toggle_comments(
12656        &mut self,
12657        action: &ToggleComments,
12658        window: &mut Window,
12659        cx: &mut Context<Self>,
12660    ) {
12661        if self.read_only(cx) {
12662            return;
12663        }
12664        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12665        let text_layout_details = &self.text_layout_details(window);
12666        self.transact(window, cx, |this, window, cx| {
12667            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12668            let mut edits = Vec::new();
12669            let mut selection_edit_ranges = Vec::new();
12670            let mut last_toggled_row = None;
12671            let snapshot = this.buffer.read(cx).read(cx);
12672            let empty_str: Arc<str> = Arc::default();
12673            let mut suffixes_inserted = Vec::new();
12674            let ignore_indent = action.ignore_indent;
12675
12676            fn comment_prefix_range(
12677                snapshot: &MultiBufferSnapshot,
12678                row: MultiBufferRow,
12679                comment_prefix: &str,
12680                comment_prefix_whitespace: &str,
12681                ignore_indent: bool,
12682            ) -> Range<Point> {
12683                let indent_size = if ignore_indent {
12684                    0
12685                } else {
12686                    snapshot.indent_size_for_line(row).len
12687                };
12688
12689                let start = Point::new(row.0, indent_size);
12690
12691                let mut line_bytes = snapshot
12692                    .bytes_in_range(start..snapshot.max_point())
12693                    .flatten()
12694                    .copied();
12695
12696                // If this line currently begins with the line comment prefix, then record
12697                // the range containing the prefix.
12698                if line_bytes
12699                    .by_ref()
12700                    .take(comment_prefix.len())
12701                    .eq(comment_prefix.bytes())
12702                {
12703                    // Include any whitespace that matches the comment prefix.
12704                    let matching_whitespace_len = line_bytes
12705                        .zip(comment_prefix_whitespace.bytes())
12706                        .take_while(|(a, b)| a == b)
12707                        .count() as u32;
12708                    let end = Point::new(
12709                        start.row,
12710                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12711                    );
12712                    start..end
12713                } else {
12714                    start..start
12715                }
12716            }
12717
12718            fn comment_suffix_range(
12719                snapshot: &MultiBufferSnapshot,
12720                row: MultiBufferRow,
12721                comment_suffix: &str,
12722                comment_suffix_has_leading_space: bool,
12723            ) -> Range<Point> {
12724                let end = Point::new(row.0, snapshot.line_len(row));
12725                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12726
12727                let mut line_end_bytes = snapshot
12728                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12729                    .flatten()
12730                    .copied();
12731
12732                let leading_space_len = if suffix_start_column > 0
12733                    && line_end_bytes.next() == Some(b' ')
12734                    && comment_suffix_has_leading_space
12735                {
12736                    1
12737                } else {
12738                    0
12739                };
12740
12741                // If this line currently begins with the line comment prefix, then record
12742                // the range containing the prefix.
12743                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12744                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12745                    start..end
12746                } else {
12747                    end..end
12748                }
12749            }
12750
12751            // TODO: Handle selections that cross excerpts
12752            for selection in &mut selections {
12753                let start_column = snapshot
12754                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12755                    .len;
12756                let language = if let Some(language) =
12757                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12758                {
12759                    language
12760                } else {
12761                    continue;
12762                };
12763
12764                selection_edit_ranges.clear();
12765
12766                // If multiple selections contain a given row, avoid processing that
12767                // row more than once.
12768                let mut start_row = MultiBufferRow(selection.start.row);
12769                if last_toggled_row == Some(start_row) {
12770                    start_row = start_row.next_row();
12771                }
12772                let end_row =
12773                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12774                        MultiBufferRow(selection.end.row - 1)
12775                    } else {
12776                        MultiBufferRow(selection.end.row)
12777                    };
12778                last_toggled_row = Some(end_row);
12779
12780                if start_row > end_row {
12781                    continue;
12782                }
12783
12784                // If the language has line comments, toggle those.
12785                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12786
12787                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12788                if ignore_indent {
12789                    full_comment_prefixes = full_comment_prefixes
12790                        .into_iter()
12791                        .map(|s| Arc::from(s.trim_end()))
12792                        .collect();
12793                }
12794
12795                if !full_comment_prefixes.is_empty() {
12796                    let first_prefix = full_comment_prefixes
12797                        .first()
12798                        .expect("prefixes is non-empty");
12799                    let prefix_trimmed_lengths = full_comment_prefixes
12800                        .iter()
12801                        .map(|p| p.trim_end_matches(' ').len())
12802                        .collect::<SmallVec<[usize; 4]>>();
12803
12804                    let mut all_selection_lines_are_comments = true;
12805
12806                    for row in start_row.0..=end_row.0 {
12807                        let row = MultiBufferRow(row);
12808                        if start_row < end_row && snapshot.is_line_blank(row) {
12809                            continue;
12810                        }
12811
12812                        let prefix_range = full_comment_prefixes
12813                            .iter()
12814                            .zip(prefix_trimmed_lengths.iter().copied())
12815                            .map(|(prefix, trimmed_prefix_len)| {
12816                                comment_prefix_range(
12817                                    snapshot.deref(),
12818                                    row,
12819                                    &prefix[..trimmed_prefix_len],
12820                                    &prefix[trimmed_prefix_len..],
12821                                    ignore_indent,
12822                                )
12823                            })
12824                            .max_by_key(|range| range.end.column - range.start.column)
12825                            .expect("prefixes is non-empty");
12826
12827                        if prefix_range.is_empty() {
12828                            all_selection_lines_are_comments = false;
12829                        }
12830
12831                        selection_edit_ranges.push(prefix_range);
12832                    }
12833
12834                    if all_selection_lines_are_comments {
12835                        edits.extend(
12836                            selection_edit_ranges
12837                                .iter()
12838                                .cloned()
12839                                .map(|range| (range, empty_str.clone())),
12840                        );
12841                    } else {
12842                        let min_column = selection_edit_ranges
12843                            .iter()
12844                            .map(|range| range.start.column)
12845                            .min()
12846                            .unwrap_or(0);
12847                        edits.extend(selection_edit_ranges.iter().map(|range| {
12848                            let position = Point::new(range.start.row, min_column);
12849                            (position..position, first_prefix.clone())
12850                        }));
12851                    }
12852                } else if let Some((full_comment_prefix, comment_suffix)) =
12853                    language.block_comment_delimiters()
12854                {
12855                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12856                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12857                    let prefix_range = comment_prefix_range(
12858                        snapshot.deref(),
12859                        start_row,
12860                        comment_prefix,
12861                        comment_prefix_whitespace,
12862                        ignore_indent,
12863                    );
12864                    let suffix_range = comment_suffix_range(
12865                        snapshot.deref(),
12866                        end_row,
12867                        comment_suffix.trim_start_matches(' '),
12868                        comment_suffix.starts_with(' '),
12869                    );
12870
12871                    if prefix_range.is_empty() || suffix_range.is_empty() {
12872                        edits.push((
12873                            prefix_range.start..prefix_range.start,
12874                            full_comment_prefix.clone(),
12875                        ));
12876                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12877                        suffixes_inserted.push((end_row, comment_suffix.len()));
12878                    } else {
12879                        edits.push((prefix_range, empty_str.clone()));
12880                        edits.push((suffix_range, empty_str.clone()));
12881                    }
12882                } else {
12883                    continue;
12884                }
12885            }
12886
12887            drop(snapshot);
12888            this.buffer.update(cx, |buffer, cx| {
12889                buffer.edit(edits, None, cx);
12890            });
12891
12892            // Adjust selections so that they end before any comment suffixes that
12893            // were inserted.
12894            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12895            let mut selections = this.selections.all::<Point>(cx);
12896            let snapshot = this.buffer.read(cx).read(cx);
12897            for selection in &mut selections {
12898                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12899                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12900                        Ordering::Less => {
12901                            suffixes_inserted.next();
12902                            continue;
12903                        }
12904                        Ordering::Greater => break,
12905                        Ordering::Equal => {
12906                            if selection.end.column == snapshot.line_len(row) {
12907                                if selection.is_empty() {
12908                                    selection.start.column -= suffix_len as u32;
12909                                }
12910                                selection.end.column -= suffix_len as u32;
12911                            }
12912                            break;
12913                        }
12914                    }
12915                }
12916            }
12917
12918            drop(snapshot);
12919            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12920                s.select(selections)
12921            });
12922
12923            let selections = this.selections.all::<Point>(cx);
12924            let selections_on_single_row = selections.windows(2).all(|selections| {
12925                selections[0].start.row == selections[1].start.row
12926                    && selections[0].end.row == selections[1].end.row
12927                    && selections[0].start.row == selections[0].end.row
12928            });
12929            let selections_selecting = selections
12930                .iter()
12931                .any(|selection| selection.start != selection.end);
12932            let advance_downwards = action.advance_downwards
12933                && selections_on_single_row
12934                && !selections_selecting
12935                && !matches!(this.mode, EditorMode::SingleLine { .. });
12936
12937            if advance_downwards {
12938                let snapshot = this.buffer.read(cx).snapshot(cx);
12939
12940                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12941                    s.move_cursors_with(|display_snapshot, display_point, _| {
12942                        let mut point = display_point.to_point(display_snapshot);
12943                        point.row += 1;
12944                        point = snapshot.clip_point(point, Bias::Left);
12945                        let display_point = point.to_display_point(display_snapshot);
12946                        let goal = SelectionGoal::HorizontalPosition(
12947                            display_snapshot
12948                                .x_for_display_point(display_point, text_layout_details)
12949                                .into(),
12950                        );
12951                        (display_point, goal)
12952                    })
12953                });
12954            }
12955        });
12956    }
12957
12958    pub fn select_enclosing_symbol(
12959        &mut self,
12960        _: &SelectEnclosingSymbol,
12961        window: &mut Window,
12962        cx: &mut Context<Self>,
12963    ) {
12964        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12965
12966        let buffer = self.buffer.read(cx).snapshot(cx);
12967        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12968
12969        fn update_selection(
12970            selection: &Selection<usize>,
12971            buffer_snap: &MultiBufferSnapshot,
12972        ) -> Option<Selection<usize>> {
12973            let cursor = selection.head();
12974            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12975            for symbol in symbols.iter().rev() {
12976                let start = symbol.range.start.to_offset(buffer_snap);
12977                let end = symbol.range.end.to_offset(buffer_snap);
12978                let new_range = start..end;
12979                if start < selection.start || end > selection.end {
12980                    return Some(Selection {
12981                        id: selection.id,
12982                        start: new_range.start,
12983                        end: new_range.end,
12984                        goal: SelectionGoal::None,
12985                        reversed: selection.reversed,
12986                    });
12987                }
12988            }
12989            None
12990        }
12991
12992        let mut selected_larger_symbol = false;
12993        let new_selections = old_selections
12994            .iter()
12995            .map(|selection| match update_selection(selection, &buffer) {
12996                Some(new_selection) => {
12997                    if new_selection.range() != selection.range() {
12998                        selected_larger_symbol = true;
12999                    }
13000                    new_selection
13001                }
13002                None => selection.clone(),
13003            })
13004            .collect::<Vec<_>>();
13005
13006        if selected_larger_symbol {
13007            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13008                s.select(new_selections);
13009            });
13010        }
13011    }
13012
13013    pub fn select_larger_syntax_node(
13014        &mut self,
13015        _: &SelectLargerSyntaxNode,
13016        window: &mut Window,
13017        cx: &mut Context<Self>,
13018    ) {
13019        let Some(visible_row_count) = self.visible_row_count() else {
13020            return;
13021        };
13022        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
13023        if old_selections.is_empty() {
13024            return;
13025        }
13026
13027        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13028
13029        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13030        let buffer = self.buffer.read(cx).snapshot(cx);
13031
13032        let mut selected_larger_node = false;
13033        let mut new_selections = old_selections
13034            .iter()
13035            .map(|selection| {
13036                let old_range = selection.start..selection.end;
13037
13038                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
13039                    // manually select word at selection
13040                    if ["string_content", "inline"].contains(&node.kind()) {
13041                        let word_range = {
13042                            let display_point = buffer
13043                                .offset_to_point(old_range.start)
13044                                .to_display_point(&display_map);
13045                            let Range { start, end } =
13046                                movement::surrounding_word(&display_map, display_point);
13047                            start.to_point(&display_map).to_offset(&buffer)
13048                                ..end.to_point(&display_map).to_offset(&buffer)
13049                        };
13050                        // ignore if word is already selected
13051                        if !word_range.is_empty() && old_range != word_range {
13052                            let last_word_range = {
13053                                let display_point = buffer
13054                                    .offset_to_point(old_range.end)
13055                                    .to_display_point(&display_map);
13056                                let Range { start, end } =
13057                                    movement::surrounding_word(&display_map, display_point);
13058                                start.to_point(&display_map).to_offset(&buffer)
13059                                    ..end.to_point(&display_map).to_offset(&buffer)
13060                            };
13061                            // only select word if start and end point belongs to same word
13062                            if word_range == last_word_range {
13063                                selected_larger_node = true;
13064                                return Selection {
13065                                    id: selection.id,
13066                                    start: word_range.start,
13067                                    end: word_range.end,
13068                                    goal: SelectionGoal::None,
13069                                    reversed: selection.reversed,
13070                                };
13071                            }
13072                        }
13073                    }
13074                }
13075
13076                let mut new_range = old_range.clone();
13077                while let Some((_node, containing_range)) =
13078                    buffer.syntax_ancestor(new_range.clone())
13079                {
13080                    new_range = match containing_range {
13081                        MultiOrSingleBufferOffsetRange::Single(_) => break,
13082                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
13083                    };
13084                    if !display_map.intersects_fold(new_range.start)
13085                        && !display_map.intersects_fold(new_range.end)
13086                    {
13087                        break;
13088                    }
13089                }
13090
13091                selected_larger_node |= new_range != old_range;
13092                Selection {
13093                    id: selection.id,
13094                    start: new_range.start,
13095                    end: new_range.end,
13096                    goal: SelectionGoal::None,
13097                    reversed: selection.reversed,
13098                }
13099            })
13100            .collect::<Vec<_>>();
13101
13102        if !selected_larger_node {
13103            return; // don't put this call in the history
13104        }
13105
13106        // scroll based on transformation done to the last selection created by the user
13107        let (last_old, last_new) = old_selections
13108            .last()
13109            .zip(new_selections.last().cloned())
13110            .expect("old_selections isn't empty");
13111
13112        // revert selection
13113        let is_selection_reversed = {
13114            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13115            new_selections.last_mut().expect("checked above").reversed =
13116                should_newest_selection_be_reversed;
13117            should_newest_selection_be_reversed
13118        };
13119
13120        if selected_larger_node {
13121            self.select_syntax_node_history.disable_clearing = true;
13122            self.change_selections(None, window, cx, |s| {
13123                s.select(new_selections.clone());
13124            });
13125            self.select_syntax_node_history.disable_clearing = false;
13126        }
13127
13128        let start_row = last_new.start.to_display_point(&display_map).row().0;
13129        let end_row = last_new.end.to_display_point(&display_map).row().0;
13130        let selection_height = end_row - start_row + 1;
13131        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13132
13133        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13134        let scroll_behavior = if fits_on_the_screen {
13135            self.request_autoscroll(Autoscroll::fit(), cx);
13136            SelectSyntaxNodeScrollBehavior::FitSelection
13137        } else if is_selection_reversed {
13138            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13139            SelectSyntaxNodeScrollBehavior::CursorTop
13140        } else {
13141            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13142            SelectSyntaxNodeScrollBehavior::CursorBottom
13143        };
13144
13145        self.select_syntax_node_history.push((
13146            old_selections,
13147            scroll_behavior,
13148            is_selection_reversed,
13149        ));
13150    }
13151
13152    pub fn select_smaller_syntax_node(
13153        &mut self,
13154        _: &SelectSmallerSyntaxNode,
13155        window: &mut Window,
13156        cx: &mut Context<Self>,
13157    ) {
13158        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13159
13160        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13161            self.select_syntax_node_history.pop()
13162        {
13163            if let Some(selection) = selections.last_mut() {
13164                selection.reversed = is_selection_reversed;
13165            }
13166
13167            self.select_syntax_node_history.disable_clearing = true;
13168            self.change_selections(None, window, cx, |s| {
13169                s.select(selections.to_vec());
13170            });
13171            self.select_syntax_node_history.disable_clearing = false;
13172
13173            match scroll_behavior {
13174                SelectSyntaxNodeScrollBehavior::CursorTop => {
13175                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13176                }
13177                SelectSyntaxNodeScrollBehavior::FitSelection => {
13178                    self.request_autoscroll(Autoscroll::fit(), cx);
13179                }
13180                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13181                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13182                }
13183            }
13184        }
13185    }
13186
13187    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13188        if !EditorSettings::get_global(cx).gutter.runnables {
13189            self.clear_tasks();
13190            return Task::ready(());
13191        }
13192        let project = self.project.as_ref().map(Entity::downgrade);
13193        let task_sources = self.lsp_task_sources(cx);
13194        cx.spawn_in(window, async move |editor, cx| {
13195            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13196            let Some(project) = project.and_then(|p| p.upgrade()) else {
13197                return;
13198            };
13199            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13200                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13201            }) else {
13202                return;
13203            };
13204
13205            let hide_runnables = project
13206                .update(cx, |project, cx| {
13207                    // Do not display any test indicators in non-dev server remote projects.
13208                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13209                })
13210                .unwrap_or(true);
13211            if hide_runnables {
13212                return;
13213            }
13214            let new_rows =
13215                cx.background_spawn({
13216                    let snapshot = display_snapshot.clone();
13217                    async move {
13218                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13219                    }
13220                })
13221                    .await;
13222            let Ok(lsp_tasks) =
13223                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13224            else {
13225                return;
13226            };
13227            let lsp_tasks = lsp_tasks.await;
13228
13229            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13230                lsp_tasks
13231                    .into_iter()
13232                    .flat_map(|(kind, tasks)| {
13233                        tasks.into_iter().filter_map(move |(location, task)| {
13234                            Some((kind.clone(), location?, task))
13235                        })
13236                    })
13237                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13238                        let buffer = location.target.buffer;
13239                        let buffer_snapshot = buffer.read(cx).snapshot();
13240                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13241                            |(excerpt_id, snapshot, _)| {
13242                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13243                                    display_snapshot
13244                                        .buffer_snapshot
13245                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13246                                } else {
13247                                    None
13248                                }
13249                            },
13250                        );
13251                        if let Some(offset) = offset {
13252                            let task_buffer_range =
13253                                location.target.range.to_point(&buffer_snapshot);
13254                            let context_buffer_range =
13255                                task_buffer_range.to_offset(&buffer_snapshot);
13256                            let context_range = BufferOffset(context_buffer_range.start)
13257                                ..BufferOffset(context_buffer_range.end);
13258
13259                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13260                                .or_insert_with(|| RunnableTasks {
13261                                    templates: Vec::new(),
13262                                    offset,
13263                                    column: task_buffer_range.start.column,
13264                                    extra_variables: HashMap::default(),
13265                                    context_range,
13266                                })
13267                                .templates
13268                                .push((kind, task.original_task().clone()));
13269                        }
13270
13271                        acc
13272                    })
13273            }) else {
13274                return;
13275            };
13276
13277            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13278            editor
13279                .update(cx, |editor, _| {
13280                    editor.clear_tasks();
13281                    for (key, mut value) in rows {
13282                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13283                            value.templates.extend(lsp_tasks.templates);
13284                        }
13285
13286                        editor.insert_tasks(key, value);
13287                    }
13288                    for (key, value) in lsp_tasks_by_rows {
13289                        editor.insert_tasks(key, value);
13290                    }
13291                })
13292                .ok();
13293        })
13294    }
13295    fn fetch_runnable_ranges(
13296        snapshot: &DisplaySnapshot,
13297        range: Range<Anchor>,
13298    ) -> Vec<language::RunnableRange> {
13299        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13300    }
13301
13302    fn runnable_rows(
13303        project: Entity<Project>,
13304        snapshot: DisplaySnapshot,
13305        runnable_ranges: Vec<RunnableRange>,
13306        mut cx: AsyncWindowContext,
13307    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13308        runnable_ranges
13309            .into_iter()
13310            .filter_map(|mut runnable| {
13311                let tasks = cx
13312                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13313                    .ok()?;
13314                if tasks.is_empty() {
13315                    return None;
13316                }
13317
13318                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13319
13320                let row = snapshot
13321                    .buffer_snapshot
13322                    .buffer_line_for_row(MultiBufferRow(point.row))?
13323                    .1
13324                    .start
13325                    .row;
13326
13327                let context_range =
13328                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13329                Some((
13330                    (runnable.buffer_id, row),
13331                    RunnableTasks {
13332                        templates: tasks,
13333                        offset: snapshot
13334                            .buffer_snapshot
13335                            .anchor_before(runnable.run_range.start),
13336                        context_range,
13337                        column: point.column,
13338                        extra_variables: runnable.extra_captures,
13339                    },
13340                ))
13341            })
13342            .collect()
13343    }
13344
13345    fn templates_with_tags(
13346        project: &Entity<Project>,
13347        runnable: &mut Runnable,
13348        cx: &mut App,
13349    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13350        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13351            let (worktree_id, file) = project
13352                .buffer_for_id(runnable.buffer, cx)
13353                .and_then(|buffer| buffer.read(cx).file())
13354                .map(|file| (file.worktree_id(cx), file.clone()))
13355                .unzip();
13356
13357            (
13358                project.task_store().read(cx).task_inventory().cloned(),
13359                worktree_id,
13360                file,
13361            )
13362        });
13363
13364        let mut templates_with_tags = mem::take(&mut runnable.tags)
13365            .into_iter()
13366            .flat_map(|RunnableTag(tag)| {
13367                inventory
13368                    .as_ref()
13369                    .into_iter()
13370                    .flat_map(|inventory| {
13371                        inventory.read(cx).list_tasks(
13372                            file.clone(),
13373                            Some(runnable.language.clone()),
13374                            worktree_id,
13375                            cx,
13376                        )
13377                    })
13378                    .filter(move |(_, template)| {
13379                        template.tags.iter().any(|source_tag| source_tag == &tag)
13380                    })
13381            })
13382            .sorted_by_key(|(kind, _)| kind.to_owned())
13383            .collect::<Vec<_>>();
13384        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13385            // Strongest source wins; if we have worktree tag binding, prefer that to
13386            // global and language bindings;
13387            // if we have a global binding, prefer that to language binding.
13388            let first_mismatch = templates_with_tags
13389                .iter()
13390                .position(|(tag_source, _)| tag_source != leading_tag_source);
13391            if let Some(index) = first_mismatch {
13392                templates_with_tags.truncate(index);
13393            }
13394        }
13395
13396        templates_with_tags
13397    }
13398
13399    pub fn move_to_enclosing_bracket(
13400        &mut self,
13401        _: &MoveToEnclosingBracket,
13402        window: &mut Window,
13403        cx: &mut Context<Self>,
13404    ) {
13405        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13406        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13407            s.move_offsets_with(|snapshot, selection| {
13408                let Some(enclosing_bracket_ranges) =
13409                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13410                else {
13411                    return;
13412                };
13413
13414                let mut best_length = usize::MAX;
13415                let mut best_inside = false;
13416                let mut best_in_bracket_range = false;
13417                let mut best_destination = None;
13418                for (open, close) in enclosing_bracket_ranges {
13419                    let close = close.to_inclusive();
13420                    let length = close.end() - open.start;
13421                    let inside = selection.start >= open.end && selection.end <= *close.start();
13422                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13423                        || close.contains(&selection.head());
13424
13425                    // If best is next to a bracket and current isn't, skip
13426                    if !in_bracket_range && best_in_bracket_range {
13427                        continue;
13428                    }
13429
13430                    // Prefer smaller lengths unless best is inside and current isn't
13431                    if length > best_length && (best_inside || !inside) {
13432                        continue;
13433                    }
13434
13435                    best_length = length;
13436                    best_inside = inside;
13437                    best_in_bracket_range = in_bracket_range;
13438                    best_destination = Some(
13439                        if close.contains(&selection.start) && close.contains(&selection.end) {
13440                            if inside { open.end } else { open.start }
13441                        } else if inside {
13442                            *close.start()
13443                        } else {
13444                            *close.end()
13445                        },
13446                    );
13447                }
13448
13449                if let Some(destination) = best_destination {
13450                    selection.collapse_to(destination, SelectionGoal::None);
13451                }
13452            })
13453        });
13454    }
13455
13456    pub fn undo_selection(
13457        &mut self,
13458        _: &UndoSelection,
13459        window: &mut Window,
13460        cx: &mut Context<Self>,
13461    ) {
13462        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13463        self.end_selection(window, cx);
13464        self.selection_history.mode = SelectionHistoryMode::Undoing;
13465        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13466            self.change_selections(None, window, cx, |s| {
13467                s.select_anchors(entry.selections.to_vec())
13468            });
13469            self.select_next_state = entry.select_next_state;
13470            self.select_prev_state = entry.select_prev_state;
13471            self.add_selections_state = entry.add_selections_state;
13472            self.request_autoscroll(Autoscroll::newest(), cx);
13473        }
13474        self.selection_history.mode = SelectionHistoryMode::Normal;
13475    }
13476
13477    pub fn redo_selection(
13478        &mut self,
13479        _: &RedoSelection,
13480        window: &mut Window,
13481        cx: &mut Context<Self>,
13482    ) {
13483        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13484        self.end_selection(window, cx);
13485        self.selection_history.mode = SelectionHistoryMode::Redoing;
13486        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13487            self.change_selections(None, window, cx, |s| {
13488                s.select_anchors(entry.selections.to_vec())
13489            });
13490            self.select_next_state = entry.select_next_state;
13491            self.select_prev_state = entry.select_prev_state;
13492            self.add_selections_state = entry.add_selections_state;
13493            self.request_autoscroll(Autoscroll::newest(), cx);
13494        }
13495        self.selection_history.mode = SelectionHistoryMode::Normal;
13496    }
13497
13498    pub fn expand_excerpts(
13499        &mut self,
13500        action: &ExpandExcerpts,
13501        _: &mut Window,
13502        cx: &mut Context<Self>,
13503    ) {
13504        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13505    }
13506
13507    pub fn expand_excerpts_down(
13508        &mut self,
13509        action: &ExpandExcerptsDown,
13510        _: &mut Window,
13511        cx: &mut Context<Self>,
13512    ) {
13513        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13514    }
13515
13516    pub fn expand_excerpts_up(
13517        &mut self,
13518        action: &ExpandExcerptsUp,
13519        _: &mut Window,
13520        cx: &mut Context<Self>,
13521    ) {
13522        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13523    }
13524
13525    pub fn expand_excerpts_for_direction(
13526        &mut self,
13527        lines: u32,
13528        direction: ExpandExcerptDirection,
13529
13530        cx: &mut Context<Self>,
13531    ) {
13532        let selections = self.selections.disjoint_anchors();
13533
13534        let lines = if lines == 0 {
13535            EditorSettings::get_global(cx).expand_excerpt_lines
13536        } else {
13537            lines
13538        };
13539
13540        self.buffer.update(cx, |buffer, cx| {
13541            let snapshot = buffer.snapshot(cx);
13542            let mut excerpt_ids = selections
13543                .iter()
13544                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13545                .collect::<Vec<_>>();
13546            excerpt_ids.sort();
13547            excerpt_ids.dedup();
13548            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13549        })
13550    }
13551
13552    pub fn expand_excerpt(
13553        &mut self,
13554        excerpt: ExcerptId,
13555        direction: ExpandExcerptDirection,
13556        window: &mut Window,
13557        cx: &mut Context<Self>,
13558    ) {
13559        let current_scroll_position = self.scroll_position(cx);
13560        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13561        let mut should_scroll_up = false;
13562
13563        if direction == ExpandExcerptDirection::Down {
13564            let multi_buffer = self.buffer.read(cx);
13565            let snapshot = multi_buffer.snapshot(cx);
13566            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13567                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13568                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13569                        let buffer_snapshot = buffer.read(cx).snapshot();
13570                        let excerpt_end_row =
13571                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13572                        let last_row = buffer_snapshot.max_point().row;
13573                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13574                        should_scroll_up = lines_below >= lines_to_expand;
13575                    }
13576                }
13577            }
13578        }
13579
13580        self.buffer.update(cx, |buffer, cx| {
13581            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13582        });
13583
13584        if should_scroll_up {
13585            let new_scroll_position =
13586                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13587            self.set_scroll_position(new_scroll_position, window, cx);
13588        }
13589    }
13590
13591    pub fn go_to_singleton_buffer_point(
13592        &mut self,
13593        point: Point,
13594        window: &mut Window,
13595        cx: &mut Context<Self>,
13596    ) {
13597        self.go_to_singleton_buffer_range(point..point, window, cx);
13598    }
13599
13600    pub fn go_to_singleton_buffer_range(
13601        &mut self,
13602        range: Range<Point>,
13603        window: &mut Window,
13604        cx: &mut Context<Self>,
13605    ) {
13606        let multibuffer = self.buffer().read(cx);
13607        let Some(buffer) = multibuffer.as_singleton() else {
13608            return;
13609        };
13610        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13611            return;
13612        };
13613        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13614            return;
13615        };
13616        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13617            s.select_anchor_ranges([start..end])
13618        });
13619    }
13620
13621    pub fn go_to_diagnostic(
13622        &mut self,
13623        _: &GoToDiagnostic,
13624        window: &mut Window,
13625        cx: &mut Context<Self>,
13626    ) {
13627        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13628        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13629    }
13630
13631    pub fn go_to_prev_diagnostic(
13632        &mut self,
13633        _: &GoToPreviousDiagnostic,
13634        window: &mut Window,
13635        cx: &mut Context<Self>,
13636    ) {
13637        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13638        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13639    }
13640
13641    pub fn go_to_diagnostic_impl(
13642        &mut self,
13643        direction: Direction,
13644        window: &mut Window,
13645        cx: &mut Context<Self>,
13646    ) {
13647        let buffer = self.buffer.read(cx).snapshot(cx);
13648        let selection = self.selections.newest::<usize>(cx);
13649
13650        let mut active_group_id = None;
13651        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13652            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13653                active_group_id = Some(active_group.group_id);
13654            }
13655        }
13656
13657        fn filtered(
13658            snapshot: EditorSnapshot,
13659            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13660        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13661            diagnostics
13662                .filter(|entry| entry.range.start != entry.range.end)
13663                .filter(|entry| !entry.diagnostic.is_unnecessary)
13664                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13665        }
13666
13667        let snapshot = self.snapshot(window, cx);
13668        let before = filtered(
13669            snapshot.clone(),
13670            buffer
13671                .diagnostics_in_range(0..selection.start)
13672                .filter(|entry| entry.range.start <= selection.start),
13673        );
13674        let after = filtered(
13675            snapshot,
13676            buffer
13677                .diagnostics_in_range(selection.start..buffer.len())
13678                .filter(|entry| entry.range.start >= selection.start),
13679        );
13680
13681        let mut found: Option<DiagnosticEntry<usize>> = None;
13682        if direction == Direction::Prev {
13683            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13684            {
13685                for diagnostic in prev_diagnostics.into_iter().rev() {
13686                    if diagnostic.range.start != selection.start
13687                        || active_group_id
13688                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13689                    {
13690                        found = Some(diagnostic);
13691                        break 'outer;
13692                    }
13693                }
13694            }
13695        } else {
13696            for diagnostic in after.chain(before) {
13697                if diagnostic.range.start != selection.start
13698                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13699                {
13700                    found = Some(diagnostic);
13701                    break;
13702                }
13703            }
13704        }
13705        let Some(next_diagnostic) = found else {
13706            return;
13707        };
13708
13709        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13710            return;
13711        };
13712        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13713            s.select_ranges(vec![
13714                next_diagnostic.range.start..next_diagnostic.range.start,
13715            ])
13716        });
13717        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13718        self.refresh_inline_completion(false, true, window, cx);
13719    }
13720
13721    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13722        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13723        let snapshot = self.snapshot(window, cx);
13724        let selection = self.selections.newest::<Point>(cx);
13725        self.go_to_hunk_before_or_after_position(
13726            &snapshot,
13727            selection.head(),
13728            Direction::Next,
13729            window,
13730            cx,
13731        );
13732    }
13733
13734    pub fn go_to_hunk_before_or_after_position(
13735        &mut self,
13736        snapshot: &EditorSnapshot,
13737        position: Point,
13738        direction: Direction,
13739        window: &mut Window,
13740        cx: &mut Context<Editor>,
13741    ) {
13742        let row = if direction == Direction::Next {
13743            self.hunk_after_position(snapshot, position)
13744                .map(|hunk| hunk.row_range.start)
13745        } else {
13746            self.hunk_before_position(snapshot, position)
13747        };
13748
13749        if let Some(row) = row {
13750            let destination = Point::new(row.0, 0);
13751            let autoscroll = Autoscroll::center();
13752
13753            self.unfold_ranges(&[destination..destination], false, false, cx);
13754            self.change_selections(Some(autoscroll), window, cx, |s| {
13755                s.select_ranges([destination..destination]);
13756            });
13757        }
13758    }
13759
13760    fn hunk_after_position(
13761        &mut self,
13762        snapshot: &EditorSnapshot,
13763        position: Point,
13764    ) -> Option<MultiBufferDiffHunk> {
13765        snapshot
13766            .buffer_snapshot
13767            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13768            .find(|hunk| hunk.row_range.start.0 > position.row)
13769            .or_else(|| {
13770                snapshot
13771                    .buffer_snapshot
13772                    .diff_hunks_in_range(Point::zero()..position)
13773                    .find(|hunk| hunk.row_range.end.0 < position.row)
13774            })
13775    }
13776
13777    fn go_to_prev_hunk(
13778        &mut self,
13779        _: &GoToPreviousHunk,
13780        window: &mut Window,
13781        cx: &mut Context<Self>,
13782    ) {
13783        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13784        let snapshot = self.snapshot(window, cx);
13785        let selection = self.selections.newest::<Point>(cx);
13786        self.go_to_hunk_before_or_after_position(
13787            &snapshot,
13788            selection.head(),
13789            Direction::Prev,
13790            window,
13791            cx,
13792        );
13793    }
13794
13795    fn hunk_before_position(
13796        &mut self,
13797        snapshot: &EditorSnapshot,
13798        position: Point,
13799    ) -> Option<MultiBufferRow> {
13800        snapshot
13801            .buffer_snapshot
13802            .diff_hunk_before(position)
13803            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13804    }
13805
13806    fn go_to_next_change(
13807        &mut self,
13808        _: &GoToNextChange,
13809        window: &mut Window,
13810        cx: &mut Context<Self>,
13811    ) {
13812        if let Some(selections) = self
13813            .change_list
13814            .next_change(1, Direction::Next)
13815            .map(|s| s.to_vec())
13816        {
13817            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13818                let map = s.display_map();
13819                s.select_display_ranges(selections.iter().map(|a| {
13820                    let point = a.to_display_point(&map);
13821                    point..point
13822                }))
13823            })
13824        }
13825    }
13826
13827    fn go_to_previous_change(
13828        &mut self,
13829        _: &GoToPreviousChange,
13830        window: &mut Window,
13831        cx: &mut Context<Self>,
13832    ) {
13833        if let Some(selections) = self
13834            .change_list
13835            .next_change(1, Direction::Prev)
13836            .map(|s| s.to_vec())
13837        {
13838            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13839                let map = s.display_map();
13840                s.select_display_ranges(selections.iter().map(|a| {
13841                    let point = a.to_display_point(&map);
13842                    point..point
13843                }))
13844            })
13845        }
13846    }
13847
13848    fn go_to_line<T: 'static>(
13849        &mut self,
13850        position: Anchor,
13851        highlight_color: Option<Hsla>,
13852        window: &mut Window,
13853        cx: &mut Context<Self>,
13854    ) {
13855        let snapshot = self.snapshot(window, cx).display_snapshot;
13856        let position = position.to_point(&snapshot.buffer_snapshot);
13857        let start = snapshot
13858            .buffer_snapshot
13859            .clip_point(Point::new(position.row, 0), Bias::Left);
13860        let end = start + Point::new(1, 0);
13861        let start = snapshot.buffer_snapshot.anchor_before(start);
13862        let end = snapshot.buffer_snapshot.anchor_before(end);
13863
13864        self.highlight_rows::<T>(
13865            start..end,
13866            highlight_color
13867                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13868            Default::default(),
13869            cx,
13870        );
13871        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13872    }
13873
13874    pub fn go_to_definition(
13875        &mut self,
13876        _: &GoToDefinition,
13877        window: &mut Window,
13878        cx: &mut Context<Self>,
13879    ) -> Task<Result<Navigated>> {
13880        let definition =
13881            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13882        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13883        cx.spawn_in(window, async move |editor, cx| {
13884            if definition.await? == Navigated::Yes {
13885                return Ok(Navigated::Yes);
13886            }
13887            match fallback_strategy {
13888                GoToDefinitionFallback::None => Ok(Navigated::No),
13889                GoToDefinitionFallback::FindAllReferences => {
13890                    match editor.update_in(cx, |editor, window, cx| {
13891                        editor.find_all_references(&FindAllReferences, window, cx)
13892                    })? {
13893                        Some(references) => references.await,
13894                        None => Ok(Navigated::No),
13895                    }
13896                }
13897            }
13898        })
13899    }
13900
13901    pub fn go_to_declaration(
13902        &mut self,
13903        _: &GoToDeclaration,
13904        window: &mut Window,
13905        cx: &mut Context<Self>,
13906    ) -> Task<Result<Navigated>> {
13907        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13908    }
13909
13910    pub fn go_to_declaration_split(
13911        &mut self,
13912        _: &GoToDeclaration,
13913        window: &mut Window,
13914        cx: &mut Context<Self>,
13915    ) -> Task<Result<Navigated>> {
13916        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13917    }
13918
13919    pub fn go_to_implementation(
13920        &mut self,
13921        _: &GoToImplementation,
13922        window: &mut Window,
13923        cx: &mut Context<Self>,
13924    ) -> Task<Result<Navigated>> {
13925        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13926    }
13927
13928    pub fn go_to_implementation_split(
13929        &mut self,
13930        _: &GoToImplementationSplit,
13931        window: &mut Window,
13932        cx: &mut Context<Self>,
13933    ) -> Task<Result<Navigated>> {
13934        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13935    }
13936
13937    pub fn go_to_type_definition(
13938        &mut self,
13939        _: &GoToTypeDefinition,
13940        window: &mut Window,
13941        cx: &mut Context<Self>,
13942    ) -> Task<Result<Navigated>> {
13943        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13944    }
13945
13946    pub fn go_to_definition_split(
13947        &mut self,
13948        _: &GoToDefinitionSplit,
13949        window: &mut Window,
13950        cx: &mut Context<Self>,
13951    ) -> Task<Result<Navigated>> {
13952        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13953    }
13954
13955    pub fn go_to_type_definition_split(
13956        &mut self,
13957        _: &GoToTypeDefinitionSplit,
13958        window: &mut Window,
13959        cx: &mut Context<Self>,
13960    ) -> Task<Result<Navigated>> {
13961        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13962    }
13963
13964    fn go_to_definition_of_kind(
13965        &mut self,
13966        kind: GotoDefinitionKind,
13967        split: bool,
13968        window: &mut Window,
13969        cx: &mut Context<Self>,
13970    ) -> Task<Result<Navigated>> {
13971        let Some(provider) = self.semantics_provider.clone() else {
13972            return Task::ready(Ok(Navigated::No));
13973        };
13974        let head = self.selections.newest::<usize>(cx).head();
13975        let buffer = self.buffer.read(cx);
13976        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13977            text_anchor
13978        } else {
13979            return Task::ready(Ok(Navigated::No));
13980        };
13981
13982        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13983            return Task::ready(Ok(Navigated::No));
13984        };
13985
13986        cx.spawn_in(window, async move |editor, cx| {
13987            let definitions = definitions.await?;
13988            let navigated = editor
13989                .update_in(cx, |editor, window, cx| {
13990                    editor.navigate_to_hover_links(
13991                        Some(kind),
13992                        definitions
13993                            .into_iter()
13994                            .filter(|location| {
13995                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13996                            })
13997                            .map(HoverLink::Text)
13998                            .collect::<Vec<_>>(),
13999                        split,
14000                        window,
14001                        cx,
14002                    )
14003                })?
14004                .await?;
14005            anyhow::Ok(navigated)
14006        })
14007    }
14008
14009    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
14010        let selection = self.selections.newest_anchor();
14011        let head = selection.head();
14012        let tail = selection.tail();
14013
14014        let Some((buffer, start_position)) =
14015            self.buffer.read(cx).text_anchor_for_position(head, cx)
14016        else {
14017            return;
14018        };
14019
14020        let end_position = if head != tail {
14021            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
14022                return;
14023            };
14024            Some(pos)
14025        } else {
14026            None
14027        };
14028
14029        let url_finder = cx.spawn_in(window, async move |editor, cx| {
14030            let url = if let Some(end_pos) = end_position {
14031                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
14032            } else {
14033                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
14034            };
14035
14036            if let Some(url) = url {
14037                editor.update(cx, |_, cx| {
14038                    cx.open_url(&url);
14039                })
14040            } else {
14041                Ok(())
14042            }
14043        });
14044
14045        url_finder.detach();
14046    }
14047
14048    pub fn open_selected_filename(
14049        &mut self,
14050        _: &OpenSelectedFilename,
14051        window: &mut Window,
14052        cx: &mut Context<Self>,
14053    ) {
14054        let Some(workspace) = self.workspace() else {
14055            return;
14056        };
14057
14058        let position = self.selections.newest_anchor().head();
14059
14060        let Some((buffer, buffer_position)) =
14061            self.buffer.read(cx).text_anchor_for_position(position, cx)
14062        else {
14063            return;
14064        };
14065
14066        let project = self.project.clone();
14067
14068        cx.spawn_in(window, async move |_, cx| {
14069            let result = find_file(&buffer, project, buffer_position, cx).await;
14070
14071            if let Some((_, path)) = result {
14072                workspace
14073                    .update_in(cx, |workspace, window, cx| {
14074                        workspace.open_resolved_path(path, window, cx)
14075                    })?
14076                    .await?;
14077            }
14078            anyhow::Ok(())
14079        })
14080        .detach();
14081    }
14082
14083    pub(crate) fn navigate_to_hover_links(
14084        &mut self,
14085        kind: Option<GotoDefinitionKind>,
14086        mut definitions: Vec<HoverLink>,
14087        split: bool,
14088        window: &mut Window,
14089        cx: &mut Context<Editor>,
14090    ) -> Task<Result<Navigated>> {
14091        // If there is one definition, just open it directly
14092        if definitions.len() == 1 {
14093            let definition = definitions.pop().unwrap();
14094
14095            enum TargetTaskResult {
14096                Location(Option<Location>),
14097                AlreadyNavigated,
14098            }
14099
14100            let target_task = match definition {
14101                HoverLink::Text(link) => {
14102                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14103                }
14104                HoverLink::InlayHint(lsp_location, server_id) => {
14105                    let computation =
14106                        self.compute_target_location(lsp_location, server_id, window, cx);
14107                    cx.background_spawn(async move {
14108                        let location = computation.await?;
14109                        Ok(TargetTaskResult::Location(location))
14110                    })
14111                }
14112                HoverLink::Url(url) => {
14113                    cx.open_url(&url);
14114                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14115                }
14116                HoverLink::File(path) => {
14117                    if let Some(workspace) = self.workspace() {
14118                        cx.spawn_in(window, async move |_, cx| {
14119                            workspace
14120                                .update_in(cx, |workspace, window, cx| {
14121                                    workspace.open_resolved_path(path, window, cx)
14122                                })?
14123                                .await
14124                                .map(|_| TargetTaskResult::AlreadyNavigated)
14125                        })
14126                    } else {
14127                        Task::ready(Ok(TargetTaskResult::Location(None)))
14128                    }
14129                }
14130            };
14131            cx.spawn_in(window, async move |editor, cx| {
14132                let target = match target_task.await.context("target resolution task")? {
14133                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14134                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14135                    TargetTaskResult::Location(Some(target)) => target,
14136                };
14137
14138                editor.update_in(cx, |editor, window, cx| {
14139                    let Some(workspace) = editor.workspace() else {
14140                        return Navigated::No;
14141                    };
14142                    let pane = workspace.read(cx).active_pane().clone();
14143
14144                    let range = target.range.to_point(target.buffer.read(cx));
14145                    let range = editor.range_for_match(&range);
14146                    let range = collapse_multiline_range(range);
14147
14148                    if !split
14149                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14150                    {
14151                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14152                    } else {
14153                        window.defer(cx, move |window, cx| {
14154                            let target_editor: Entity<Self> =
14155                                workspace.update(cx, |workspace, cx| {
14156                                    let pane = if split {
14157                                        workspace.adjacent_pane(window, cx)
14158                                    } else {
14159                                        workspace.active_pane().clone()
14160                                    };
14161
14162                                    workspace.open_project_item(
14163                                        pane,
14164                                        target.buffer.clone(),
14165                                        true,
14166                                        true,
14167                                        window,
14168                                        cx,
14169                                    )
14170                                });
14171                            target_editor.update(cx, |target_editor, cx| {
14172                                // When selecting a definition in a different buffer, disable the nav history
14173                                // to avoid creating a history entry at the previous cursor location.
14174                                pane.update(cx, |pane, _| pane.disable_history());
14175                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14176                                pane.update(cx, |pane, _| pane.enable_history());
14177                            });
14178                        });
14179                    }
14180                    Navigated::Yes
14181                })
14182            })
14183        } else if !definitions.is_empty() {
14184            cx.spawn_in(window, async move |editor, cx| {
14185                let (title, location_tasks, workspace) = editor
14186                    .update_in(cx, |editor, window, cx| {
14187                        let tab_kind = match kind {
14188                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14189                            _ => "Definitions",
14190                        };
14191                        let title = definitions
14192                            .iter()
14193                            .find_map(|definition| match definition {
14194                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14195                                    let buffer = origin.buffer.read(cx);
14196                                    format!(
14197                                        "{} for {}",
14198                                        tab_kind,
14199                                        buffer
14200                                            .text_for_range(origin.range.clone())
14201                                            .collect::<String>()
14202                                    )
14203                                }),
14204                                HoverLink::InlayHint(_, _) => None,
14205                                HoverLink::Url(_) => None,
14206                                HoverLink::File(_) => None,
14207                            })
14208                            .unwrap_or(tab_kind.to_string());
14209                        let location_tasks = definitions
14210                            .into_iter()
14211                            .map(|definition| match definition {
14212                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14213                                HoverLink::InlayHint(lsp_location, server_id) => editor
14214                                    .compute_target_location(lsp_location, server_id, window, cx),
14215                                HoverLink::Url(_) => Task::ready(Ok(None)),
14216                                HoverLink::File(_) => Task::ready(Ok(None)),
14217                            })
14218                            .collect::<Vec<_>>();
14219                        (title, location_tasks, editor.workspace().clone())
14220                    })
14221                    .context("location tasks preparation")?;
14222
14223                let locations = future::join_all(location_tasks)
14224                    .await
14225                    .into_iter()
14226                    .filter_map(|location| location.transpose())
14227                    .collect::<Result<_>>()
14228                    .context("location tasks")?;
14229
14230                let Some(workspace) = workspace else {
14231                    return Ok(Navigated::No);
14232                };
14233                let opened = workspace
14234                    .update_in(cx, |workspace, window, cx| {
14235                        Self::open_locations_in_multibuffer(
14236                            workspace,
14237                            locations,
14238                            title,
14239                            split,
14240                            MultibufferSelectionMode::First,
14241                            window,
14242                            cx,
14243                        )
14244                    })
14245                    .ok();
14246
14247                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14248            })
14249        } else {
14250            Task::ready(Ok(Navigated::No))
14251        }
14252    }
14253
14254    fn compute_target_location(
14255        &self,
14256        lsp_location: lsp::Location,
14257        server_id: LanguageServerId,
14258        window: &mut Window,
14259        cx: &mut Context<Self>,
14260    ) -> Task<anyhow::Result<Option<Location>>> {
14261        let Some(project) = self.project.clone() else {
14262            return Task::ready(Ok(None));
14263        };
14264
14265        cx.spawn_in(window, async move |editor, cx| {
14266            let location_task = editor.update(cx, |_, cx| {
14267                project.update(cx, |project, cx| {
14268                    let language_server_name = project
14269                        .language_server_statuses(cx)
14270                        .find(|(id, _)| server_id == *id)
14271                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14272                    language_server_name.map(|language_server_name| {
14273                        project.open_local_buffer_via_lsp(
14274                            lsp_location.uri.clone(),
14275                            server_id,
14276                            language_server_name,
14277                            cx,
14278                        )
14279                    })
14280                })
14281            })?;
14282            let location = match location_task {
14283                Some(task) => Some({
14284                    let target_buffer_handle = task.await.context("open local buffer")?;
14285                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14286                        let target_start = target_buffer
14287                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14288                        let target_end = target_buffer
14289                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14290                        target_buffer.anchor_after(target_start)
14291                            ..target_buffer.anchor_before(target_end)
14292                    })?;
14293                    Location {
14294                        buffer: target_buffer_handle,
14295                        range,
14296                    }
14297                }),
14298                None => None,
14299            };
14300            Ok(location)
14301        })
14302    }
14303
14304    pub fn find_all_references(
14305        &mut self,
14306        _: &FindAllReferences,
14307        window: &mut Window,
14308        cx: &mut Context<Self>,
14309    ) -> Option<Task<Result<Navigated>>> {
14310        let selection = self.selections.newest::<usize>(cx);
14311        let multi_buffer = self.buffer.read(cx);
14312        let head = selection.head();
14313
14314        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14315        let head_anchor = multi_buffer_snapshot.anchor_at(
14316            head,
14317            if head < selection.tail() {
14318                Bias::Right
14319            } else {
14320                Bias::Left
14321            },
14322        );
14323
14324        match self
14325            .find_all_references_task_sources
14326            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14327        {
14328            Ok(_) => {
14329                log::info!(
14330                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14331                );
14332                return None;
14333            }
14334            Err(i) => {
14335                self.find_all_references_task_sources.insert(i, head_anchor);
14336            }
14337        }
14338
14339        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14340        let workspace = self.workspace()?;
14341        let project = workspace.read(cx).project().clone();
14342        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14343        Some(cx.spawn_in(window, async move |editor, cx| {
14344            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14345                if let Ok(i) = editor
14346                    .find_all_references_task_sources
14347                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14348                {
14349                    editor.find_all_references_task_sources.remove(i);
14350                }
14351            });
14352
14353            let locations = references.await?;
14354            if locations.is_empty() {
14355                return anyhow::Ok(Navigated::No);
14356            }
14357
14358            workspace.update_in(cx, |workspace, window, cx| {
14359                let title = locations
14360                    .first()
14361                    .as_ref()
14362                    .map(|location| {
14363                        let buffer = location.buffer.read(cx);
14364                        format!(
14365                            "References to `{}`",
14366                            buffer
14367                                .text_for_range(location.range.clone())
14368                                .collect::<String>()
14369                        )
14370                    })
14371                    .unwrap();
14372                Self::open_locations_in_multibuffer(
14373                    workspace,
14374                    locations,
14375                    title,
14376                    false,
14377                    MultibufferSelectionMode::First,
14378                    window,
14379                    cx,
14380                );
14381                Navigated::Yes
14382            })
14383        }))
14384    }
14385
14386    /// Opens a multibuffer with the given project locations in it
14387    pub fn open_locations_in_multibuffer(
14388        workspace: &mut Workspace,
14389        mut locations: Vec<Location>,
14390        title: String,
14391        split: bool,
14392        multibuffer_selection_mode: MultibufferSelectionMode,
14393        window: &mut Window,
14394        cx: &mut Context<Workspace>,
14395    ) {
14396        // If there are multiple definitions, open them in a multibuffer
14397        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14398        let mut locations = locations.into_iter().peekable();
14399        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14400        let capability = workspace.project().read(cx).capability();
14401
14402        let excerpt_buffer = cx.new(|cx| {
14403            let mut multibuffer = MultiBuffer::new(capability);
14404            while let Some(location) = locations.next() {
14405                let buffer = location.buffer.read(cx);
14406                let mut ranges_for_buffer = Vec::new();
14407                let range = location.range.to_point(buffer);
14408                ranges_for_buffer.push(range.clone());
14409
14410                while let Some(next_location) = locations.peek() {
14411                    if next_location.buffer == location.buffer {
14412                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14413                        locations.next();
14414                    } else {
14415                        break;
14416                    }
14417                }
14418
14419                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14420                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14421                    PathKey::for_buffer(&location.buffer, cx),
14422                    location.buffer.clone(),
14423                    ranges_for_buffer,
14424                    DEFAULT_MULTIBUFFER_CONTEXT,
14425                    cx,
14426                );
14427                ranges.extend(new_ranges)
14428            }
14429
14430            multibuffer.with_title(title)
14431        });
14432
14433        let editor = cx.new(|cx| {
14434            Editor::for_multibuffer(
14435                excerpt_buffer,
14436                Some(workspace.project().clone()),
14437                window,
14438                cx,
14439            )
14440        });
14441        editor.update(cx, |editor, cx| {
14442            match multibuffer_selection_mode {
14443                MultibufferSelectionMode::First => {
14444                    if let Some(first_range) = ranges.first() {
14445                        editor.change_selections(None, window, cx, |selections| {
14446                            selections.clear_disjoint();
14447                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14448                        });
14449                    }
14450                    editor.highlight_background::<Self>(
14451                        &ranges,
14452                        |theme| theme.editor_highlighted_line_background,
14453                        cx,
14454                    );
14455                }
14456                MultibufferSelectionMode::All => {
14457                    editor.change_selections(None, window, cx, |selections| {
14458                        selections.clear_disjoint();
14459                        selections.select_anchor_ranges(ranges);
14460                    });
14461                }
14462            }
14463            editor.register_buffers_with_language_servers(cx);
14464        });
14465
14466        let item = Box::new(editor);
14467        let item_id = item.item_id();
14468
14469        if split {
14470            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14471        } else {
14472            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14473                let (preview_item_id, preview_item_idx) =
14474                    workspace.active_pane().update(cx, |pane, _| {
14475                        (pane.preview_item_id(), pane.preview_item_idx())
14476                    });
14477
14478                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14479
14480                if let Some(preview_item_id) = preview_item_id {
14481                    workspace.active_pane().update(cx, |pane, cx| {
14482                        pane.remove_item(preview_item_id, false, false, window, cx);
14483                    });
14484                }
14485            } else {
14486                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14487            }
14488        }
14489        workspace.active_pane().update(cx, |pane, cx| {
14490            pane.set_preview_item_id(Some(item_id), cx);
14491        });
14492    }
14493
14494    pub fn rename(
14495        &mut self,
14496        _: &Rename,
14497        window: &mut Window,
14498        cx: &mut Context<Self>,
14499    ) -> Option<Task<Result<()>>> {
14500        use language::ToOffset as _;
14501
14502        let provider = self.semantics_provider.clone()?;
14503        let selection = self.selections.newest_anchor().clone();
14504        let (cursor_buffer, cursor_buffer_position) = self
14505            .buffer
14506            .read(cx)
14507            .text_anchor_for_position(selection.head(), cx)?;
14508        let (tail_buffer, cursor_buffer_position_end) = self
14509            .buffer
14510            .read(cx)
14511            .text_anchor_for_position(selection.tail(), cx)?;
14512        if tail_buffer != cursor_buffer {
14513            return None;
14514        }
14515
14516        let snapshot = cursor_buffer.read(cx).snapshot();
14517        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14518        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14519        let prepare_rename = provider
14520            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14521            .unwrap_or_else(|| Task::ready(Ok(None)));
14522        drop(snapshot);
14523
14524        Some(cx.spawn_in(window, async move |this, cx| {
14525            let rename_range = if let Some(range) = prepare_rename.await? {
14526                Some(range)
14527            } else {
14528                this.update(cx, |this, cx| {
14529                    let buffer = this.buffer.read(cx).snapshot(cx);
14530                    let mut buffer_highlights = this
14531                        .document_highlights_for_position(selection.head(), &buffer)
14532                        .filter(|highlight| {
14533                            highlight.start.excerpt_id == selection.head().excerpt_id
14534                                && highlight.end.excerpt_id == selection.head().excerpt_id
14535                        });
14536                    buffer_highlights
14537                        .next()
14538                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14539                })?
14540            };
14541            if let Some(rename_range) = rename_range {
14542                this.update_in(cx, |this, window, cx| {
14543                    let snapshot = cursor_buffer.read(cx).snapshot();
14544                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14545                    let cursor_offset_in_rename_range =
14546                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14547                    let cursor_offset_in_rename_range_end =
14548                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14549
14550                    this.take_rename(false, window, cx);
14551                    let buffer = this.buffer.read(cx).read(cx);
14552                    let cursor_offset = selection.head().to_offset(&buffer);
14553                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14554                    let rename_end = rename_start + rename_buffer_range.len();
14555                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14556                    let mut old_highlight_id = None;
14557                    let old_name: Arc<str> = buffer
14558                        .chunks(rename_start..rename_end, true)
14559                        .map(|chunk| {
14560                            if old_highlight_id.is_none() {
14561                                old_highlight_id = chunk.syntax_highlight_id;
14562                            }
14563                            chunk.text
14564                        })
14565                        .collect::<String>()
14566                        .into();
14567
14568                    drop(buffer);
14569
14570                    // Position the selection in the rename editor so that it matches the current selection.
14571                    this.show_local_selections = false;
14572                    let rename_editor = cx.new(|cx| {
14573                        let mut editor = Editor::single_line(window, cx);
14574                        editor.buffer.update(cx, |buffer, cx| {
14575                            buffer.edit([(0..0, old_name.clone())], None, cx)
14576                        });
14577                        let rename_selection_range = match cursor_offset_in_rename_range
14578                            .cmp(&cursor_offset_in_rename_range_end)
14579                        {
14580                            Ordering::Equal => {
14581                                editor.select_all(&SelectAll, window, cx);
14582                                return editor;
14583                            }
14584                            Ordering::Less => {
14585                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14586                            }
14587                            Ordering::Greater => {
14588                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14589                            }
14590                        };
14591                        if rename_selection_range.end > old_name.len() {
14592                            editor.select_all(&SelectAll, window, cx);
14593                        } else {
14594                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14595                                s.select_ranges([rename_selection_range]);
14596                            });
14597                        }
14598                        editor
14599                    });
14600                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14601                        if e == &EditorEvent::Focused {
14602                            cx.emit(EditorEvent::FocusedIn)
14603                        }
14604                    })
14605                    .detach();
14606
14607                    let write_highlights =
14608                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14609                    let read_highlights =
14610                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14611                    let ranges = write_highlights
14612                        .iter()
14613                        .flat_map(|(_, ranges)| ranges.iter())
14614                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14615                        .cloned()
14616                        .collect();
14617
14618                    this.highlight_text::<Rename>(
14619                        ranges,
14620                        HighlightStyle {
14621                            fade_out: Some(0.6),
14622                            ..Default::default()
14623                        },
14624                        cx,
14625                    );
14626                    let rename_focus_handle = rename_editor.focus_handle(cx);
14627                    window.focus(&rename_focus_handle);
14628                    let block_id = this.insert_blocks(
14629                        [BlockProperties {
14630                            style: BlockStyle::Flex,
14631                            placement: BlockPlacement::Below(range.start),
14632                            height: Some(1),
14633                            render: Arc::new({
14634                                let rename_editor = rename_editor.clone();
14635                                move |cx: &mut BlockContext| {
14636                                    let mut text_style = cx.editor_style.text.clone();
14637                                    if let Some(highlight_style) = old_highlight_id
14638                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14639                                    {
14640                                        text_style = text_style.highlight(highlight_style);
14641                                    }
14642                                    div()
14643                                        .block_mouse_down()
14644                                        .pl(cx.anchor_x)
14645                                        .child(EditorElement::new(
14646                                            &rename_editor,
14647                                            EditorStyle {
14648                                                background: cx.theme().system().transparent,
14649                                                local_player: cx.editor_style.local_player,
14650                                                text: text_style,
14651                                                scrollbar_width: cx.editor_style.scrollbar_width,
14652                                                syntax: cx.editor_style.syntax.clone(),
14653                                                status: cx.editor_style.status.clone(),
14654                                                inlay_hints_style: HighlightStyle {
14655                                                    font_weight: Some(FontWeight::BOLD),
14656                                                    ..make_inlay_hints_style(cx.app)
14657                                                },
14658                                                inline_completion_styles: make_suggestion_styles(
14659                                                    cx.app,
14660                                                ),
14661                                                ..EditorStyle::default()
14662                                            },
14663                                        ))
14664                                        .into_any_element()
14665                                }
14666                            }),
14667                            priority: 0,
14668                            render_in_minimap: true,
14669                        }],
14670                        Some(Autoscroll::fit()),
14671                        cx,
14672                    )[0];
14673                    this.pending_rename = Some(RenameState {
14674                        range,
14675                        old_name,
14676                        editor: rename_editor,
14677                        block_id,
14678                    });
14679                })?;
14680            }
14681
14682            Ok(())
14683        }))
14684    }
14685
14686    pub fn confirm_rename(
14687        &mut self,
14688        _: &ConfirmRename,
14689        window: &mut Window,
14690        cx: &mut Context<Self>,
14691    ) -> Option<Task<Result<()>>> {
14692        let rename = self.take_rename(false, window, cx)?;
14693        let workspace = self.workspace()?.downgrade();
14694        let (buffer, start) = self
14695            .buffer
14696            .read(cx)
14697            .text_anchor_for_position(rename.range.start, cx)?;
14698        let (end_buffer, _) = self
14699            .buffer
14700            .read(cx)
14701            .text_anchor_for_position(rename.range.end, cx)?;
14702        if buffer != end_buffer {
14703            return None;
14704        }
14705
14706        let old_name = rename.old_name;
14707        let new_name = rename.editor.read(cx).text(cx);
14708
14709        let rename = self.semantics_provider.as_ref()?.perform_rename(
14710            &buffer,
14711            start,
14712            new_name.clone(),
14713            cx,
14714        )?;
14715
14716        Some(cx.spawn_in(window, async move |editor, cx| {
14717            let project_transaction = rename.await?;
14718            Self::open_project_transaction(
14719                &editor,
14720                workspace,
14721                project_transaction,
14722                format!("Rename: {}{}", old_name, new_name),
14723                cx,
14724            )
14725            .await?;
14726
14727            editor.update(cx, |editor, cx| {
14728                editor.refresh_document_highlights(cx);
14729            })?;
14730            Ok(())
14731        }))
14732    }
14733
14734    fn take_rename(
14735        &mut self,
14736        moving_cursor: bool,
14737        window: &mut Window,
14738        cx: &mut Context<Self>,
14739    ) -> Option<RenameState> {
14740        let rename = self.pending_rename.take()?;
14741        if rename.editor.focus_handle(cx).is_focused(window) {
14742            window.focus(&self.focus_handle);
14743        }
14744
14745        self.remove_blocks(
14746            [rename.block_id].into_iter().collect(),
14747            Some(Autoscroll::fit()),
14748            cx,
14749        );
14750        self.clear_highlights::<Rename>(cx);
14751        self.show_local_selections = true;
14752
14753        if moving_cursor {
14754            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14755                editor.selections.newest::<usize>(cx).head()
14756            });
14757
14758            // Update the selection to match the position of the selection inside
14759            // the rename editor.
14760            let snapshot = self.buffer.read(cx).read(cx);
14761            let rename_range = rename.range.to_offset(&snapshot);
14762            let cursor_in_editor = snapshot
14763                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14764                .min(rename_range.end);
14765            drop(snapshot);
14766
14767            self.change_selections(None, window, cx, |s| {
14768                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14769            });
14770        } else {
14771            self.refresh_document_highlights(cx);
14772        }
14773
14774        Some(rename)
14775    }
14776
14777    pub fn pending_rename(&self) -> Option<&RenameState> {
14778        self.pending_rename.as_ref()
14779    }
14780
14781    fn format(
14782        &mut self,
14783        _: &Format,
14784        window: &mut Window,
14785        cx: &mut Context<Self>,
14786    ) -> Option<Task<Result<()>>> {
14787        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14788
14789        let project = match &self.project {
14790            Some(project) => project.clone(),
14791            None => return None,
14792        };
14793
14794        Some(self.perform_format(
14795            project,
14796            FormatTrigger::Manual,
14797            FormatTarget::Buffers,
14798            window,
14799            cx,
14800        ))
14801    }
14802
14803    fn format_selections(
14804        &mut self,
14805        _: &FormatSelections,
14806        window: &mut Window,
14807        cx: &mut Context<Self>,
14808    ) -> Option<Task<Result<()>>> {
14809        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14810
14811        let project = match &self.project {
14812            Some(project) => project.clone(),
14813            None => return None,
14814        };
14815
14816        let ranges = self
14817            .selections
14818            .all_adjusted(cx)
14819            .into_iter()
14820            .map(|selection| selection.range())
14821            .collect_vec();
14822
14823        Some(self.perform_format(
14824            project,
14825            FormatTrigger::Manual,
14826            FormatTarget::Ranges(ranges),
14827            window,
14828            cx,
14829        ))
14830    }
14831
14832    fn perform_format(
14833        &mut self,
14834        project: Entity<Project>,
14835        trigger: FormatTrigger,
14836        target: FormatTarget,
14837        window: &mut Window,
14838        cx: &mut Context<Self>,
14839    ) -> Task<Result<()>> {
14840        let buffer = self.buffer.clone();
14841        let (buffers, target) = match target {
14842            FormatTarget::Buffers => {
14843                let mut buffers = buffer.read(cx).all_buffers();
14844                if trigger == FormatTrigger::Save {
14845                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14846                }
14847                (buffers, LspFormatTarget::Buffers)
14848            }
14849            FormatTarget::Ranges(selection_ranges) => {
14850                let multi_buffer = buffer.read(cx);
14851                let snapshot = multi_buffer.read(cx);
14852                let mut buffers = HashSet::default();
14853                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14854                    BTreeMap::new();
14855                for selection_range in selection_ranges {
14856                    for (buffer, buffer_range, _) in
14857                        snapshot.range_to_buffer_ranges(selection_range)
14858                    {
14859                        let buffer_id = buffer.remote_id();
14860                        let start = buffer.anchor_before(buffer_range.start);
14861                        let end = buffer.anchor_after(buffer_range.end);
14862                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14863                        buffer_id_to_ranges
14864                            .entry(buffer_id)
14865                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14866                            .or_insert_with(|| vec![start..end]);
14867                    }
14868                }
14869                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14870            }
14871        };
14872
14873        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14874        let selections_prev = transaction_id_prev
14875            .and_then(|transaction_id_prev| {
14876                // default to selections as they were after the last edit, if we have them,
14877                // instead of how they are now.
14878                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14879                // will take you back to where you made the last edit, instead of staying where you scrolled
14880                self.selection_history
14881                    .transaction(transaction_id_prev)
14882                    .map(|t| t.0.clone())
14883            })
14884            .unwrap_or_else(|| {
14885                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14886                self.selections.disjoint_anchors()
14887            });
14888
14889        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14890        let format = project.update(cx, |project, cx| {
14891            project.format(buffers, target, true, trigger, cx)
14892        });
14893
14894        cx.spawn_in(window, async move |editor, cx| {
14895            let transaction = futures::select_biased! {
14896                transaction = format.log_err().fuse() => transaction,
14897                () = timeout => {
14898                    log::warn!("timed out waiting for formatting");
14899                    None
14900                }
14901            };
14902
14903            buffer
14904                .update(cx, |buffer, cx| {
14905                    if let Some(transaction) = transaction {
14906                        if !buffer.is_singleton() {
14907                            buffer.push_transaction(&transaction.0, cx);
14908                        }
14909                    }
14910                    cx.notify();
14911                })
14912                .ok();
14913
14914            if let Some(transaction_id_now) =
14915                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14916            {
14917                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14918                if has_new_transaction {
14919                    _ = editor.update(cx, |editor, _| {
14920                        editor
14921                            .selection_history
14922                            .insert_transaction(transaction_id_now, selections_prev);
14923                    });
14924                }
14925            }
14926
14927            Ok(())
14928        })
14929    }
14930
14931    fn organize_imports(
14932        &mut self,
14933        _: &OrganizeImports,
14934        window: &mut Window,
14935        cx: &mut Context<Self>,
14936    ) -> Option<Task<Result<()>>> {
14937        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14938        let project = match &self.project {
14939            Some(project) => project.clone(),
14940            None => return None,
14941        };
14942        Some(self.perform_code_action_kind(
14943            project,
14944            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14945            window,
14946            cx,
14947        ))
14948    }
14949
14950    fn perform_code_action_kind(
14951        &mut self,
14952        project: Entity<Project>,
14953        kind: CodeActionKind,
14954        window: &mut Window,
14955        cx: &mut Context<Self>,
14956    ) -> Task<Result<()>> {
14957        let buffer = self.buffer.clone();
14958        let buffers = buffer.read(cx).all_buffers();
14959        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14960        let apply_action = project.update(cx, |project, cx| {
14961            project.apply_code_action_kind(buffers, kind, true, cx)
14962        });
14963        cx.spawn_in(window, async move |_, cx| {
14964            let transaction = futures::select_biased! {
14965                () = timeout => {
14966                    log::warn!("timed out waiting for executing code action");
14967                    None
14968                }
14969                transaction = apply_action.log_err().fuse() => transaction,
14970            };
14971            buffer
14972                .update(cx, |buffer, cx| {
14973                    // check if we need this
14974                    if let Some(transaction) = transaction {
14975                        if !buffer.is_singleton() {
14976                            buffer.push_transaction(&transaction.0, cx);
14977                        }
14978                    }
14979                    cx.notify();
14980                })
14981                .ok();
14982            Ok(())
14983        })
14984    }
14985
14986    fn restart_language_server(
14987        &mut self,
14988        _: &RestartLanguageServer,
14989        _: &mut Window,
14990        cx: &mut Context<Self>,
14991    ) {
14992        if let Some(project) = self.project.clone() {
14993            self.buffer.update(cx, |multi_buffer, cx| {
14994                project.update(cx, |project, cx| {
14995                    project.restart_language_servers_for_buffers(
14996                        multi_buffer.all_buffers().into_iter().collect(),
14997                        cx,
14998                    );
14999                });
15000            })
15001        }
15002    }
15003
15004    fn stop_language_server(
15005        &mut self,
15006        _: &StopLanguageServer,
15007        _: &mut Window,
15008        cx: &mut Context<Self>,
15009    ) {
15010        if let Some(project) = self.project.clone() {
15011            self.buffer.update(cx, |multi_buffer, cx| {
15012                project.update(cx, |project, cx| {
15013                    project.stop_language_servers_for_buffers(
15014                        multi_buffer.all_buffers().into_iter().collect(),
15015                        cx,
15016                    );
15017                    cx.emit(project::Event::RefreshInlayHints);
15018                });
15019            });
15020        }
15021    }
15022
15023    fn cancel_language_server_work(
15024        workspace: &mut Workspace,
15025        _: &actions::CancelLanguageServerWork,
15026        _: &mut Window,
15027        cx: &mut Context<Workspace>,
15028    ) {
15029        let project = workspace.project();
15030        let buffers = workspace
15031            .active_item(cx)
15032            .and_then(|item| item.act_as::<Editor>(cx))
15033            .map_or(HashSet::default(), |editor| {
15034                editor.read(cx).buffer.read(cx).all_buffers()
15035            });
15036        project.update(cx, |project, cx| {
15037            project.cancel_language_server_work_for_buffers(buffers, cx);
15038        });
15039    }
15040
15041    fn show_character_palette(
15042        &mut self,
15043        _: &ShowCharacterPalette,
15044        window: &mut Window,
15045        _: &mut Context<Self>,
15046    ) {
15047        window.show_character_palette();
15048    }
15049
15050    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
15051        if self.mode.is_minimap() {
15052            return;
15053        }
15054
15055        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
15056            let buffer = self.buffer.read(cx).snapshot(cx);
15057            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
15058            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
15059            let is_valid = buffer
15060                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
15061                .any(|entry| {
15062                    entry.diagnostic.is_primary
15063                        && !entry.range.is_empty()
15064                        && entry.range.start == primary_range_start
15065                        && entry.diagnostic.message == active_diagnostics.active_message
15066                });
15067
15068            if !is_valid {
15069                self.dismiss_diagnostics(cx);
15070            }
15071        }
15072    }
15073
15074    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15075        match &self.active_diagnostics {
15076            ActiveDiagnostic::Group(group) => Some(group),
15077            _ => None,
15078        }
15079    }
15080
15081    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15082        self.dismiss_diagnostics(cx);
15083        self.active_diagnostics = ActiveDiagnostic::All;
15084    }
15085
15086    fn activate_diagnostics(
15087        &mut self,
15088        buffer_id: BufferId,
15089        diagnostic: DiagnosticEntry<usize>,
15090        window: &mut Window,
15091        cx: &mut Context<Self>,
15092    ) {
15093        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15094            return;
15095        }
15096        self.dismiss_diagnostics(cx);
15097        let snapshot = self.snapshot(window, cx);
15098        let buffer = self.buffer.read(cx).snapshot(cx);
15099        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15100            return;
15101        };
15102
15103        let diagnostic_group = buffer
15104            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15105            .collect::<Vec<_>>();
15106
15107        let blocks =
15108            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15109
15110        let blocks = self.display_map.update(cx, |display_map, cx| {
15111            display_map.insert_blocks(blocks, cx).into_iter().collect()
15112        });
15113        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15114            active_range: buffer.anchor_before(diagnostic.range.start)
15115                ..buffer.anchor_after(diagnostic.range.end),
15116            active_message: diagnostic.diagnostic.message.clone(),
15117            group_id: diagnostic.diagnostic.group_id,
15118            blocks,
15119        });
15120        cx.notify();
15121    }
15122
15123    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15124        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15125            return;
15126        };
15127
15128        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15129        if let ActiveDiagnostic::Group(group) = prev {
15130            self.display_map.update(cx, |display_map, cx| {
15131                display_map.remove_blocks(group.blocks, cx);
15132            });
15133            cx.notify();
15134        }
15135    }
15136
15137    /// Disable inline diagnostics rendering for this editor.
15138    pub fn disable_inline_diagnostics(&mut self) {
15139        self.inline_diagnostics_enabled = false;
15140        self.inline_diagnostics_update = Task::ready(());
15141        self.inline_diagnostics.clear();
15142    }
15143
15144    pub fn diagnostics_enabled(&self) -> bool {
15145        self.mode.is_full()
15146    }
15147
15148    pub fn inline_diagnostics_enabled(&self) -> bool {
15149        self.diagnostics_enabled() && self.inline_diagnostics_enabled
15150    }
15151
15152    pub fn show_inline_diagnostics(&self) -> bool {
15153        self.show_inline_diagnostics
15154    }
15155
15156    pub fn toggle_inline_diagnostics(
15157        &mut self,
15158        _: &ToggleInlineDiagnostics,
15159        window: &mut Window,
15160        cx: &mut Context<Editor>,
15161    ) {
15162        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15163        self.refresh_inline_diagnostics(false, window, cx);
15164    }
15165
15166    pub fn set_max_diagnostics_severity(&mut self, severity: DiagnosticSeverity, cx: &mut App) {
15167        self.diagnostics_max_severity = severity;
15168        self.display_map.update(cx, |display_map, _| {
15169            display_map.diagnostics_max_severity = self.diagnostics_max_severity;
15170        });
15171    }
15172
15173    pub fn toggle_diagnostics(
15174        &mut self,
15175        _: &ToggleDiagnostics,
15176        window: &mut Window,
15177        cx: &mut Context<Editor>,
15178    ) {
15179        if !self.diagnostics_enabled() {
15180            return;
15181        }
15182
15183        let new_severity = if self.diagnostics_max_severity == DiagnosticSeverity::Off {
15184            EditorSettings::get_global(cx)
15185                .diagnostics_max_severity
15186                .filter(|severity| severity != &DiagnosticSeverity::Off)
15187                .unwrap_or(DiagnosticSeverity::Hint)
15188        } else {
15189            DiagnosticSeverity::Off
15190        };
15191        self.set_max_diagnostics_severity(new_severity, cx);
15192        if self.diagnostics_max_severity == DiagnosticSeverity::Off {
15193            self.active_diagnostics = ActiveDiagnostic::None;
15194            self.inline_diagnostics_update = Task::ready(());
15195            self.inline_diagnostics.clear();
15196        } else {
15197            self.refresh_inline_diagnostics(false, window, cx);
15198        }
15199
15200        cx.notify();
15201    }
15202
15203    pub fn toggle_minimap(
15204        &mut self,
15205        _: &ToggleMinimap,
15206        window: &mut Window,
15207        cx: &mut Context<Editor>,
15208    ) {
15209        if self.supports_minimap(cx) {
15210            self.set_minimap_visibility(self.minimap_visibility.toggle_visibility(), window, cx);
15211        }
15212    }
15213
15214    fn refresh_inline_diagnostics(
15215        &mut self,
15216        debounce: bool,
15217        window: &mut Window,
15218        cx: &mut Context<Self>,
15219    ) {
15220        let max_severity = ProjectSettings::get_global(cx)
15221            .diagnostics
15222            .inline
15223            .max_severity
15224            .unwrap_or(self.diagnostics_max_severity);
15225
15226        if self.mode.is_minimap()
15227            || !self.inline_diagnostics_enabled()
15228            || !self.show_inline_diagnostics
15229            || max_severity == DiagnosticSeverity::Off
15230        {
15231            self.inline_diagnostics_update = Task::ready(());
15232            self.inline_diagnostics.clear();
15233            return;
15234        }
15235
15236        let debounce_ms = ProjectSettings::get_global(cx)
15237            .diagnostics
15238            .inline
15239            .update_debounce_ms;
15240        let debounce = if debounce && debounce_ms > 0 {
15241            Some(Duration::from_millis(debounce_ms))
15242        } else {
15243            None
15244        };
15245        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15246            let editor = editor.upgrade().unwrap();
15247
15248            if let Some(debounce) = debounce {
15249                cx.background_executor().timer(debounce).await;
15250            }
15251            let Some(snapshot) = editor
15252                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15253                .ok()
15254            else {
15255                return;
15256            };
15257
15258            let new_inline_diagnostics = cx
15259                .background_spawn(async move {
15260                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15261                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15262                        let message = diagnostic_entry
15263                            .diagnostic
15264                            .message
15265                            .split_once('\n')
15266                            .map(|(line, _)| line)
15267                            .map(SharedString::new)
15268                            .unwrap_or_else(|| {
15269                                SharedString::from(diagnostic_entry.diagnostic.message)
15270                            });
15271                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15272                        let (Ok(i) | Err(i)) = inline_diagnostics
15273                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15274                        inline_diagnostics.insert(
15275                            i,
15276                            (
15277                                start_anchor,
15278                                InlineDiagnostic {
15279                                    message,
15280                                    group_id: diagnostic_entry.diagnostic.group_id,
15281                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15282                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15283                                    severity: diagnostic_entry.diagnostic.severity,
15284                                },
15285                            ),
15286                        );
15287                    }
15288                    inline_diagnostics
15289                })
15290                .await;
15291
15292            editor
15293                .update(cx, |editor, cx| {
15294                    editor.inline_diagnostics = new_inline_diagnostics;
15295                    cx.notify();
15296                })
15297                .ok();
15298        });
15299    }
15300
15301    pub fn set_selections_from_remote(
15302        &mut self,
15303        selections: Vec<Selection<Anchor>>,
15304        pending_selection: Option<Selection<Anchor>>,
15305        window: &mut Window,
15306        cx: &mut Context<Self>,
15307    ) {
15308        let old_cursor_position = self.selections.newest_anchor().head();
15309        self.selections.change_with(cx, |s| {
15310            s.select_anchors(selections);
15311            if let Some(pending_selection) = pending_selection {
15312                s.set_pending(pending_selection, SelectMode::Character);
15313            } else {
15314                s.clear_pending();
15315            }
15316        });
15317        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15318    }
15319
15320    fn push_to_selection_history(&mut self) {
15321        self.selection_history.push(SelectionHistoryEntry {
15322            selections: self.selections.disjoint_anchors(),
15323            select_next_state: self.select_next_state.clone(),
15324            select_prev_state: self.select_prev_state.clone(),
15325            add_selections_state: self.add_selections_state.clone(),
15326        });
15327    }
15328
15329    pub fn transact(
15330        &mut self,
15331        window: &mut Window,
15332        cx: &mut Context<Self>,
15333        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15334    ) -> Option<TransactionId> {
15335        self.start_transaction_at(Instant::now(), window, cx);
15336        update(self, window, cx);
15337        self.end_transaction_at(Instant::now(), cx)
15338    }
15339
15340    pub fn start_transaction_at(
15341        &mut self,
15342        now: Instant,
15343        window: &mut Window,
15344        cx: &mut Context<Self>,
15345    ) {
15346        self.end_selection(window, cx);
15347        if let Some(tx_id) = self
15348            .buffer
15349            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15350        {
15351            self.selection_history
15352                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15353            cx.emit(EditorEvent::TransactionBegun {
15354                transaction_id: tx_id,
15355            })
15356        }
15357    }
15358
15359    pub fn end_transaction_at(
15360        &mut self,
15361        now: Instant,
15362        cx: &mut Context<Self>,
15363    ) -> Option<TransactionId> {
15364        if let Some(transaction_id) = self
15365            .buffer
15366            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15367        {
15368            if let Some((_, end_selections)) =
15369                self.selection_history.transaction_mut(transaction_id)
15370            {
15371                *end_selections = Some(self.selections.disjoint_anchors());
15372            } else {
15373                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15374            }
15375
15376            cx.emit(EditorEvent::Edited { transaction_id });
15377            Some(transaction_id)
15378        } else {
15379            None
15380        }
15381    }
15382
15383    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15384        if self.selection_mark_mode {
15385            self.change_selections(None, window, cx, |s| {
15386                s.move_with(|_, sel| {
15387                    sel.collapse_to(sel.head(), SelectionGoal::None);
15388                });
15389            })
15390        }
15391        self.selection_mark_mode = true;
15392        cx.notify();
15393    }
15394
15395    pub fn swap_selection_ends(
15396        &mut self,
15397        _: &actions::SwapSelectionEnds,
15398        window: &mut Window,
15399        cx: &mut Context<Self>,
15400    ) {
15401        self.change_selections(None, window, cx, |s| {
15402            s.move_with(|_, sel| {
15403                if sel.start != sel.end {
15404                    sel.reversed = !sel.reversed
15405                }
15406            });
15407        });
15408        self.request_autoscroll(Autoscroll::newest(), cx);
15409        cx.notify();
15410    }
15411
15412    pub fn toggle_fold(
15413        &mut self,
15414        _: &actions::ToggleFold,
15415        window: &mut Window,
15416        cx: &mut Context<Self>,
15417    ) {
15418        if self.is_singleton(cx) {
15419            let selection = self.selections.newest::<Point>(cx);
15420
15421            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15422            let range = if selection.is_empty() {
15423                let point = selection.head().to_display_point(&display_map);
15424                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15425                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15426                    .to_point(&display_map);
15427                start..end
15428            } else {
15429                selection.range()
15430            };
15431            if display_map.folds_in_range(range).next().is_some() {
15432                self.unfold_lines(&Default::default(), window, cx)
15433            } else {
15434                self.fold(&Default::default(), window, cx)
15435            }
15436        } else {
15437            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15438            let buffer_ids: HashSet<_> = self
15439                .selections
15440                .disjoint_anchor_ranges()
15441                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15442                .collect();
15443
15444            let should_unfold = buffer_ids
15445                .iter()
15446                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15447
15448            for buffer_id in buffer_ids {
15449                if should_unfold {
15450                    self.unfold_buffer(buffer_id, cx);
15451                } else {
15452                    self.fold_buffer(buffer_id, cx);
15453                }
15454            }
15455        }
15456    }
15457
15458    pub fn toggle_fold_recursive(
15459        &mut self,
15460        _: &actions::ToggleFoldRecursive,
15461        window: &mut Window,
15462        cx: &mut Context<Self>,
15463    ) {
15464        let selection = self.selections.newest::<Point>(cx);
15465
15466        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15467        let range = if selection.is_empty() {
15468            let point = selection.head().to_display_point(&display_map);
15469            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15470            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15471                .to_point(&display_map);
15472            start..end
15473        } else {
15474            selection.range()
15475        };
15476        if display_map.folds_in_range(range).next().is_some() {
15477            self.unfold_recursive(&Default::default(), window, cx)
15478        } else {
15479            self.fold_recursive(&Default::default(), window, cx)
15480        }
15481    }
15482
15483    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15484        if self.is_singleton(cx) {
15485            let mut to_fold = Vec::new();
15486            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15487            let selections = self.selections.all_adjusted(cx);
15488
15489            for selection in selections {
15490                let range = selection.range().sorted();
15491                let buffer_start_row = range.start.row;
15492
15493                if range.start.row != range.end.row {
15494                    let mut found = false;
15495                    let mut row = range.start.row;
15496                    while row <= range.end.row {
15497                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15498                        {
15499                            found = true;
15500                            row = crease.range().end.row + 1;
15501                            to_fold.push(crease);
15502                        } else {
15503                            row += 1
15504                        }
15505                    }
15506                    if found {
15507                        continue;
15508                    }
15509                }
15510
15511                for row in (0..=range.start.row).rev() {
15512                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15513                        if crease.range().end.row >= buffer_start_row {
15514                            to_fold.push(crease);
15515                            if row <= range.start.row {
15516                                break;
15517                            }
15518                        }
15519                    }
15520                }
15521            }
15522
15523            self.fold_creases(to_fold, true, window, cx);
15524        } else {
15525            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15526            let buffer_ids = self
15527                .selections
15528                .disjoint_anchor_ranges()
15529                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15530                .collect::<HashSet<_>>();
15531            for buffer_id in buffer_ids {
15532                self.fold_buffer(buffer_id, cx);
15533            }
15534        }
15535    }
15536
15537    fn fold_at_level(
15538        &mut self,
15539        fold_at: &FoldAtLevel,
15540        window: &mut Window,
15541        cx: &mut Context<Self>,
15542    ) {
15543        if !self.buffer.read(cx).is_singleton() {
15544            return;
15545        }
15546
15547        let fold_at_level = fold_at.0;
15548        let snapshot = self.buffer.read(cx).snapshot(cx);
15549        let mut to_fold = Vec::new();
15550        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15551
15552        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15553            while start_row < end_row {
15554                match self
15555                    .snapshot(window, cx)
15556                    .crease_for_buffer_row(MultiBufferRow(start_row))
15557                {
15558                    Some(crease) => {
15559                        let nested_start_row = crease.range().start.row + 1;
15560                        let nested_end_row = crease.range().end.row;
15561
15562                        if current_level < fold_at_level {
15563                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15564                        } else if current_level == fold_at_level {
15565                            to_fold.push(crease);
15566                        }
15567
15568                        start_row = nested_end_row + 1;
15569                    }
15570                    None => start_row += 1,
15571                }
15572            }
15573        }
15574
15575        self.fold_creases(to_fold, true, window, cx);
15576    }
15577
15578    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15579        if self.buffer.read(cx).is_singleton() {
15580            let mut fold_ranges = Vec::new();
15581            let snapshot = self.buffer.read(cx).snapshot(cx);
15582
15583            for row in 0..snapshot.max_row().0 {
15584                if let Some(foldable_range) = self
15585                    .snapshot(window, cx)
15586                    .crease_for_buffer_row(MultiBufferRow(row))
15587                {
15588                    fold_ranges.push(foldable_range);
15589                }
15590            }
15591
15592            self.fold_creases(fold_ranges, true, window, cx);
15593        } else {
15594            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15595                editor
15596                    .update_in(cx, |editor, _, cx| {
15597                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15598                            editor.fold_buffer(buffer_id, cx);
15599                        }
15600                    })
15601                    .ok();
15602            });
15603        }
15604    }
15605
15606    pub fn fold_function_bodies(
15607        &mut self,
15608        _: &actions::FoldFunctionBodies,
15609        window: &mut Window,
15610        cx: &mut Context<Self>,
15611    ) {
15612        let snapshot = self.buffer.read(cx).snapshot(cx);
15613
15614        let ranges = snapshot
15615            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15616            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15617            .collect::<Vec<_>>();
15618
15619        let creases = ranges
15620            .into_iter()
15621            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15622            .collect();
15623
15624        self.fold_creases(creases, true, window, cx);
15625    }
15626
15627    pub fn fold_recursive(
15628        &mut self,
15629        _: &actions::FoldRecursive,
15630        window: &mut Window,
15631        cx: &mut Context<Self>,
15632    ) {
15633        let mut to_fold = Vec::new();
15634        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15635        let selections = self.selections.all_adjusted(cx);
15636
15637        for selection in selections {
15638            let range = selection.range().sorted();
15639            let buffer_start_row = range.start.row;
15640
15641            if range.start.row != range.end.row {
15642                let mut found = false;
15643                for row in range.start.row..=range.end.row {
15644                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15645                        found = true;
15646                        to_fold.push(crease);
15647                    }
15648                }
15649                if found {
15650                    continue;
15651                }
15652            }
15653
15654            for row in (0..=range.start.row).rev() {
15655                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15656                    if crease.range().end.row >= buffer_start_row {
15657                        to_fold.push(crease);
15658                    } else {
15659                        break;
15660                    }
15661                }
15662            }
15663        }
15664
15665        self.fold_creases(to_fold, true, window, cx);
15666    }
15667
15668    pub fn fold_at(
15669        &mut self,
15670        buffer_row: MultiBufferRow,
15671        window: &mut Window,
15672        cx: &mut Context<Self>,
15673    ) {
15674        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15675
15676        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15677            let autoscroll = self
15678                .selections
15679                .all::<Point>(cx)
15680                .iter()
15681                .any(|selection| crease.range().overlaps(&selection.range()));
15682
15683            self.fold_creases(vec![crease], autoscroll, window, cx);
15684        }
15685    }
15686
15687    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15688        if self.is_singleton(cx) {
15689            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15690            let buffer = &display_map.buffer_snapshot;
15691            let selections = self.selections.all::<Point>(cx);
15692            let ranges = selections
15693                .iter()
15694                .map(|s| {
15695                    let range = s.display_range(&display_map).sorted();
15696                    let mut start = range.start.to_point(&display_map);
15697                    let mut end = range.end.to_point(&display_map);
15698                    start.column = 0;
15699                    end.column = buffer.line_len(MultiBufferRow(end.row));
15700                    start..end
15701                })
15702                .collect::<Vec<_>>();
15703
15704            self.unfold_ranges(&ranges, true, true, cx);
15705        } else {
15706            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15707            let buffer_ids = self
15708                .selections
15709                .disjoint_anchor_ranges()
15710                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15711                .collect::<HashSet<_>>();
15712            for buffer_id in buffer_ids {
15713                self.unfold_buffer(buffer_id, cx);
15714            }
15715        }
15716    }
15717
15718    pub fn unfold_recursive(
15719        &mut self,
15720        _: &UnfoldRecursive,
15721        _window: &mut Window,
15722        cx: &mut Context<Self>,
15723    ) {
15724        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15725        let selections = self.selections.all::<Point>(cx);
15726        let ranges = selections
15727            .iter()
15728            .map(|s| {
15729                let mut range = s.display_range(&display_map).sorted();
15730                *range.start.column_mut() = 0;
15731                *range.end.column_mut() = display_map.line_len(range.end.row());
15732                let start = range.start.to_point(&display_map);
15733                let end = range.end.to_point(&display_map);
15734                start..end
15735            })
15736            .collect::<Vec<_>>();
15737
15738        self.unfold_ranges(&ranges, true, true, cx);
15739    }
15740
15741    pub fn unfold_at(
15742        &mut self,
15743        buffer_row: MultiBufferRow,
15744        _window: &mut Window,
15745        cx: &mut Context<Self>,
15746    ) {
15747        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15748
15749        let intersection_range = Point::new(buffer_row.0, 0)
15750            ..Point::new(
15751                buffer_row.0,
15752                display_map.buffer_snapshot.line_len(buffer_row),
15753            );
15754
15755        let autoscroll = self
15756            .selections
15757            .all::<Point>(cx)
15758            .iter()
15759            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15760
15761        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15762    }
15763
15764    pub fn unfold_all(
15765        &mut self,
15766        _: &actions::UnfoldAll,
15767        _window: &mut Window,
15768        cx: &mut Context<Self>,
15769    ) {
15770        if self.buffer.read(cx).is_singleton() {
15771            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15772            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15773        } else {
15774            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15775                editor
15776                    .update(cx, |editor, cx| {
15777                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15778                            editor.unfold_buffer(buffer_id, cx);
15779                        }
15780                    })
15781                    .ok();
15782            });
15783        }
15784    }
15785
15786    pub fn fold_selected_ranges(
15787        &mut self,
15788        _: &FoldSelectedRanges,
15789        window: &mut Window,
15790        cx: &mut Context<Self>,
15791    ) {
15792        let selections = self.selections.all_adjusted(cx);
15793        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15794        let ranges = selections
15795            .into_iter()
15796            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15797            .collect::<Vec<_>>();
15798        self.fold_creases(ranges, true, window, cx);
15799    }
15800
15801    pub fn fold_ranges<T: ToOffset + Clone>(
15802        &mut self,
15803        ranges: Vec<Range<T>>,
15804        auto_scroll: bool,
15805        window: &mut Window,
15806        cx: &mut Context<Self>,
15807    ) {
15808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15809        let ranges = ranges
15810            .into_iter()
15811            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15812            .collect::<Vec<_>>();
15813        self.fold_creases(ranges, auto_scroll, window, cx);
15814    }
15815
15816    pub fn fold_creases<T: ToOffset + Clone>(
15817        &mut self,
15818        creases: Vec<Crease<T>>,
15819        auto_scroll: bool,
15820        _window: &mut Window,
15821        cx: &mut Context<Self>,
15822    ) {
15823        if creases.is_empty() {
15824            return;
15825        }
15826
15827        let mut buffers_affected = HashSet::default();
15828        let multi_buffer = self.buffer().read(cx);
15829        for crease in &creases {
15830            if let Some((_, buffer, _)) =
15831                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15832            {
15833                buffers_affected.insert(buffer.read(cx).remote_id());
15834            };
15835        }
15836
15837        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15838
15839        if auto_scroll {
15840            self.request_autoscroll(Autoscroll::fit(), cx);
15841        }
15842
15843        cx.notify();
15844
15845        self.scrollbar_marker_state.dirty = true;
15846        self.folds_did_change(cx);
15847    }
15848
15849    /// Removes any folds whose ranges intersect any of the given ranges.
15850    pub fn unfold_ranges<T: ToOffset + Clone>(
15851        &mut self,
15852        ranges: &[Range<T>],
15853        inclusive: bool,
15854        auto_scroll: bool,
15855        cx: &mut Context<Self>,
15856    ) {
15857        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15858            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15859        });
15860        self.folds_did_change(cx);
15861    }
15862
15863    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15864        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15865            return;
15866        }
15867        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15868        self.display_map.update(cx, |display_map, cx| {
15869            display_map.fold_buffers([buffer_id], cx)
15870        });
15871        cx.emit(EditorEvent::BufferFoldToggled {
15872            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15873            folded: true,
15874        });
15875        cx.notify();
15876    }
15877
15878    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15879        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15880            return;
15881        }
15882        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15883        self.display_map.update(cx, |display_map, cx| {
15884            display_map.unfold_buffers([buffer_id], cx);
15885        });
15886        cx.emit(EditorEvent::BufferFoldToggled {
15887            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15888            folded: false,
15889        });
15890        cx.notify();
15891    }
15892
15893    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15894        self.display_map.read(cx).is_buffer_folded(buffer)
15895    }
15896
15897    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15898        self.display_map.read(cx).folded_buffers()
15899    }
15900
15901    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15902        self.display_map.update(cx, |display_map, cx| {
15903            display_map.disable_header_for_buffer(buffer_id, cx);
15904        });
15905        cx.notify();
15906    }
15907
15908    /// Removes any folds with the given ranges.
15909    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15910        &mut self,
15911        ranges: &[Range<T>],
15912        type_id: TypeId,
15913        auto_scroll: bool,
15914        cx: &mut Context<Self>,
15915    ) {
15916        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15917            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15918        });
15919        self.folds_did_change(cx);
15920    }
15921
15922    fn remove_folds_with<T: ToOffset + Clone>(
15923        &mut self,
15924        ranges: &[Range<T>],
15925        auto_scroll: bool,
15926        cx: &mut Context<Self>,
15927        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15928    ) {
15929        if ranges.is_empty() {
15930            return;
15931        }
15932
15933        let mut buffers_affected = HashSet::default();
15934        let multi_buffer = self.buffer().read(cx);
15935        for range in ranges {
15936            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15937                buffers_affected.insert(buffer.read(cx).remote_id());
15938            };
15939        }
15940
15941        self.display_map.update(cx, update);
15942
15943        if auto_scroll {
15944            self.request_autoscroll(Autoscroll::fit(), cx);
15945        }
15946
15947        cx.notify();
15948        self.scrollbar_marker_state.dirty = true;
15949        self.active_indent_guides_state.dirty = true;
15950    }
15951
15952    pub fn update_fold_widths(
15953        &mut self,
15954        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15955        cx: &mut Context<Self>,
15956    ) -> bool {
15957        self.display_map
15958            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15959    }
15960
15961    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15962        self.display_map.read(cx).fold_placeholder.clone()
15963    }
15964
15965    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15966        self.buffer.update(cx, |buffer, cx| {
15967            buffer.set_all_diff_hunks_expanded(cx);
15968        });
15969    }
15970
15971    pub fn expand_all_diff_hunks(
15972        &mut self,
15973        _: &ExpandAllDiffHunks,
15974        _window: &mut Window,
15975        cx: &mut Context<Self>,
15976    ) {
15977        self.buffer.update(cx, |buffer, cx| {
15978            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15979        });
15980    }
15981
15982    pub fn toggle_selected_diff_hunks(
15983        &mut self,
15984        _: &ToggleSelectedDiffHunks,
15985        _window: &mut Window,
15986        cx: &mut Context<Self>,
15987    ) {
15988        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15989        self.toggle_diff_hunks_in_ranges(ranges, cx);
15990    }
15991
15992    pub fn diff_hunks_in_ranges<'a>(
15993        &'a self,
15994        ranges: &'a [Range<Anchor>],
15995        buffer: &'a MultiBufferSnapshot,
15996    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15997        ranges.iter().flat_map(move |range| {
15998            let end_excerpt_id = range.end.excerpt_id;
15999            let range = range.to_point(buffer);
16000            let mut peek_end = range.end;
16001            if range.end.row < buffer.max_row().0 {
16002                peek_end = Point::new(range.end.row + 1, 0);
16003            }
16004            buffer
16005                .diff_hunks_in_range(range.start..peek_end)
16006                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
16007        })
16008    }
16009
16010    pub fn has_stageable_diff_hunks_in_ranges(
16011        &self,
16012        ranges: &[Range<Anchor>],
16013        snapshot: &MultiBufferSnapshot,
16014    ) -> bool {
16015        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
16016        hunks.any(|hunk| hunk.status().has_secondary_hunk())
16017    }
16018
16019    pub fn toggle_staged_selected_diff_hunks(
16020        &mut self,
16021        _: &::git::ToggleStaged,
16022        _: &mut Window,
16023        cx: &mut Context<Self>,
16024    ) {
16025        let snapshot = self.buffer.read(cx).snapshot(cx);
16026        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16027        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
16028        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16029    }
16030
16031    pub fn set_render_diff_hunk_controls(
16032        &mut self,
16033        render_diff_hunk_controls: RenderDiffHunkControlsFn,
16034        cx: &mut Context<Self>,
16035    ) {
16036        self.render_diff_hunk_controls = render_diff_hunk_controls;
16037        cx.notify();
16038    }
16039
16040    pub fn stage_and_next(
16041        &mut self,
16042        _: &::git::StageAndNext,
16043        window: &mut Window,
16044        cx: &mut Context<Self>,
16045    ) {
16046        self.do_stage_or_unstage_and_next(true, window, cx);
16047    }
16048
16049    pub fn unstage_and_next(
16050        &mut self,
16051        _: &::git::UnstageAndNext,
16052        window: &mut Window,
16053        cx: &mut Context<Self>,
16054    ) {
16055        self.do_stage_or_unstage_and_next(false, window, cx);
16056    }
16057
16058    pub fn stage_or_unstage_diff_hunks(
16059        &mut self,
16060        stage: bool,
16061        ranges: Vec<Range<Anchor>>,
16062        cx: &mut Context<Self>,
16063    ) {
16064        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
16065        cx.spawn(async move |this, cx| {
16066            task.await?;
16067            this.update(cx, |this, cx| {
16068                let snapshot = this.buffer.read(cx).snapshot(cx);
16069                let chunk_by = this
16070                    .diff_hunks_in_ranges(&ranges, &snapshot)
16071                    .chunk_by(|hunk| hunk.buffer_id);
16072                for (buffer_id, hunks) in &chunk_by {
16073                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
16074                }
16075            })
16076        })
16077        .detach_and_log_err(cx);
16078    }
16079
16080    fn save_buffers_for_ranges_if_needed(
16081        &mut self,
16082        ranges: &[Range<Anchor>],
16083        cx: &mut Context<Editor>,
16084    ) -> Task<Result<()>> {
16085        let multibuffer = self.buffer.read(cx);
16086        let snapshot = multibuffer.read(cx);
16087        let buffer_ids: HashSet<_> = ranges
16088            .iter()
16089            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
16090            .collect();
16091        drop(snapshot);
16092
16093        let mut buffers = HashSet::default();
16094        for buffer_id in buffer_ids {
16095            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
16096                let buffer = buffer_entity.read(cx);
16097                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
16098                {
16099                    buffers.insert(buffer_entity);
16100                }
16101            }
16102        }
16103
16104        if let Some(project) = &self.project {
16105            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
16106        } else {
16107            Task::ready(Ok(()))
16108        }
16109    }
16110
16111    fn do_stage_or_unstage_and_next(
16112        &mut self,
16113        stage: bool,
16114        window: &mut Window,
16115        cx: &mut Context<Self>,
16116    ) {
16117        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
16118
16119        if ranges.iter().any(|range| range.start != range.end) {
16120            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16121            return;
16122        }
16123
16124        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16125        let snapshot = self.snapshot(window, cx);
16126        let position = self.selections.newest::<Point>(cx).head();
16127        let mut row = snapshot
16128            .buffer_snapshot
16129            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
16130            .find(|hunk| hunk.row_range.start.0 > position.row)
16131            .map(|hunk| hunk.row_range.start);
16132
16133        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16134        // Outside of the project diff editor, wrap around to the beginning.
16135        if !all_diff_hunks_expanded {
16136            row = row.or_else(|| {
16137                snapshot
16138                    .buffer_snapshot
16139                    .diff_hunks_in_range(Point::zero()..position)
16140                    .find(|hunk| hunk.row_range.end.0 < position.row)
16141                    .map(|hunk| hunk.row_range.start)
16142            });
16143        }
16144
16145        if let Some(row) = row {
16146            let destination = Point::new(row.0, 0);
16147            let autoscroll = Autoscroll::center();
16148
16149            self.unfold_ranges(&[destination..destination], false, false, cx);
16150            self.change_selections(Some(autoscroll), window, cx, |s| {
16151                s.select_ranges([destination..destination]);
16152            });
16153        }
16154    }
16155
16156    fn do_stage_or_unstage(
16157        &self,
16158        stage: bool,
16159        buffer_id: BufferId,
16160        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16161        cx: &mut App,
16162    ) -> Option<()> {
16163        let project = self.project.as_ref()?;
16164        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16165        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16166        let buffer_snapshot = buffer.read(cx).snapshot();
16167        let file_exists = buffer_snapshot
16168            .file()
16169            .is_some_and(|file| file.disk_state().exists());
16170        diff.update(cx, |diff, cx| {
16171            diff.stage_or_unstage_hunks(
16172                stage,
16173                &hunks
16174                    .map(|hunk| buffer_diff::DiffHunk {
16175                        buffer_range: hunk.buffer_range,
16176                        diff_base_byte_range: hunk.diff_base_byte_range,
16177                        secondary_status: hunk.secondary_status,
16178                        range: Point::zero()..Point::zero(), // unused
16179                    })
16180                    .collect::<Vec<_>>(),
16181                &buffer_snapshot,
16182                file_exists,
16183                cx,
16184            )
16185        });
16186        None
16187    }
16188
16189    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16190        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16191        self.buffer
16192            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16193    }
16194
16195    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16196        self.buffer.update(cx, |buffer, cx| {
16197            let ranges = vec![Anchor::min()..Anchor::max()];
16198            if !buffer.all_diff_hunks_expanded()
16199                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16200            {
16201                buffer.collapse_diff_hunks(ranges, cx);
16202                true
16203            } else {
16204                false
16205            }
16206        })
16207    }
16208
16209    fn toggle_diff_hunks_in_ranges(
16210        &mut self,
16211        ranges: Vec<Range<Anchor>>,
16212        cx: &mut Context<Editor>,
16213    ) {
16214        self.buffer.update(cx, |buffer, cx| {
16215            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16216            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16217        })
16218    }
16219
16220    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16221        self.buffer.update(cx, |buffer, cx| {
16222            let snapshot = buffer.snapshot(cx);
16223            let excerpt_id = range.end.excerpt_id;
16224            let point_range = range.to_point(&snapshot);
16225            let expand = !buffer.single_hunk_is_expanded(range, cx);
16226            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16227        })
16228    }
16229
16230    pub(crate) fn apply_all_diff_hunks(
16231        &mut self,
16232        _: &ApplyAllDiffHunks,
16233        window: &mut Window,
16234        cx: &mut Context<Self>,
16235    ) {
16236        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16237
16238        let buffers = self.buffer.read(cx).all_buffers();
16239        for branch_buffer in buffers {
16240            branch_buffer.update(cx, |branch_buffer, cx| {
16241                branch_buffer.merge_into_base(Vec::new(), cx);
16242            });
16243        }
16244
16245        if let Some(project) = self.project.clone() {
16246            self.save(true, project, window, cx).detach_and_log_err(cx);
16247        }
16248    }
16249
16250    pub(crate) fn apply_selected_diff_hunks(
16251        &mut self,
16252        _: &ApplyDiffHunk,
16253        window: &mut Window,
16254        cx: &mut Context<Self>,
16255    ) {
16256        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16257        let snapshot = self.snapshot(window, cx);
16258        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16259        let mut ranges_by_buffer = HashMap::default();
16260        self.transact(window, cx, |editor, _window, cx| {
16261            for hunk in hunks {
16262                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16263                    ranges_by_buffer
16264                        .entry(buffer.clone())
16265                        .or_insert_with(Vec::new)
16266                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16267                }
16268            }
16269
16270            for (buffer, ranges) in ranges_by_buffer {
16271                buffer.update(cx, |buffer, cx| {
16272                    buffer.merge_into_base(ranges, cx);
16273                });
16274            }
16275        });
16276
16277        if let Some(project) = self.project.clone() {
16278            self.save(true, project, window, cx).detach_and_log_err(cx);
16279        }
16280    }
16281
16282    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16283        if hovered != self.gutter_hovered {
16284            self.gutter_hovered = hovered;
16285            cx.notify();
16286        }
16287    }
16288
16289    pub fn insert_blocks(
16290        &mut self,
16291        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16292        autoscroll: Option<Autoscroll>,
16293        cx: &mut Context<Self>,
16294    ) -> Vec<CustomBlockId> {
16295        let blocks = self
16296            .display_map
16297            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16298        if let Some(autoscroll) = autoscroll {
16299            self.request_autoscroll(autoscroll, cx);
16300        }
16301        cx.notify();
16302        blocks
16303    }
16304
16305    pub fn resize_blocks(
16306        &mut self,
16307        heights: HashMap<CustomBlockId, u32>,
16308        autoscroll: Option<Autoscroll>,
16309        cx: &mut Context<Self>,
16310    ) {
16311        self.display_map
16312            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16313        if let Some(autoscroll) = autoscroll {
16314            self.request_autoscroll(autoscroll, cx);
16315        }
16316        cx.notify();
16317    }
16318
16319    pub fn replace_blocks(
16320        &mut self,
16321        renderers: HashMap<CustomBlockId, RenderBlock>,
16322        autoscroll: Option<Autoscroll>,
16323        cx: &mut Context<Self>,
16324    ) {
16325        self.display_map
16326            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16327        if let Some(autoscroll) = autoscroll {
16328            self.request_autoscroll(autoscroll, cx);
16329        }
16330        cx.notify();
16331    }
16332
16333    pub fn remove_blocks(
16334        &mut self,
16335        block_ids: HashSet<CustomBlockId>,
16336        autoscroll: Option<Autoscroll>,
16337        cx: &mut Context<Self>,
16338    ) {
16339        self.display_map.update(cx, |display_map, cx| {
16340            display_map.remove_blocks(block_ids, cx)
16341        });
16342        if let Some(autoscroll) = autoscroll {
16343            self.request_autoscroll(autoscroll, cx);
16344        }
16345        cx.notify();
16346    }
16347
16348    pub fn row_for_block(
16349        &self,
16350        block_id: CustomBlockId,
16351        cx: &mut Context<Self>,
16352    ) -> Option<DisplayRow> {
16353        self.display_map
16354            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16355    }
16356
16357    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16358        self.focused_block = Some(focused_block);
16359    }
16360
16361    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16362        self.focused_block.take()
16363    }
16364
16365    pub fn insert_creases(
16366        &mut self,
16367        creases: impl IntoIterator<Item = Crease<Anchor>>,
16368        cx: &mut Context<Self>,
16369    ) -> Vec<CreaseId> {
16370        self.display_map
16371            .update(cx, |map, cx| map.insert_creases(creases, cx))
16372    }
16373
16374    pub fn remove_creases(
16375        &mut self,
16376        ids: impl IntoIterator<Item = CreaseId>,
16377        cx: &mut Context<Self>,
16378    ) -> Vec<(CreaseId, Range<Anchor>)> {
16379        self.display_map
16380            .update(cx, |map, cx| map.remove_creases(ids, cx))
16381    }
16382
16383    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16384        self.display_map
16385            .update(cx, |map, cx| map.snapshot(cx))
16386            .longest_row()
16387    }
16388
16389    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16390        self.display_map
16391            .update(cx, |map, cx| map.snapshot(cx))
16392            .max_point()
16393    }
16394
16395    pub fn text(&self, cx: &App) -> String {
16396        self.buffer.read(cx).read(cx).text()
16397    }
16398
16399    pub fn is_empty(&self, cx: &App) -> bool {
16400        self.buffer.read(cx).read(cx).is_empty()
16401    }
16402
16403    pub fn text_option(&self, cx: &App) -> Option<String> {
16404        let text = self.text(cx);
16405        let text = text.trim();
16406
16407        if text.is_empty() {
16408            return None;
16409        }
16410
16411        Some(text.to_string())
16412    }
16413
16414    pub fn set_text(
16415        &mut self,
16416        text: impl Into<Arc<str>>,
16417        window: &mut Window,
16418        cx: &mut Context<Self>,
16419    ) {
16420        self.transact(window, cx, |this, _, cx| {
16421            this.buffer
16422                .read(cx)
16423                .as_singleton()
16424                .expect("you can only call set_text on editors for singleton buffers")
16425                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16426        });
16427    }
16428
16429    pub fn display_text(&self, cx: &mut App) -> String {
16430        self.display_map
16431            .update(cx, |map, cx| map.snapshot(cx))
16432            .text()
16433    }
16434
16435    fn create_minimap(
16436        &self,
16437        minimap_settings: MinimapSettings,
16438        window: &mut Window,
16439        cx: &mut Context<Self>,
16440    ) -> Option<Entity<Self>> {
16441        (minimap_settings.minimap_enabled() && self.is_singleton(cx))
16442            .then(|| self.initialize_new_minimap(minimap_settings, window, cx))
16443    }
16444
16445    fn initialize_new_minimap(
16446        &self,
16447        minimap_settings: MinimapSettings,
16448        window: &mut Window,
16449        cx: &mut Context<Self>,
16450    ) -> Entity<Self> {
16451        const MINIMAP_FONT_WEIGHT: gpui::FontWeight = gpui::FontWeight::BLACK;
16452
16453        let mut minimap = Editor::new_internal(
16454            EditorMode::Minimap {
16455                parent: cx.weak_entity(),
16456            },
16457            self.buffer.clone(),
16458            self.project.clone(),
16459            Some(self.display_map.clone()),
16460            window,
16461            cx,
16462        );
16463        minimap.scroll_manager.clone_state(&self.scroll_manager);
16464        minimap.set_text_style_refinement(TextStyleRefinement {
16465            font_size: Some(MINIMAP_FONT_SIZE),
16466            font_weight: Some(MINIMAP_FONT_WEIGHT),
16467            ..Default::default()
16468        });
16469        minimap.update_minimap_configuration(minimap_settings, cx);
16470        cx.new(|_| minimap)
16471    }
16472
16473    fn update_minimap_configuration(&mut self, minimap_settings: MinimapSettings, cx: &App) {
16474        let current_line_highlight = minimap_settings
16475            .current_line_highlight
16476            .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight);
16477        self.set_current_line_highlight(Some(current_line_highlight));
16478    }
16479
16480    pub fn minimap(&self) -> Option<&Entity<Self>> {
16481        self.minimap
16482            .as_ref()
16483            .filter(|_| self.minimap_visibility.visible())
16484    }
16485
16486    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16487        let mut wrap_guides = smallvec::smallvec![];
16488
16489        if self.show_wrap_guides == Some(false) {
16490            return wrap_guides;
16491        }
16492
16493        let settings = self.buffer.read(cx).language_settings(cx);
16494        if settings.show_wrap_guides {
16495            match self.soft_wrap_mode(cx) {
16496                SoftWrap::Column(soft_wrap) => {
16497                    wrap_guides.push((soft_wrap as usize, true));
16498                }
16499                SoftWrap::Bounded(soft_wrap) => {
16500                    wrap_guides.push((soft_wrap as usize, true));
16501                }
16502                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16503            }
16504            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16505        }
16506
16507        wrap_guides
16508    }
16509
16510    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16511        let settings = self.buffer.read(cx).language_settings(cx);
16512        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16513        match mode {
16514            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16515                SoftWrap::None
16516            }
16517            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16518            language_settings::SoftWrap::PreferredLineLength => {
16519                SoftWrap::Column(settings.preferred_line_length)
16520            }
16521            language_settings::SoftWrap::Bounded => {
16522                SoftWrap::Bounded(settings.preferred_line_length)
16523            }
16524        }
16525    }
16526
16527    pub fn set_soft_wrap_mode(
16528        &mut self,
16529        mode: language_settings::SoftWrap,
16530
16531        cx: &mut Context<Self>,
16532    ) {
16533        self.soft_wrap_mode_override = Some(mode);
16534        cx.notify();
16535    }
16536
16537    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16538        self.hard_wrap = hard_wrap;
16539        cx.notify();
16540    }
16541
16542    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16543        self.text_style_refinement = Some(style);
16544    }
16545
16546    /// called by the Element so we know what style we were most recently rendered with.
16547    pub(crate) fn set_style(
16548        &mut self,
16549        style: EditorStyle,
16550        window: &mut Window,
16551        cx: &mut Context<Self>,
16552    ) {
16553        // We intentionally do not inform the display map about the minimap style
16554        // so that wrapping is not recalculated and stays consistent for the editor
16555        // and its linked minimap.
16556        if !self.mode.is_minimap() {
16557            let rem_size = window.rem_size();
16558            self.display_map.update(cx, |map, cx| {
16559                map.set_font(
16560                    style.text.font(),
16561                    style.text.font_size.to_pixels(rem_size),
16562                    cx,
16563                )
16564            });
16565        }
16566        self.style = Some(style);
16567    }
16568
16569    pub fn style(&self) -> Option<&EditorStyle> {
16570        self.style.as_ref()
16571    }
16572
16573    // Called by the element. This method is not designed to be called outside of the editor
16574    // element's layout code because it does not notify when rewrapping is computed synchronously.
16575    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16576        self.display_map
16577            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16578    }
16579
16580    pub fn set_soft_wrap(&mut self) {
16581        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16582    }
16583
16584    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16585        if self.soft_wrap_mode_override.is_some() {
16586            self.soft_wrap_mode_override.take();
16587        } else {
16588            let soft_wrap = match self.soft_wrap_mode(cx) {
16589                SoftWrap::GitDiff => return,
16590                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16591                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16592                    language_settings::SoftWrap::None
16593                }
16594            };
16595            self.soft_wrap_mode_override = Some(soft_wrap);
16596        }
16597        cx.notify();
16598    }
16599
16600    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16601        let Some(workspace) = self.workspace() else {
16602            return;
16603        };
16604        let fs = workspace.read(cx).app_state().fs.clone();
16605        let current_show = TabBarSettings::get_global(cx).show;
16606        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16607            setting.show = Some(!current_show);
16608        });
16609    }
16610
16611    pub fn toggle_indent_guides(
16612        &mut self,
16613        _: &ToggleIndentGuides,
16614        _: &mut Window,
16615        cx: &mut Context<Self>,
16616    ) {
16617        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16618            self.buffer
16619                .read(cx)
16620                .language_settings(cx)
16621                .indent_guides
16622                .enabled
16623        });
16624        self.show_indent_guides = Some(!currently_enabled);
16625        cx.notify();
16626    }
16627
16628    fn should_show_indent_guides(&self) -> Option<bool> {
16629        self.show_indent_guides
16630    }
16631
16632    pub fn toggle_line_numbers(
16633        &mut self,
16634        _: &ToggleLineNumbers,
16635        _: &mut Window,
16636        cx: &mut Context<Self>,
16637    ) {
16638        let mut editor_settings = EditorSettings::get_global(cx).clone();
16639        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16640        EditorSettings::override_global(editor_settings, cx);
16641    }
16642
16643    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16644        if let Some(show_line_numbers) = self.show_line_numbers {
16645            return show_line_numbers;
16646        }
16647        EditorSettings::get_global(cx).gutter.line_numbers
16648    }
16649
16650    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16651        self.use_relative_line_numbers
16652            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16653    }
16654
16655    pub fn toggle_relative_line_numbers(
16656        &mut self,
16657        _: &ToggleRelativeLineNumbers,
16658        _: &mut Window,
16659        cx: &mut Context<Self>,
16660    ) {
16661        let is_relative = self.should_use_relative_line_numbers(cx);
16662        self.set_relative_line_number(Some(!is_relative), cx)
16663    }
16664
16665    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16666        self.use_relative_line_numbers = is_relative;
16667        cx.notify();
16668    }
16669
16670    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16671        self.show_gutter = show_gutter;
16672        cx.notify();
16673    }
16674
16675    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16676        self.show_scrollbars = show_scrollbars;
16677        cx.notify();
16678    }
16679
16680    pub fn set_minimap_visibility(
16681        &mut self,
16682        minimap_visibility: MinimapVisibility,
16683        window: &mut Window,
16684        cx: &mut Context<Self>,
16685    ) {
16686        if self.minimap_visibility != minimap_visibility {
16687            if minimap_visibility.visible() && self.minimap.is_none() {
16688                let minimap_settings = EditorSettings::get_global(cx).minimap;
16689                self.minimap =
16690                    self.create_minimap(minimap_settings.with_show_override(), window, cx);
16691            }
16692            self.minimap_visibility = minimap_visibility;
16693            cx.notify();
16694        }
16695    }
16696
16697    pub fn disable_scrollbars_and_minimap(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16698        self.set_show_scrollbars(false, cx);
16699        self.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
16700    }
16701
16702    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16703        self.show_line_numbers = Some(show_line_numbers);
16704        cx.notify();
16705    }
16706
16707    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16708        self.disable_expand_excerpt_buttons = true;
16709        cx.notify();
16710    }
16711
16712    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16713        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16714        cx.notify();
16715    }
16716
16717    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16718        self.show_code_actions = Some(show_code_actions);
16719        cx.notify();
16720    }
16721
16722    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16723        self.show_runnables = Some(show_runnables);
16724        cx.notify();
16725    }
16726
16727    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16728        self.show_breakpoints = Some(show_breakpoints);
16729        cx.notify();
16730    }
16731
16732    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16733        if self.display_map.read(cx).masked != masked {
16734            self.display_map.update(cx, |map, _| map.masked = masked);
16735        }
16736        cx.notify()
16737    }
16738
16739    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16740        self.show_wrap_guides = Some(show_wrap_guides);
16741        cx.notify();
16742    }
16743
16744    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16745        self.show_indent_guides = Some(show_indent_guides);
16746        cx.notify();
16747    }
16748
16749    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16750        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16751            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16752                if let Some(dir) = file.abs_path(cx).parent() {
16753                    return Some(dir.to_owned());
16754                }
16755            }
16756
16757            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16758                return Some(project_path.path.to_path_buf());
16759            }
16760        }
16761
16762        None
16763    }
16764
16765    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16766        self.active_excerpt(cx)?
16767            .1
16768            .read(cx)
16769            .file()
16770            .and_then(|f| f.as_local())
16771    }
16772
16773    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16774        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16775            let buffer = buffer.read(cx);
16776            if let Some(project_path) = buffer.project_path(cx) {
16777                let project = self.project.as_ref()?.read(cx);
16778                project.absolute_path(&project_path, cx)
16779            } else {
16780                buffer
16781                    .file()
16782                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16783            }
16784        })
16785    }
16786
16787    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16788        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16789            let project_path = buffer.read(cx).project_path(cx)?;
16790            let project = self.project.as_ref()?.read(cx);
16791            let entry = project.entry_for_path(&project_path, cx)?;
16792            let path = entry.path.to_path_buf();
16793            Some(path)
16794        })
16795    }
16796
16797    pub fn reveal_in_finder(
16798        &mut self,
16799        _: &RevealInFileManager,
16800        _window: &mut Window,
16801        cx: &mut Context<Self>,
16802    ) {
16803        if let Some(target) = self.target_file(cx) {
16804            cx.reveal_path(&target.abs_path(cx));
16805        }
16806    }
16807
16808    pub fn copy_path(
16809        &mut self,
16810        _: &zed_actions::workspace::CopyPath,
16811        _window: &mut Window,
16812        cx: &mut Context<Self>,
16813    ) {
16814        if let Some(path) = self.target_file_abs_path(cx) {
16815            if let Some(path) = path.to_str() {
16816                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16817            }
16818        }
16819    }
16820
16821    pub fn copy_relative_path(
16822        &mut self,
16823        _: &zed_actions::workspace::CopyRelativePath,
16824        _window: &mut Window,
16825        cx: &mut Context<Self>,
16826    ) {
16827        if let Some(path) = self.target_file_path(cx) {
16828            if let Some(path) = path.to_str() {
16829                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16830            }
16831        }
16832    }
16833
16834    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16835        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16836            buffer.read(cx).project_path(cx)
16837        } else {
16838            None
16839        }
16840    }
16841
16842    // Returns true if the editor handled a go-to-line request
16843    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16844        maybe!({
16845            let breakpoint_store = self.breakpoint_store.as_ref()?;
16846
16847            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16848            else {
16849                self.clear_row_highlights::<ActiveDebugLine>();
16850                return None;
16851            };
16852
16853            let position = active_stack_frame.position;
16854            let buffer_id = position.buffer_id?;
16855            let snapshot = self
16856                .project
16857                .as_ref()?
16858                .read(cx)
16859                .buffer_for_id(buffer_id, cx)?
16860                .read(cx)
16861                .snapshot();
16862
16863            let mut handled = false;
16864            for (id, ExcerptRange { context, .. }) in
16865                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16866            {
16867                if context.start.cmp(&position, &snapshot).is_ge()
16868                    || context.end.cmp(&position, &snapshot).is_lt()
16869                {
16870                    continue;
16871                }
16872                let snapshot = self.buffer.read(cx).snapshot(cx);
16873                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16874
16875                handled = true;
16876                self.clear_row_highlights::<ActiveDebugLine>();
16877                self.go_to_line::<ActiveDebugLine>(
16878                    multibuffer_anchor,
16879                    Some(cx.theme().colors().editor_debugger_active_line_background),
16880                    window,
16881                    cx,
16882                );
16883
16884                cx.notify();
16885            }
16886
16887            handled.then_some(())
16888        })
16889        .is_some()
16890    }
16891
16892    pub fn copy_file_name_without_extension(
16893        &mut self,
16894        _: &CopyFileNameWithoutExtension,
16895        _: &mut Window,
16896        cx: &mut Context<Self>,
16897    ) {
16898        if let Some(file) = self.target_file(cx) {
16899            if let Some(file_stem) = file.path().file_stem() {
16900                if let Some(name) = file_stem.to_str() {
16901                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16902                }
16903            }
16904        }
16905    }
16906
16907    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16908        if let Some(file) = self.target_file(cx) {
16909            if let Some(file_name) = file.path().file_name() {
16910                if let Some(name) = file_name.to_str() {
16911                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16912                }
16913            }
16914        }
16915    }
16916
16917    pub fn toggle_git_blame(
16918        &mut self,
16919        _: &::git::Blame,
16920        window: &mut Window,
16921        cx: &mut Context<Self>,
16922    ) {
16923        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16924
16925        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16926            self.start_git_blame(true, window, cx);
16927        }
16928
16929        cx.notify();
16930    }
16931
16932    pub fn toggle_git_blame_inline(
16933        &mut self,
16934        _: &ToggleGitBlameInline,
16935        window: &mut Window,
16936        cx: &mut Context<Self>,
16937    ) {
16938        self.toggle_git_blame_inline_internal(true, window, cx);
16939        cx.notify();
16940    }
16941
16942    pub fn open_git_blame_commit(
16943        &mut self,
16944        _: &OpenGitBlameCommit,
16945        window: &mut Window,
16946        cx: &mut Context<Self>,
16947    ) {
16948        self.open_git_blame_commit_internal(window, cx);
16949    }
16950
16951    fn open_git_blame_commit_internal(
16952        &mut self,
16953        window: &mut Window,
16954        cx: &mut Context<Self>,
16955    ) -> Option<()> {
16956        let blame = self.blame.as_ref()?;
16957        let snapshot = self.snapshot(window, cx);
16958        let cursor = self.selections.newest::<Point>(cx).head();
16959        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16960        let blame_entry = blame
16961            .update(cx, |blame, cx| {
16962                blame
16963                    .blame_for_rows(
16964                        &[RowInfo {
16965                            buffer_id: Some(buffer.remote_id()),
16966                            buffer_row: Some(point.row),
16967                            ..Default::default()
16968                        }],
16969                        cx,
16970                    )
16971                    .next()
16972            })
16973            .flatten()?;
16974        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16975        let repo = blame.read(cx).repository(cx)?;
16976        let workspace = self.workspace()?.downgrade();
16977        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16978        None
16979    }
16980
16981    pub fn git_blame_inline_enabled(&self) -> bool {
16982        self.git_blame_inline_enabled
16983    }
16984
16985    pub fn toggle_selection_menu(
16986        &mut self,
16987        _: &ToggleSelectionMenu,
16988        _: &mut Window,
16989        cx: &mut Context<Self>,
16990    ) {
16991        self.show_selection_menu = self
16992            .show_selection_menu
16993            .map(|show_selections_menu| !show_selections_menu)
16994            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16995
16996        cx.notify();
16997    }
16998
16999    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
17000        self.show_selection_menu
17001            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
17002    }
17003
17004    fn start_git_blame(
17005        &mut self,
17006        user_triggered: bool,
17007        window: &mut Window,
17008        cx: &mut Context<Self>,
17009    ) {
17010        if let Some(project) = self.project.as_ref() {
17011            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
17012                return;
17013            };
17014
17015            if buffer.read(cx).file().is_none() {
17016                return;
17017            }
17018
17019            let focused = self.focus_handle(cx).contains_focused(window, cx);
17020
17021            let project = project.clone();
17022            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
17023            self.blame_subscription =
17024                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
17025            self.blame = Some(blame);
17026        }
17027    }
17028
17029    fn toggle_git_blame_inline_internal(
17030        &mut self,
17031        user_triggered: bool,
17032        window: &mut Window,
17033        cx: &mut Context<Self>,
17034    ) {
17035        if self.git_blame_inline_enabled {
17036            self.git_blame_inline_enabled = false;
17037            self.show_git_blame_inline = false;
17038            self.show_git_blame_inline_delay_task.take();
17039        } else {
17040            self.git_blame_inline_enabled = true;
17041            self.start_git_blame_inline(user_triggered, window, cx);
17042        }
17043
17044        cx.notify();
17045    }
17046
17047    fn start_git_blame_inline(
17048        &mut self,
17049        user_triggered: bool,
17050        window: &mut Window,
17051        cx: &mut Context<Self>,
17052    ) {
17053        self.start_git_blame(user_triggered, window, cx);
17054
17055        if ProjectSettings::get_global(cx)
17056            .git
17057            .inline_blame_delay()
17058            .is_some()
17059        {
17060            self.start_inline_blame_timer(window, cx);
17061        } else {
17062            self.show_git_blame_inline = true
17063        }
17064    }
17065
17066    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
17067        self.blame.as_ref()
17068    }
17069
17070    pub fn show_git_blame_gutter(&self) -> bool {
17071        self.show_git_blame_gutter
17072    }
17073
17074    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
17075        !self.mode().is_minimap() && self.show_git_blame_gutter && self.has_blame_entries(cx)
17076    }
17077
17078    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
17079        self.show_git_blame_inline
17080            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
17081            && !self.newest_selection_head_on_empty_line(cx)
17082            && self.has_blame_entries(cx)
17083    }
17084
17085    fn has_blame_entries(&self, cx: &App) -> bool {
17086        self.blame()
17087            .map_or(false, |blame| blame.read(cx).has_generated_entries())
17088    }
17089
17090    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
17091        let cursor_anchor = self.selections.newest_anchor().head();
17092
17093        let snapshot = self.buffer.read(cx).snapshot(cx);
17094        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
17095
17096        snapshot.line_len(buffer_row) == 0
17097    }
17098
17099    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
17100        let buffer_and_selection = maybe!({
17101            let selection = self.selections.newest::<Point>(cx);
17102            let selection_range = selection.range();
17103
17104            let multi_buffer = self.buffer().read(cx);
17105            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17106            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
17107
17108            let (buffer, range, _) = if selection.reversed {
17109                buffer_ranges.first()
17110            } else {
17111                buffer_ranges.last()
17112            }?;
17113
17114            let selection = text::ToPoint::to_point(&range.start, &buffer).row
17115                ..text::ToPoint::to_point(&range.end, &buffer).row;
17116            Some((
17117                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
17118                selection,
17119            ))
17120        });
17121
17122        let Some((buffer, selection)) = buffer_and_selection else {
17123            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
17124        };
17125
17126        let Some(project) = self.project.as_ref() else {
17127            return Task::ready(Err(anyhow!("editor does not have project")));
17128        };
17129
17130        project.update(cx, |project, cx| {
17131            project.get_permalink_to_line(&buffer, selection, cx)
17132        })
17133    }
17134
17135    pub fn copy_permalink_to_line(
17136        &mut self,
17137        _: &CopyPermalinkToLine,
17138        window: &mut Window,
17139        cx: &mut Context<Self>,
17140    ) {
17141        let permalink_task = self.get_permalink_to_line(cx);
17142        let workspace = self.workspace();
17143
17144        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17145            Ok(permalink) => {
17146                cx.update(|_, cx| {
17147                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
17148                })
17149                .ok();
17150            }
17151            Err(err) => {
17152                let message = format!("Failed to copy permalink: {err}");
17153
17154                Err::<(), anyhow::Error>(err).log_err();
17155
17156                if let Some(workspace) = workspace {
17157                    workspace
17158                        .update_in(cx, |workspace, _, cx| {
17159                            struct CopyPermalinkToLine;
17160
17161                            workspace.show_toast(
17162                                Toast::new(
17163                                    NotificationId::unique::<CopyPermalinkToLine>(),
17164                                    message,
17165                                ),
17166                                cx,
17167                            )
17168                        })
17169                        .ok();
17170                }
17171            }
17172        })
17173        .detach();
17174    }
17175
17176    pub fn copy_file_location(
17177        &mut self,
17178        _: &CopyFileLocation,
17179        _: &mut Window,
17180        cx: &mut Context<Self>,
17181    ) {
17182        let selection = self.selections.newest::<Point>(cx).start.row + 1;
17183        if let Some(file) = self.target_file(cx) {
17184            if let Some(path) = file.path().to_str() {
17185                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
17186            }
17187        }
17188    }
17189
17190    pub fn open_permalink_to_line(
17191        &mut self,
17192        _: &OpenPermalinkToLine,
17193        window: &mut Window,
17194        cx: &mut Context<Self>,
17195    ) {
17196        let permalink_task = self.get_permalink_to_line(cx);
17197        let workspace = self.workspace();
17198
17199        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17200            Ok(permalink) => {
17201                cx.update(|_, cx| {
17202                    cx.open_url(permalink.as_ref());
17203                })
17204                .ok();
17205            }
17206            Err(err) => {
17207                let message = format!("Failed to open permalink: {err}");
17208
17209                Err::<(), anyhow::Error>(err).log_err();
17210
17211                if let Some(workspace) = workspace {
17212                    workspace
17213                        .update(cx, |workspace, cx| {
17214                            struct OpenPermalinkToLine;
17215
17216                            workspace.show_toast(
17217                                Toast::new(
17218                                    NotificationId::unique::<OpenPermalinkToLine>(),
17219                                    message,
17220                                ),
17221                                cx,
17222                            )
17223                        })
17224                        .ok();
17225                }
17226            }
17227        })
17228        .detach();
17229    }
17230
17231    pub fn insert_uuid_v4(
17232        &mut self,
17233        _: &InsertUuidV4,
17234        window: &mut Window,
17235        cx: &mut Context<Self>,
17236    ) {
17237        self.insert_uuid(UuidVersion::V4, window, cx);
17238    }
17239
17240    pub fn insert_uuid_v7(
17241        &mut self,
17242        _: &InsertUuidV7,
17243        window: &mut Window,
17244        cx: &mut Context<Self>,
17245    ) {
17246        self.insert_uuid(UuidVersion::V7, window, cx);
17247    }
17248
17249    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17250        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17251        self.transact(window, cx, |this, window, cx| {
17252            let edits = this
17253                .selections
17254                .all::<Point>(cx)
17255                .into_iter()
17256                .map(|selection| {
17257                    let uuid = match version {
17258                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17259                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17260                    };
17261
17262                    (selection.range(), uuid.to_string())
17263                });
17264            this.edit(edits, cx);
17265            this.refresh_inline_completion(true, false, window, cx);
17266        });
17267    }
17268
17269    pub fn open_selections_in_multibuffer(
17270        &mut self,
17271        _: &OpenSelectionsInMultibuffer,
17272        window: &mut Window,
17273        cx: &mut Context<Self>,
17274    ) {
17275        let multibuffer = self.buffer.read(cx);
17276
17277        let Some(buffer) = multibuffer.as_singleton() else {
17278            return;
17279        };
17280
17281        let Some(workspace) = self.workspace() else {
17282            return;
17283        };
17284
17285        let locations = self
17286            .selections
17287            .disjoint_anchors()
17288            .iter()
17289            .map(|range| Location {
17290                buffer: buffer.clone(),
17291                range: range.start.text_anchor..range.end.text_anchor,
17292            })
17293            .collect::<Vec<_>>();
17294
17295        let title = multibuffer.title(cx).to_string();
17296
17297        cx.spawn_in(window, async move |_, cx| {
17298            workspace.update_in(cx, |workspace, window, cx| {
17299                Self::open_locations_in_multibuffer(
17300                    workspace,
17301                    locations,
17302                    format!("Selections for '{title}'"),
17303                    false,
17304                    MultibufferSelectionMode::All,
17305                    window,
17306                    cx,
17307                );
17308            })
17309        })
17310        .detach();
17311    }
17312
17313    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17314    /// last highlight added will be used.
17315    ///
17316    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17317    pub fn highlight_rows<T: 'static>(
17318        &mut self,
17319        range: Range<Anchor>,
17320        color: Hsla,
17321        options: RowHighlightOptions,
17322        cx: &mut Context<Self>,
17323    ) {
17324        let snapshot = self.buffer().read(cx).snapshot(cx);
17325        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17326        let ix = row_highlights.binary_search_by(|highlight| {
17327            Ordering::Equal
17328                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17329                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17330        });
17331
17332        if let Err(mut ix) = ix {
17333            let index = post_inc(&mut self.highlight_order);
17334
17335            // If this range intersects with the preceding highlight, then merge it with
17336            // the preceding highlight. Otherwise insert a new highlight.
17337            let mut merged = false;
17338            if ix > 0 {
17339                let prev_highlight = &mut row_highlights[ix - 1];
17340                if prev_highlight
17341                    .range
17342                    .end
17343                    .cmp(&range.start, &snapshot)
17344                    .is_ge()
17345                {
17346                    ix -= 1;
17347                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17348                        prev_highlight.range.end = range.end;
17349                    }
17350                    merged = true;
17351                    prev_highlight.index = index;
17352                    prev_highlight.color = color;
17353                    prev_highlight.options = options;
17354                }
17355            }
17356
17357            if !merged {
17358                row_highlights.insert(
17359                    ix,
17360                    RowHighlight {
17361                        range: range.clone(),
17362                        index,
17363                        color,
17364                        options,
17365                        type_id: TypeId::of::<T>(),
17366                    },
17367                );
17368            }
17369
17370            // If any of the following highlights intersect with this one, merge them.
17371            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17372                let highlight = &row_highlights[ix];
17373                if next_highlight
17374                    .range
17375                    .start
17376                    .cmp(&highlight.range.end, &snapshot)
17377                    .is_le()
17378                {
17379                    if next_highlight
17380                        .range
17381                        .end
17382                        .cmp(&highlight.range.end, &snapshot)
17383                        .is_gt()
17384                    {
17385                        row_highlights[ix].range.end = next_highlight.range.end;
17386                    }
17387                    row_highlights.remove(ix + 1);
17388                } else {
17389                    break;
17390                }
17391            }
17392        }
17393    }
17394
17395    /// Remove any highlighted row ranges of the given type that intersect the
17396    /// given ranges.
17397    pub fn remove_highlighted_rows<T: 'static>(
17398        &mut self,
17399        ranges_to_remove: Vec<Range<Anchor>>,
17400        cx: &mut Context<Self>,
17401    ) {
17402        let snapshot = self.buffer().read(cx).snapshot(cx);
17403        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17404        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17405        row_highlights.retain(|highlight| {
17406            while let Some(range_to_remove) = ranges_to_remove.peek() {
17407                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17408                    Ordering::Less | Ordering::Equal => {
17409                        ranges_to_remove.next();
17410                    }
17411                    Ordering::Greater => {
17412                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17413                            Ordering::Less | Ordering::Equal => {
17414                                return false;
17415                            }
17416                            Ordering::Greater => break,
17417                        }
17418                    }
17419                }
17420            }
17421
17422            true
17423        })
17424    }
17425
17426    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17427    pub fn clear_row_highlights<T: 'static>(&mut self) {
17428        self.highlighted_rows.remove(&TypeId::of::<T>());
17429    }
17430
17431    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17432    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17433        self.highlighted_rows
17434            .get(&TypeId::of::<T>())
17435            .map_or(&[] as &[_], |vec| vec.as_slice())
17436            .iter()
17437            .map(|highlight| (highlight.range.clone(), highlight.color))
17438    }
17439
17440    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17441    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17442    /// Allows to ignore certain kinds of highlights.
17443    pub fn highlighted_display_rows(
17444        &self,
17445        window: &mut Window,
17446        cx: &mut App,
17447    ) -> BTreeMap<DisplayRow, LineHighlight> {
17448        let snapshot = self.snapshot(window, cx);
17449        let mut used_highlight_orders = HashMap::default();
17450        self.highlighted_rows
17451            .iter()
17452            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17453            .fold(
17454                BTreeMap::<DisplayRow, LineHighlight>::new(),
17455                |mut unique_rows, highlight| {
17456                    let start = highlight.range.start.to_display_point(&snapshot);
17457                    let end = highlight.range.end.to_display_point(&snapshot);
17458                    let start_row = start.row().0;
17459                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17460                        && end.column() == 0
17461                    {
17462                        end.row().0.saturating_sub(1)
17463                    } else {
17464                        end.row().0
17465                    };
17466                    for row in start_row..=end_row {
17467                        let used_index =
17468                            used_highlight_orders.entry(row).or_insert(highlight.index);
17469                        if highlight.index >= *used_index {
17470                            *used_index = highlight.index;
17471                            unique_rows.insert(
17472                                DisplayRow(row),
17473                                LineHighlight {
17474                                    include_gutter: highlight.options.include_gutter,
17475                                    border: None,
17476                                    background: highlight.color.into(),
17477                                    type_id: Some(highlight.type_id),
17478                                },
17479                            );
17480                        }
17481                    }
17482                    unique_rows
17483                },
17484            )
17485    }
17486
17487    pub fn highlighted_display_row_for_autoscroll(
17488        &self,
17489        snapshot: &DisplaySnapshot,
17490    ) -> Option<DisplayRow> {
17491        self.highlighted_rows
17492            .values()
17493            .flat_map(|highlighted_rows| highlighted_rows.iter())
17494            .filter_map(|highlight| {
17495                if highlight.options.autoscroll {
17496                    Some(highlight.range.start.to_display_point(snapshot).row())
17497                } else {
17498                    None
17499                }
17500            })
17501            .min()
17502    }
17503
17504    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17505        self.highlight_background::<SearchWithinRange>(
17506            ranges,
17507            |colors| colors.editor_document_highlight_read_background,
17508            cx,
17509        )
17510    }
17511
17512    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17513        self.breadcrumb_header = Some(new_header);
17514    }
17515
17516    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17517        self.clear_background_highlights::<SearchWithinRange>(cx);
17518    }
17519
17520    pub fn highlight_background<T: 'static>(
17521        &mut self,
17522        ranges: &[Range<Anchor>],
17523        color_fetcher: fn(&ThemeColors) -> Hsla,
17524        cx: &mut Context<Self>,
17525    ) {
17526        self.background_highlights
17527            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17528        self.scrollbar_marker_state.dirty = true;
17529        cx.notify();
17530    }
17531
17532    pub fn clear_background_highlights<T: 'static>(
17533        &mut self,
17534        cx: &mut Context<Self>,
17535    ) -> Option<BackgroundHighlight> {
17536        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17537        if !text_highlights.1.is_empty() {
17538            self.scrollbar_marker_state.dirty = true;
17539            cx.notify();
17540        }
17541        Some(text_highlights)
17542    }
17543
17544    pub fn highlight_gutter<T: 'static>(
17545        &mut self,
17546        ranges: &[Range<Anchor>],
17547        color_fetcher: fn(&App) -> Hsla,
17548        cx: &mut Context<Self>,
17549    ) {
17550        self.gutter_highlights
17551            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17552        cx.notify();
17553    }
17554
17555    pub fn clear_gutter_highlights<T: 'static>(
17556        &mut self,
17557        cx: &mut Context<Self>,
17558    ) -> Option<GutterHighlight> {
17559        cx.notify();
17560        self.gutter_highlights.remove(&TypeId::of::<T>())
17561    }
17562
17563    #[cfg(feature = "test-support")]
17564    pub fn all_text_background_highlights(
17565        &self,
17566        window: &mut Window,
17567        cx: &mut Context<Self>,
17568    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17569        let snapshot = self.snapshot(window, cx);
17570        let buffer = &snapshot.buffer_snapshot;
17571        let start = buffer.anchor_before(0);
17572        let end = buffer.anchor_after(buffer.len());
17573        let theme = cx.theme().colors();
17574        self.background_highlights_in_range(start..end, &snapshot, theme)
17575    }
17576
17577    #[cfg(feature = "test-support")]
17578    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17579        let snapshot = self.buffer().read(cx).snapshot(cx);
17580
17581        let highlights = self
17582            .background_highlights
17583            .get(&TypeId::of::<items::BufferSearchHighlights>());
17584
17585        if let Some((_color, ranges)) = highlights {
17586            ranges
17587                .iter()
17588                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17589                .collect_vec()
17590        } else {
17591            vec![]
17592        }
17593    }
17594
17595    fn document_highlights_for_position<'a>(
17596        &'a self,
17597        position: Anchor,
17598        buffer: &'a MultiBufferSnapshot,
17599    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17600        let read_highlights = self
17601            .background_highlights
17602            .get(&TypeId::of::<DocumentHighlightRead>())
17603            .map(|h| &h.1);
17604        let write_highlights = self
17605            .background_highlights
17606            .get(&TypeId::of::<DocumentHighlightWrite>())
17607            .map(|h| &h.1);
17608        let left_position = position.bias_left(buffer);
17609        let right_position = position.bias_right(buffer);
17610        read_highlights
17611            .into_iter()
17612            .chain(write_highlights)
17613            .flat_map(move |ranges| {
17614                let start_ix = match ranges.binary_search_by(|probe| {
17615                    let cmp = probe.end.cmp(&left_position, buffer);
17616                    if cmp.is_ge() {
17617                        Ordering::Greater
17618                    } else {
17619                        Ordering::Less
17620                    }
17621                }) {
17622                    Ok(i) | Err(i) => i,
17623                };
17624
17625                ranges[start_ix..]
17626                    .iter()
17627                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17628            })
17629    }
17630
17631    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17632        self.background_highlights
17633            .get(&TypeId::of::<T>())
17634            .map_or(false, |(_, highlights)| !highlights.is_empty())
17635    }
17636
17637    pub fn background_highlights_in_range(
17638        &self,
17639        search_range: Range<Anchor>,
17640        display_snapshot: &DisplaySnapshot,
17641        theme: &ThemeColors,
17642    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17643        let mut results = Vec::new();
17644        for (color_fetcher, ranges) in self.background_highlights.values() {
17645            let color = color_fetcher(theme);
17646            let start_ix = match ranges.binary_search_by(|probe| {
17647                let cmp = probe
17648                    .end
17649                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17650                if cmp.is_gt() {
17651                    Ordering::Greater
17652                } else {
17653                    Ordering::Less
17654                }
17655            }) {
17656                Ok(i) | Err(i) => i,
17657            };
17658            for range in &ranges[start_ix..] {
17659                if range
17660                    .start
17661                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17662                    .is_ge()
17663                {
17664                    break;
17665                }
17666
17667                let start = range.start.to_display_point(display_snapshot);
17668                let end = range.end.to_display_point(display_snapshot);
17669                results.push((start..end, color))
17670            }
17671        }
17672        results
17673    }
17674
17675    pub fn background_highlight_row_ranges<T: 'static>(
17676        &self,
17677        search_range: Range<Anchor>,
17678        display_snapshot: &DisplaySnapshot,
17679        count: usize,
17680    ) -> Vec<RangeInclusive<DisplayPoint>> {
17681        let mut results = Vec::new();
17682        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17683            return vec![];
17684        };
17685
17686        let start_ix = match ranges.binary_search_by(|probe| {
17687            let cmp = probe
17688                .end
17689                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17690            if cmp.is_gt() {
17691                Ordering::Greater
17692            } else {
17693                Ordering::Less
17694            }
17695        }) {
17696            Ok(i) | Err(i) => i,
17697        };
17698        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17699            if let (Some(start_display), Some(end_display)) = (start, end) {
17700                results.push(
17701                    start_display.to_display_point(display_snapshot)
17702                        ..=end_display.to_display_point(display_snapshot),
17703                );
17704            }
17705        };
17706        let mut start_row: Option<Point> = None;
17707        let mut end_row: Option<Point> = None;
17708        if ranges.len() > count {
17709            return Vec::new();
17710        }
17711        for range in &ranges[start_ix..] {
17712            if range
17713                .start
17714                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17715                .is_ge()
17716            {
17717                break;
17718            }
17719            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17720            if let Some(current_row) = &end_row {
17721                if end.row == current_row.row {
17722                    continue;
17723                }
17724            }
17725            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17726            if start_row.is_none() {
17727                assert_eq!(end_row, None);
17728                start_row = Some(start);
17729                end_row = Some(end);
17730                continue;
17731            }
17732            if let Some(current_end) = end_row.as_mut() {
17733                if start.row > current_end.row + 1 {
17734                    push_region(start_row, end_row);
17735                    start_row = Some(start);
17736                    end_row = Some(end);
17737                } else {
17738                    // Merge two hunks.
17739                    *current_end = end;
17740                }
17741            } else {
17742                unreachable!();
17743            }
17744        }
17745        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17746        push_region(start_row, end_row);
17747        results
17748    }
17749
17750    pub fn gutter_highlights_in_range(
17751        &self,
17752        search_range: Range<Anchor>,
17753        display_snapshot: &DisplaySnapshot,
17754        cx: &App,
17755    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17756        let mut results = Vec::new();
17757        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17758            let color = color_fetcher(cx);
17759            let start_ix = match ranges.binary_search_by(|probe| {
17760                let cmp = probe
17761                    .end
17762                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17763                if cmp.is_gt() {
17764                    Ordering::Greater
17765                } else {
17766                    Ordering::Less
17767                }
17768            }) {
17769                Ok(i) | Err(i) => i,
17770            };
17771            for range in &ranges[start_ix..] {
17772                if range
17773                    .start
17774                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17775                    .is_ge()
17776                {
17777                    break;
17778                }
17779
17780                let start = range.start.to_display_point(display_snapshot);
17781                let end = range.end.to_display_point(display_snapshot);
17782                results.push((start..end, color))
17783            }
17784        }
17785        results
17786    }
17787
17788    /// Get the text ranges corresponding to the redaction query
17789    pub fn redacted_ranges(
17790        &self,
17791        search_range: Range<Anchor>,
17792        display_snapshot: &DisplaySnapshot,
17793        cx: &App,
17794    ) -> Vec<Range<DisplayPoint>> {
17795        display_snapshot
17796            .buffer_snapshot
17797            .redacted_ranges(search_range, |file| {
17798                if let Some(file) = file {
17799                    file.is_private()
17800                        && EditorSettings::get(
17801                            Some(SettingsLocation {
17802                                worktree_id: file.worktree_id(cx),
17803                                path: file.path().as_ref(),
17804                            }),
17805                            cx,
17806                        )
17807                        .redact_private_values
17808                } else {
17809                    false
17810                }
17811            })
17812            .map(|range| {
17813                range.start.to_display_point(display_snapshot)
17814                    ..range.end.to_display_point(display_snapshot)
17815            })
17816            .collect()
17817    }
17818
17819    pub fn highlight_text<T: 'static>(
17820        &mut self,
17821        ranges: Vec<Range<Anchor>>,
17822        style: HighlightStyle,
17823        cx: &mut Context<Self>,
17824    ) {
17825        self.display_map.update(cx, |map, _| {
17826            map.highlight_text(TypeId::of::<T>(), ranges, style)
17827        });
17828        cx.notify();
17829    }
17830
17831    pub(crate) fn highlight_inlays<T: 'static>(
17832        &mut self,
17833        highlights: Vec<InlayHighlight>,
17834        style: HighlightStyle,
17835        cx: &mut Context<Self>,
17836    ) {
17837        self.display_map.update(cx, |map, _| {
17838            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17839        });
17840        cx.notify();
17841    }
17842
17843    pub fn text_highlights<'a, T: 'static>(
17844        &'a self,
17845        cx: &'a App,
17846    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17847        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17848    }
17849
17850    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17851        let cleared = self
17852            .display_map
17853            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17854        if cleared {
17855            cx.notify();
17856        }
17857    }
17858
17859    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17860        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17861            && self.focus_handle.is_focused(window)
17862    }
17863
17864    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17865        self.show_cursor_when_unfocused = is_enabled;
17866        cx.notify();
17867    }
17868
17869    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17870        cx.notify();
17871    }
17872
17873    fn on_debug_session_event(
17874        &mut self,
17875        _session: Entity<Session>,
17876        event: &SessionEvent,
17877        cx: &mut Context<Self>,
17878    ) {
17879        match event {
17880            SessionEvent::InvalidateInlineValue => {
17881                self.refresh_inline_values(cx);
17882            }
17883            _ => {}
17884        }
17885    }
17886
17887    pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17888        let Some(project) = self.project.clone() else {
17889            return;
17890        };
17891        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17892            return;
17893        };
17894        if !self.inline_value_cache.enabled {
17895            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17896            self.splice_inlays(&inlays, Vec::new(), cx);
17897            return;
17898        }
17899
17900        let current_execution_position = self
17901            .highlighted_rows
17902            .get(&TypeId::of::<ActiveDebugLine>())
17903            .and_then(|lines| lines.last().map(|line| line.range.start));
17904
17905        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17906            let snapshot = editor
17907                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17908                .ok()?;
17909
17910            let inline_values = editor
17911                .update(cx, |_, cx| {
17912                    let Some(current_execution_position) = current_execution_position else {
17913                        return Some(Task::ready(Ok(Vec::new())));
17914                    };
17915
17916                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17917                    // anchor is in the same buffer
17918                    let range =
17919                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17920                    project.inline_values(buffer, range, cx)
17921                })
17922                .ok()
17923                .flatten()?
17924                .await
17925                .context("refreshing debugger inlays")
17926                .log_err()?;
17927
17928            let (excerpt_id, buffer_id) = snapshot
17929                .excerpts()
17930                .next()
17931                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17932            editor
17933                .update(cx, |editor, cx| {
17934                    let new_inlays = inline_values
17935                        .into_iter()
17936                        .map(|debugger_value| {
17937                            Inlay::debugger_hint(
17938                                post_inc(&mut editor.next_inlay_id),
17939                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17940                                debugger_value.text(),
17941                            )
17942                        })
17943                        .collect::<Vec<_>>();
17944                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17945                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17946
17947                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17948                })
17949                .ok()?;
17950            Some(())
17951        });
17952    }
17953
17954    fn on_buffer_event(
17955        &mut self,
17956        multibuffer: &Entity<MultiBuffer>,
17957        event: &multi_buffer::Event,
17958        window: &mut Window,
17959        cx: &mut Context<Self>,
17960    ) {
17961        match event {
17962            multi_buffer::Event::Edited {
17963                singleton_buffer_edited,
17964                edited_buffer: buffer_edited,
17965            } => {
17966                self.scrollbar_marker_state.dirty = true;
17967                self.active_indent_guides_state.dirty = true;
17968                self.refresh_active_diagnostics(cx);
17969                self.refresh_code_actions(window, cx);
17970                self.refresh_selected_text_highlights(true, window, cx);
17971                refresh_matching_bracket_highlights(self, window, cx);
17972                if self.has_active_inline_completion() {
17973                    self.update_visible_inline_completion(window, cx);
17974                }
17975                if let Some(buffer) = buffer_edited {
17976                    let buffer_id = buffer.read(cx).remote_id();
17977                    if !self.registered_buffers.contains_key(&buffer_id) {
17978                        if let Some(project) = self.project.as_ref() {
17979                            project.update(cx, |project, cx| {
17980                                self.registered_buffers.insert(
17981                                    buffer_id,
17982                                    project.register_buffer_with_language_servers(&buffer, cx),
17983                                );
17984                            })
17985                        }
17986                    }
17987                }
17988                cx.emit(EditorEvent::BufferEdited);
17989                cx.emit(SearchEvent::MatchesInvalidated);
17990                if *singleton_buffer_edited {
17991                    if let Some(project) = &self.project {
17992                        #[allow(clippy::mutable_key_type)]
17993                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17994                            multibuffer
17995                                .all_buffers()
17996                                .into_iter()
17997                                .filter_map(|buffer| {
17998                                    buffer.update(cx, |buffer, cx| {
17999                                        let language = buffer.language()?;
18000                                        let should_discard = project.update(cx, |project, cx| {
18001                                            project.is_local()
18002                                                && !project.has_language_servers_for(buffer, cx)
18003                                        });
18004                                        should_discard.not().then_some(language.clone())
18005                                    })
18006                                })
18007                                .collect::<HashSet<_>>()
18008                        });
18009                        if !languages_affected.is_empty() {
18010                            self.refresh_inlay_hints(
18011                                InlayHintRefreshReason::BufferEdited(languages_affected),
18012                                cx,
18013                            );
18014                        }
18015                    }
18016                }
18017
18018                let Some(project) = &self.project else { return };
18019                let (telemetry, is_via_ssh) = {
18020                    let project = project.read(cx);
18021                    let telemetry = project.client().telemetry().clone();
18022                    let is_via_ssh = project.is_via_ssh();
18023                    (telemetry, is_via_ssh)
18024                };
18025                refresh_linked_ranges(self, window, cx);
18026                telemetry.log_edit_event("editor", is_via_ssh);
18027            }
18028            multi_buffer::Event::ExcerptsAdded {
18029                buffer,
18030                predecessor,
18031                excerpts,
18032            } => {
18033                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18034                let buffer_id = buffer.read(cx).remote_id();
18035                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
18036                    if let Some(project) = &self.project {
18037                        update_uncommitted_diff_for_buffer(
18038                            cx.entity(),
18039                            project,
18040                            [buffer.clone()],
18041                            self.buffer.clone(),
18042                            cx,
18043                        )
18044                        .detach();
18045                    }
18046                }
18047                cx.emit(EditorEvent::ExcerptsAdded {
18048                    buffer: buffer.clone(),
18049                    predecessor: *predecessor,
18050                    excerpts: excerpts.clone(),
18051                });
18052                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
18053            }
18054            multi_buffer::Event::ExcerptsRemoved {
18055                ids,
18056                removed_buffer_ids,
18057            } => {
18058                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
18059                let buffer = self.buffer.read(cx);
18060                self.registered_buffers
18061                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
18062                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18063                cx.emit(EditorEvent::ExcerptsRemoved {
18064                    ids: ids.clone(),
18065                    removed_buffer_ids: removed_buffer_ids.clone(),
18066                })
18067            }
18068            multi_buffer::Event::ExcerptsEdited {
18069                excerpt_ids,
18070                buffer_ids,
18071            } => {
18072                self.display_map.update(cx, |map, cx| {
18073                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
18074                });
18075                cx.emit(EditorEvent::ExcerptsEdited {
18076                    ids: excerpt_ids.clone(),
18077                })
18078            }
18079            multi_buffer::Event::ExcerptsExpanded { ids } => {
18080                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
18081                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
18082            }
18083            multi_buffer::Event::Reparsed(buffer_id) => {
18084                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18085                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18086
18087                cx.emit(EditorEvent::Reparsed(*buffer_id));
18088            }
18089            multi_buffer::Event::DiffHunksToggled => {
18090                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18091            }
18092            multi_buffer::Event::LanguageChanged(buffer_id) => {
18093                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
18094                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18095                cx.emit(EditorEvent::Reparsed(*buffer_id));
18096                cx.notify();
18097            }
18098            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
18099            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
18100            multi_buffer::Event::FileHandleChanged
18101            | multi_buffer::Event::Reloaded
18102            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
18103            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
18104            multi_buffer::Event::DiagnosticsUpdated => {
18105                self.refresh_active_diagnostics(cx);
18106                self.refresh_inline_diagnostics(true, window, cx);
18107                self.scrollbar_marker_state.dirty = true;
18108                cx.notify();
18109            }
18110            _ => {}
18111        };
18112    }
18113
18114    pub fn start_temporary_diff_override(&mut self) {
18115        self.load_diff_task.take();
18116        self.temporary_diff_override = true;
18117    }
18118
18119    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
18120        self.temporary_diff_override = false;
18121        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
18122        self.buffer.update(cx, |buffer, cx| {
18123            buffer.set_all_diff_hunks_collapsed(cx);
18124        });
18125
18126        if let Some(project) = self.project.clone() {
18127            self.load_diff_task = Some(
18128                update_uncommitted_diff_for_buffer(
18129                    cx.entity(),
18130                    &project,
18131                    self.buffer.read(cx).all_buffers(),
18132                    self.buffer.clone(),
18133                    cx,
18134                )
18135                .shared(),
18136            );
18137        }
18138    }
18139
18140    fn on_display_map_changed(
18141        &mut self,
18142        _: Entity<DisplayMap>,
18143        _: &mut Window,
18144        cx: &mut Context<Self>,
18145    ) {
18146        cx.notify();
18147    }
18148
18149    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18150        let new_severity = if self.diagnostics_enabled() {
18151            EditorSettings::get_global(cx)
18152                .diagnostics_max_severity
18153                .unwrap_or(DiagnosticSeverity::Hint)
18154        } else {
18155            DiagnosticSeverity::Off
18156        };
18157        self.set_max_diagnostics_severity(new_severity, cx);
18158        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18159        self.update_edit_prediction_settings(cx);
18160        self.refresh_inline_completion(true, false, window, cx);
18161        self.refresh_inlay_hints(
18162            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
18163                self.selections.newest_anchor().head(),
18164                &self.buffer.read(cx).snapshot(cx),
18165                cx,
18166            )),
18167            cx,
18168        );
18169
18170        let old_cursor_shape = self.cursor_shape;
18171
18172        {
18173            let editor_settings = EditorSettings::get_global(cx);
18174            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
18175            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
18176            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
18177            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
18178        }
18179
18180        if old_cursor_shape != self.cursor_shape {
18181            cx.emit(EditorEvent::CursorShapeChanged);
18182        }
18183
18184        let project_settings = ProjectSettings::get_global(cx);
18185        self.serialize_dirty_buffers =
18186            !self.mode.is_minimap() && project_settings.session.restore_unsaved_buffers;
18187
18188        if self.mode.is_full() {
18189            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
18190            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
18191            if self.show_inline_diagnostics != show_inline_diagnostics {
18192                self.show_inline_diagnostics = show_inline_diagnostics;
18193                self.refresh_inline_diagnostics(false, window, cx);
18194            }
18195
18196            if self.git_blame_inline_enabled != inline_blame_enabled {
18197                self.toggle_git_blame_inline_internal(false, window, cx);
18198            }
18199
18200            let minimap_settings = EditorSettings::get_global(cx).minimap;
18201            if self.minimap_visibility.visible() != minimap_settings.minimap_enabled() {
18202                self.set_minimap_visibility(
18203                    self.minimap_visibility.toggle_visibility(),
18204                    window,
18205                    cx,
18206                );
18207            } else if let Some(minimap_entity) = self.minimap.as_ref() {
18208                minimap_entity.update(cx, |minimap_editor, cx| {
18209                    minimap_editor.update_minimap_configuration(minimap_settings, cx)
18210                })
18211            }
18212        }
18213
18214        cx.notify();
18215    }
18216
18217    pub fn set_searchable(&mut self, searchable: bool) {
18218        self.searchable = searchable;
18219    }
18220
18221    pub fn searchable(&self) -> bool {
18222        self.searchable
18223    }
18224
18225    fn open_proposed_changes_editor(
18226        &mut self,
18227        _: &OpenProposedChangesEditor,
18228        window: &mut Window,
18229        cx: &mut Context<Self>,
18230    ) {
18231        let Some(workspace) = self.workspace() else {
18232            cx.propagate();
18233            return;
18234        };
18235
18236        let selections = self.selections.all::<usize>(cx);
18237        let multi_buffer = self.buffer.read(cx);
18238        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18239        let mut new_selections_by_buffer = HashMap::default();
18240        for selection in selections {
18241            for (buffer, range, _) in
18242                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18243            {
18244                let mut range = range.to_point(buffer);
18245                range.start.column = 0;
18246                range.end.column = buffer.line_len(range.end.row);
18247                new_selections_by_buffer
18248                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18249                    .or_insert(Vec::new())
18250                    .push(range)
18251            }
18252        }
18253
18254        let proposed_changes_buffers = new_selections_by_buffer
18255            .into_iter()
18256            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18257            .collect::<Vec<_>>();
18258        let proposed_changes_editor = cx.new(|cx| {
18259            ProposedChangesEditor::new(
18260                "Proposed changes",
18261                proposed_changes_buffers,
18262                self.project.clone(),
18263                window,
18264                cx,
18265            )
18266        });
18267
18268        window.defer(cx, move |window, cx| {
18269            workspace.update(cx, |workspace, cx| {
18270                workspace.active_pane().update(cx, |pane, cx| {
18271                    pane.add_item(
18272                        Box::new(proposed_changes_editor),
18273                        true,
18274                        true,
18275                        None,
18276                        window,
18277                        cx,
18278                    );
18279                });
18280            });
18281        });
18282    }
18283
18284    pub fn open_excerpts_in_split(
18285        &mut self,
18286        _: &OpenExcerptsSplit,
18287        window: &mut Window,
18288        cx: &mut Context<Self>,
18289    ) {
18290        self.open_excerpts_common(None, true, window, cx)
18291    }
18292
18293    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18294        self.open_excerpts_common(None, false, window, cx)
18295    }
18296
18297    fn open_excerpts_common(
18298        &mut self,
18299        jump_data: Option<JumpData>,
18300        split: bool,
18301        window: &mut Window,
18302        cx: &mut Context<Self>,
18303    ) {
18304        let Some(workspace) = self.workspace() else {
18305            cx.propagate();
18306            return;
18307        };
18308
18309        if self.buffer.read(cx).is_singleton() {
18310            cx.propagate();
18311            return;
18312        }
18313
18314        let mut new_selections_by_buffer = HashMap::default();
18315        match &jump_data {
18316            Some(JumpData::MultiBufferPoint {
18317                excerpt_id,
18318                position,
18319                anchor,
18320                line_offset_from_top,
18321            }) => {
18322                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18323                if let Some(buffer) = multi_buffer_snapshot
18324                    .buffer_id_for_excerpt(*excerpt_id)
18325                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18326                {
18327                    let buffer_snapshot = buffer.read(cx).snapshot();
18328                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18329                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18330                    } else {
18331                        buffer_snapshot.clip_point(*position, Bias::Left)
18332                    };
18333                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18334                    new_selections_by_buffer.insert(
18335                        buffer,
18336                        (
18337                            vec![jump_to_offset..jump_to_offset],
18338                            Some(*line_offset_from_top),
18339                        ),
18340                    );
18341                }
18342            }
18343            Some(JumpData::MultiBufferRow {
18344                row,
18345                line_offset_from_top,
18346            }) => {
18347                let point = MultiBufferPoint::new(row.0, 0);
18348                if let Some((buffer, buffer_point, _)) =
18349                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18350                {
18351                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18352                    new_selections_by_buffer
18353                        .entry(buffer)
18354                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18355                        .0
18356                        .push(buffer_offset..buffer_offset)
18357                }
18358            }
18359            None => {
18360                let selections = self.selections.all::<usize>(cx);
18361                let multi_buffer = self.buffer.read(cx);
18362                for selection in selections {
18363                    for (snapshot, range, _, anchor) in multi_buffer
18364                        .snapshot(cx)
18365                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18366                    {
18367                        if let Some(anchor) = anchor {
18368                            // selection is in a deleted hunk
18369                            let Some(buffer_id) = anchor.buffer_id else {
18370                                continue;
18371                            };
18372                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18373                                continue;
18374                            };
18375                            let offset = text::ToOffset::to_offset(
18376                                &anchor.text_anchor,
18377                                &buffer_handle.read(cx).snapshot(),
18378                            );
18379                            let range = offset..offset;
18380                            new_selections_by_buffer
18381                                .entry(buffer_handle)
18382                                .or_insert((Vec::new(), None))
18383                                .0
18384                                .push(range)
18385                        } else {
18386                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18387                            else {
18388                                continue;
18389                            };
18390                            new_selections_by_buffer
18391                                .entry(buffer_handle)
18392                                .or_insert((Vec::new(), None))
18393                                .0
18394                                .push(range)
18395                        }
18396                    }
18397                }
18398            }
18399        }
18400
18401        new_selections_by_buffer
18402            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18403
18404        if new_selections_by_buffer.is_empty() {
18405            return;
18406        }
18407
18408        // We defer the pane interaction because we ourselves are a workspace item
18409        // and activating a new item causes the pane to call a method on us reentrantly,
18410        // which panics if we're on the stack.
18411        window.defer(cx, move |window, cx| {
18412            workspace.update(cx, |workspace, cx| {
18413                let pane = if split {
18414                    workspace.adjacent_pane(window, cx)
18415                } else {
18416                    workspace.active_pane().clone()
18417                };
18418
18419                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18420                    let editor = buffer
18421                        .read(cx)
18422                        .file()
18423                        .is_none()
18424                        .then(|| {
18425                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18426                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18427                            // Instead, we try to activate the existing editor in the pane first.
18428                            let (editor, pane_item_index) =
18429                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18430                                    let editor = item.downcast::<Editor>()?;
18431                                    let singleton_buffer =
18432                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18433                                    if singleton_buffer == buffer {
18434                                        Some((editor, i))
18435                                    } else {
18436                                        None
18437                                    }
18438                                })?;
18439                            pane.update(cx, |pane, cx| {
18440                                pane.activate_item(pane_item_index, true, true, window, cx)
18441                            });
18442                            Some(editor)
18443                        })
18444                        .flatten()
18445                        .unwrap_or_else(|| {
18446                            workspace.open_project_item::<Self>(
18447                                pane.clone(),
18448                                buffer,
18449                                true,
18450                                true,
18451                                window,
18452                                cx,
18453                            )
18454                        });
18455
18456                    editor.update(cx, |editor, cx| {
18457                        let autoscroll = match scroll_offset {
18458                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18459                            None => Autoscroll::newest(),
18460                        };
18461                        let nav_history = editor.nav_history.take();
18462                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18463                            s.select_ranges(ranges);
18464                        });
18465                        editor.nav_history = nav_history;
18466                    });
18467                }
18468            })
18469        });
18470    }
18471
18472    // For now, don't allow opening excerpts in buffers that aren't backed by
18473    // regular project files.
18474    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18475        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18476    }
18477
18478    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18479        let snapshot = self.buffer.read(cx).read(cx);
18480        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18481        Some(
18482            ranges
18483                .iter()
18484                .map(move |range| {
18485                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18486                })
18487                .collect(),
18488        )
18489    }
18490
18491    fn selection_replacement_ranges(
18492        &self,
18493        range: Range<OffsetUtf16>,
18494        cx: &mut App,
18495    ) -> Vec<Range<OffsetUtf16>> {
18496        let selections = self.selections.all::<OffsetUtf16>(cx);
18497        let newest_selection = selections
18498            .iter()
18499            .max_by_key(|selection| selection.id)
18500            .unwrap();
18501        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18502        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18503        let snapshot = self.buffer.read(cx).read(cx);
18504        selections
18505            .into_iter()
18506            .map(|mut selection| {
18507                selection.start.0 =
18508                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18509                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18510                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18511                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18512            })
18513            .collect()
18514    }
18515
18516    fn report_editor_event(
18517        &self,
18518        event_type: &'static str,
18519        file_extension: Option<String>,
18520        cx: &App,
18521    ) {
18522        if cfg!(any(test, feature = "test-support")) {
18523            return;
18524        }
18525
18526        let Some(project) = &self.project else { return };
18527
18528        // If None, we are in a file without an extension
18529        let file = self
18530            .buffer
18531            .read(cx)
18532            .as_singleton()
18533            .and_then(|b| b.read(cx).file());
18534        let file_extension = file_extension.or(file
18535            .as_ref()
18536            .and_then(|file| Path::new(file.file_name(cx)).extension())
18537            .and_then(|e| e.to_str())
18538            .map(|a| a.to_string()));
18539
18540        let vim_mode = vim_enabled(cx);
18541
18542        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18543        let copilot_enabled = edit_predictions_provider
18544            == language::language_settings::EditPredictionProvider::Copilot;
18545        let copilot_enabled_for_language = self
18546            .buffer
18547            .read(cx)
18548            .language_settings(cx)
18549            .show_edit_predictions;
18550
18551        let project = project.read(cx);
18552        telemetry::event!(
18553            event_type,
18554            file_extension,
18555            vim_mode,
18556            copilot_enabled,
18557            copilot_enabled_for_language,
18558            edit_predictions_provider,
18559            is_via_ssh = project.is_via_ssh(),
18560        );
18561    }
18562
18563    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18564    /// with each line being an array of {text, highlight} objects.
18565    fn copy_highlight_json(
18566        &mut self,
18567        _: &CopyHighlightJson,
18568        window: &mut Window,
18569        cx: &mut Context<Self>,
18570    ) {
18571        #[derive(Serialize)]
18572        struct Chunk<'a> {
18573            text: String,
18574            highlight: Option<&'a str>,
18575        }
18576
18577        let snapshot = self.buffer.read(cx).snapshot(cx);
18578        let range = self
18579            .selected_text_range(false, window, cx)
18580            .and_then(|selection| {
18581                if selection.range.is_empty() {
18582                    None
18583                } else {
18584                    Some(selection.range)
18585                }
18586            })
18587            .unwrap_or_else(|| 0..snapshot.len());
18588
18589        let chunks = snapshot.chunks(range, true);
18590        let mut lines = Vec::new();
18591        let mut line: VecDeque<Chunk> = VecDeque::new();
18592
18593        let Some(style) = self.style.as_ref() else {
18594            return;
18595        };
18596
18597        for chunk in chunks {
18598            let highlight = chunk
18599                .syntax_highlight_id
18600                .and_then(|id| id.name(&style.syntax));
18601            let mut chunk_lines = chunk.text.split('\n').peekable();
18602            while let Some(text) = chunk_lines.next() {
18603                let mut merged_with_last_token = false;
18604                if let Some(last_token) = line.back_mut() {
18605                    if last_token.highlight == highlight {
18606                        last_token.text.push_str(text);
18607                        merged_with_last_token = true;
18608                    }
18609                }
18610
18611                if !merged_with_last_token {
18612                    line.push_back(Chunk {
18613                        text: text.into(),
18614                        highlight,
18615                    });
18616                }
18617
18618                if chunk_lines.peek().is_some() {
18619                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18620                        line.pop_front();
18621                    }
18622                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18623                        line.pop_back();
18624                    }
18625
18626                    lines.push(mem::take(&mut line));
18627                }
18628            }
18629        }
18630
18631        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18632            return;
18633        };
18634        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18635    }
18636
18637    pub fn open_context_menu(
18638        &mut self,
18639        _: &OpenContextMenu,
18640        window: &mut Window,
18641        cx: &mut Context<Self>,
18642    ) {
18643        self.request_autoscroll(Autoscroll::newest(), cx);
18644        let position = self.selections.newest_display(cx).start;
18645        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18646    }
18647
18648    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18649        &self.inlay_hint_cache
18650    }
18651
18652    pub fn replay_insert_event(
18653        &mut self,
18654        text: &str,
18655        relative_utf16_range: Option<Range<isize>>,
18656        window: &mut Window,
18657        cx: &mut Context<Self>,
18658    ) {
18659        if !self.input_enabled {
18660            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18661            return;
18662        }
18663        if let Some(relative_utf16_range) = relative_utf16_range {
18664            let selections = self.selections.all::<OffsetUtf16>(cx);
18665            self.change_selections(None, window, cx, |s| {
18666                let new_ranges = selections.into_iter().map(|range| {
18667                    let start = OffsetUtf16(
18668                        range
18669                            .head()
18670                            .0
18671                            .saturating_add_signed(relative_utf16_range.start),
18672                    );
18673                    let end = OffsetUtf16(
18674                        range
18675                            .head()
18676                            .0
18677                            .saturating_add_signed(relative_utf16_range.end),
18678                    );
18679                    start..end
18680                });
18681                s.select_ranges(new_ranges);
18682            });
18683        }
18684
18685        self.handle_input(text, window, cx);
18686    }
18687
18688    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18689        let Some(provider) = self.semantics_provider.as_ref() else {
18690            return false;
18691        };
18692
18693        let mut supports = false;
18694        self.buffer().update(cx, |this, cx| {
18695            this.for_each_buffer(|buffer| {
18696                supports |= provider.supports_inlay_hints(buffer, cx);
18697            });
18698        });
18699
18700        supports
18701    }
18702
18703    pub fn is_focused(&self, window: &Window) -> bool {
18704        self.focus_handle.is_focused(window)
18705    }
18706
18707    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18708        cx.emit(EditorEvent::Focused);
18709
18710        if let Some(descendant) = self
18711            .last_focused_descendant
18712            .take()
18713            .and_then(|descendant| descendant.upgrade())
18714        {
18715            window.focus(&descendant);
18716        } else {
18717            if let Some(blame) = self.blame.as_ref() {
18718                blame.update(cx, GitBlame::focus)
18719            }
18720
18721            self.blink_manager.update(cx, BlinkManager::enable);
18722            self.show_cursor_names(window, cx);
18723            self.buffer.update(cx, |buffer, cx| {
18724                buffer.finalize_last_transaction(cx);
18725                if self.leader_id.is_none() {
18726                    buffer.set_active_selections(
18727                        &self.selections.disjoint_anchors(),
18728                        self.selections.line_mode,
18729                        self.cursor_shape,
18730                        cx,
18731                    );
18732                }
18733            });
18734        }
18735    }
18736
18737    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18738        cx.emit(EditorEvent::FocusedIn)
18739    }
18740
18741    fn handle_focus_out(
18742        &mut self,
18743        event: FocusOutEvent,
18744        _window: &mut Window,
18745        cx: &mut Context<Self>,
18746    ) {
18747        if event.blurred != self.focus_handle {
18748            self.last_focused_descendant = Some(event.blurred);
18749        }
18750        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18751    }
18752
18753    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18754        self.blink_manager.update(cx, BlinkManager::disable);
18755        self.buffer
18756            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18757
18758        if let Some(blame) = self.blame.as_ref() {
18759            blame.update(cx, GitBlame::blur)
18760        }
18761        if !self.hover_state.focused(window, cx) {
18762            hide_hover(self, cx);
18763        }
18764        if !self
18765            .context_menu
18766            .borrow()
18767            .as_ref()
18768            .is_some_and(|context_menu| context_menu.focused(window, cx))
18769        {
18770            self.hide_context_menu(window, cx);
18771        }
18772        self.discard_inline_completion(false, cx);
18773        cx.emit(EditorEvent::Blurred);
18774        cx.notify();
18775    }
18776
18777    pub fn register_action<A: Action>(
18778        &mut self,
18779        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18780    ) -> Subscription {
18781        let id = self.next_editor_action_id.post_inc();
18782        let listener = Arc::new(listener);
18783        self.editor_actions.borrow_mut().insert(
18784            id,
18785            Box::new(move |window, _| {
18786                let listener = listener.clone();
18787                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18788                    let action = action.downcast_ref().unwrap();
18789                    if phase == DispatchPhase::Bubble {
18790                        listener(action, window, cx)
18791                    }
18792                })
18793            }),
18794        );
18795
18796        let editor_actions = self.editor_actions.clone();
18797        Subscription::new(move || {
18798            editor_actions.borrow_mut().remove(&id);
18799        })
18800    }
18801
18802    pub fn file_header_size(&self) -> u32 {
18803        FILE_HEADER_HEIGHT
18804    }
18805
18806    pub fn restore(
18807        &mut self,
18808        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18809        window: &mut Window,
18810        cx: &mut Context<Self>,
18811    ) {
18812        let workspace = self.workspace();
18813        let project = self.project.as_ref();
18814        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18815            let mut tasks = Vec::new();
18816            for (buffer_id, changes) in revert_changes {
18817                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18818                    buffer.update(cx, |buffer, cx| {
18819                        buffer.edit(
18820                            changes
18821                                .into_iter()
18822                                .map(|(range, text)| (range, text.to_string())),
18823                            None,
18824                            cx,
18825                        );
18826                    });
18827
18828                    if let Some(project) =
18829                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18830                    {
18831                        project.update(cx, |project, cx| {
18832                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18833                        })
18834                    }
18835                }
18836            }
18837            tasks
18838        });
18839        cx.spawn_in(window, async move |_, cx| {
18840            for (buffer, task) in save_tasks {
18841                let result = task.await;
18842                if result.is_err() {
18843                    let Some(path) = buffer
18844                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18845                        .ok()
18846                    else {
18847                        continue;
18848                    };
18849                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18850                        let Some(task) = cx
18851                            .update_window_entity(&workspace, |workspace, window, cx| {
18852                                workspace
18853                                    .open_path_preview(path, None, false, false, false, window, cx)
18854                            })
18855                            .ok()
18856                        else {
18857                            continue;
18858                        };
18859                        task.await.log_err();
18860                    }
18861                }
18862            }
18863        })
18864        .detach();
18865        self.change_selections(None, window, cx, |selections| selections.refresh());
18866    }
18867
18868    pub fn to_pixel_point(
18869        &self,
18870        source: multi_buffer::Anchor,
18871        editor_snapshot: &EditorSnapshot,
18872        window: &mut Window,
18873    ) -> Option<gpui::Point<Pixels>> {
18874        let source_point = source.to_display_point(editor_snapshot);
18875        self.display_to_pixel_point(source_point, editor_snapshot, window)
18876    }
18877
18878    pub fn display_to_pixel_point(
18879        &self,
18880        source: DisplayPoint,
18881        editor_snapshot: &EditorSnapshot,
18882        window: &mut Window,
18883    ) -> Option<gpui::Point<Pixels>> {
18884        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18885        let text_layout_details = self.text_layout_details(window);
18886        let scroll_top = text_layout_details
18887            .scroll_anchor
18888            .scroll_position(editor_snapshot)
18889            .y;
18890
18891        if source.row().as_f32() < scroll_top.floor() {
18892            return None;
18893        }
18894        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18895        let source_y = line_height * (source.row().as_f32() - scroll_top);
18896        Some(gpui::Point::new(source_x, source_y))
18897    }
18898
18899    pub fn has_visible_completions_menu(&self) -> bool {
18900        !self.edit_prediction_preview_is_active()
18901            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18902                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18903            })
18904    }
18905
18906    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18907        if self.mode.is_minimap() {
18908            return;
18909        }
18910        self.addons
18911            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18912    }
18913
18914    pub fn unregister_addon<T: Addon>(&mut self) {
18915        self.addons.remove(&std::any::TypeId::of::<T>());
18916    }
18917
18918    pub fn addon<T: Addon>(&self) -> Option<&T> {
18919        let type_id = std::any::TypeId::of::<T>();
18920        self.addons
18921            .get(&type_id)
18922            .and_then(|item| item.to_any().downcast_ref::<T>())
18923    }
18924
18925    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18926        let type_id = std::any::TypeId::of::<T>();
18927        self.addons
18928            .get_mut(&type_id)
18929            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18930    }
18931
18932    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18933        let text_layout_details = self.text_layout_details(window);
18934        let style = &text_layout_details.editor_style;
18935        let font_id = window.text_system().resolve_font(&style.text.font());
18936        let font_size = style.text.font_size.to_pixels(window.rem_size());
18937        let line_height = style.text.line_height_in_pixels(window.rem_size());
18938        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18939
18940        gpui::Size::new(em_width, line_height)
18941    }
18942
18943    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18944        self.load_diff_task.clone()
18945    }
18946
18947    fn read_metadata_from_db(
18948        &mut self,
18949        item_id: u64,
18950        workspace_id: WorkspaceId,
18951        window: &mut Window,
18952        cx: &mut Context<Editor>,
18953    ) {
18954        if self.is_singleton(cx)
18955            && !self.mode.is_minimap()
18956            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18957        {
18958            let buffer_snapshot = OnceCell::new();
18959
18960            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18961                if !folds.is_empty() {
18962                    let snapshot =
18963                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18964                    self.fold_ranges(
18965                        folds
18966                            .into_iter()
18967                            .map(|(start, end)| {
18968                                snapshot.clip_offset(start, Bias::Left)
18969                                    ..snapshot.clip_offset(end, Bias::Right)
18970                            })
18971                            .collect(),
18972                        false,
18973                        window,
18974                        cx,
18975                    );
18976                }
18977            }
18978
18979            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18980                if !selections.is_empty() {
18981                    let snapshot =
18982                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18983                    self.change_selections(None, window, cx, |s| {
18984                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18985                            snapshot.clip_offset(start, Bias::Left)
18986                                ..snapshot.clip_offset(end, Bias::Right)
18987                        }));
18988                    });
18989                }
18990            };
18991        }
18992
18993        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18994    }
18995}
18996
18997fn vim_enabled(cx: &App) -> bool {
18998    cx.global::<SettingsStore>()
18999        .raw_user_settings()
19000        .get("vim_mode")
19001        == Some(&serde_json::Value::Bool(true))
19002}
19003
19004// Consider user intent and default settings
19005fn choose_completion_range(
19006    completion: &Completion,
19007    intent: CompletionIntent,
19008    buffer: &Entity<Buffer>,
19009    cx: &mut Context<Editor>,
19010) -> Range<usize> {
19011    fn should_replace(
19012        completion: &Completion,
19013        insert_range: &Range<text::Anchor>,
19014        intent: CompletionIntent,
19015        completion_mode_setting: LspInsertMode,
19016        buffer: &Buffer,
19017    ) -> bool {
19018        // specific actions take precedence over settings
19019        match intent {
19020            CompletionIntent::CompleteWithInsert => return false,
19021            CompletionIntent::CompleteWithReplace => return true,
19022            CompletionIntent::Complete | CompletionIntent::Compose => {}
19023        }
19024
19025        match completion_mode_setting {
19026            LspInsertMode::Insert => false,
19027            LspInsertMode::Replace => true,
19028            LspInsertMode::ReplaceSubsequence => {
19029                let mut text_to_replace = buffer.chars_for_range(
19030                    buffer.anchor_before(completion.replace_range.start)
19031                        ..buffer.anchor_after(completion.replace_range.end),
19032                );
19033                let mut completion_text = completion.new_text.chars();
19034
19035                // is `text_to_replace` a subsequence of `completion_text`
19036                text_to_replace
19037                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
19038            }
19039            LspInsertMode::ReplaceSuffix => {
19040                let range_after_cursor = insert_range.end..completion.replace_range.end;
19041
19042                let text_after_cursor = buffer
19043                    .text_for_range(
19044                        buffer.anchor_before(range_after_cursor.start)
19045                            ..buffer.anchor_after(range_after_cursor.end),
19046                    )
19047                    .collect::<String>();
19048                completion.new_text.ends_with(&text_after_cursor)
19049            }
19050        }
19051    }
19052
19053    let buffer = buffer.read(cx);
19054
19055    if let CompletionSource::Lsp {
19056        insert_range: Some(insert_range),
19057        ..
19058    } = &completion.source
19059    {
19060        let completion_mode_setting =
19061            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
19062                .completions
19063                .lsp_insert_mode;
19064
19065        if !should_replace(
19066            completion,
19067            &insert_range,
19068            intent,
19069            completion_mode_setting,
19070            buffer,
19071        ) {
19072            return insert_range.to_offset(buffer);
19073        }
19074    }
19075
19076    completion.replace_range.to_offset(buffer)
19077}
19078
19079fn insert_extra_newline_brackets(
19080    buffer: &MultiBufferSnapshot,
19081    range: Range<usize>,
19082    language: &language::LanguageScope,
19083) -> bool {
19084    let leading_whitespace_len = buffer
19085        .reversed_chars_at(range.start)
19086        .take_while(|c| c.is_whitespace() && *c != '\n')
19087        .map(|c| c.len_utf8())
19088        .sum::<usize>();
19089    let trailing_whitespace_len = buffer
19090        .chars_at(range.end)
19091        .take_while(|c| c.is_whitespace() && *c != '\n')
19092        .map(|c| c.len_utf8())
19093        .sum::<usize>();
19094    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
19095
19096    language.brackets().any(|(pair, enabled)| {
19097        let pair_start = pair.start.trim_end();
19098        let pair_end = pair.end.trim_start();
19099
19100        enabled
19101            && pair.newline
19102            && buffer.contains_str_at(range.end, pair_end)
19103            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
19104    })
19105}
19106
19107fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
19108    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
19109        [(buffer, range, _)] => (*buffer, range.clone()),
19110        _ => return false,
19111    };
19112    let pair = {
19113        let mut result: Option<BracketMatch> = None;
19114
19115        for pair in buffer
19116            .all_bracket_ranges(range.clone())
19117            .filter(move |pair| {
19118                pair.open_range.start <= range.start && pair.close_range.end >= range.end
19119            })
19120        {
19121            let len = pair.close_range.end - pair.open_range.start;
19122
19123            if let Some(existing) = &result {
19124                let existing_len = existing.close_range.end - existing.open_range.start;
19125                if len > existing_len {
19126                    continue;
19127                }
19128            }
19129
19130            result = Some(pair);
19131        }
19132
19133        result
19134    };
19135    let Some(pair) = pair else {
19136        return false;
19137    };
19138    pair.newline_only
19139        && buffer
19140            .chars_for_range(pair.open_range.end..range.start)
19141            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
19142            .all(|c| c.is_whitespace() && c != '\n')
19143}
19144
19145fn update_uncommitted_diff_for_buffer(
19146    editor: Entity<Editor>,
19147    project: &Entity<Project>,
19148    buffers: impl IntoIterator<Item = Entity<Buffer>>,
19149    buffer: Entity<MultiBuffer>,
19150    cx: &mut App,
19151) -> Task<()> {
19152    let mut tasks = Vec::new();
19153    project.update(cx, |project, cx| {
19154        for buffer in buffers {
19155            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
19156                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
19157            }
19158        }
19159    });
19160    cx.spawn(async move |cx| {
19161        let diffs = future::join_all(tasks).await;
19162        if editor
19163            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
19164            .unwrap_or(false)
19165        {
19166            return;
19167        }
19168
19169        buffer
19170            .update(cx, |buffer, cx| {
19171                for diff in diffs.into_iter().flatten() {
19172                    buffer.add_diff(diff, cx);
19173                }
19174            })
19175            .ok();
19176    })
19177}
19178
19179fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
19180    let tab_size = tab_size.get() as usize;
19181    let mut width = offset;
19182
19183    for ch in text.chars() {
19184        width += if ch == '\t' {
19185            tab_size - (width % tab_size)
19186        } else {
19187            1
19188        };
19189    }
19190
19191    width - offset
19192}
19193
19194#[cfg(test)]
19195mod tests {
19196    use super::*;
19197
19198    #[test]
19199    fn test_string_size_with_expanded_tabs() {
19200        let nz = |val| NonZeroU32::new(val).unwrap();
19201        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
19202        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
19203        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
19204        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
19205        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
19206        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
19207        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
19208        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
19209    }
19210}
19211
19212/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
19213struct WordBreakingTokenizer<'a> {
19214    input: &'a str,
19215}
19216
19217impl<'a> WordBreakingTokenizer<'a> {
19218    fn new(input: &'a str) -> Self {
19219        Self { input }
19220    }
19221}
19222
19223fn is_char_ideographic(ch: char) -> bool {
19224    use unicode_script::Script::*;
19225    use unicode_script::UnicodeScript;
19226    matches!(ch.script(), Han | Tangut | Yi)
19227}
19228
19229fn is_grapheme_ideographic(text: &str) -> bool {
19230    text.chars().any(is_char_ideographic)
19231}
19232
19233fn is_grapheme_whitespace(text: &str) -> bool {
19234    text.chars().any(|x| x.is_whitespace())
19235}
19236
19237fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19238    text.chars().next().map_or(false, |ch| {
19239        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19240    })
19241}
19242
19243#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19244enum WordBreakToken<'a> {
19245    Word { token: &'a str, grapheme_len: usize },
19246    InlineWhitespace { token: &'a str, grapheme_len: usize },
19247    Newline,
19248}
19249
19250impl<'a> Iterator for WordBreakingTokenizer<'a> {
19251    /// Yields a span, the count of graphemes in the token, and whether it was
19252    /// whitespace. Note that it also breaks at word boundaries.
19253    type Item = WordBreakToken<'a>;
19254
19255    fn next(&mut self) -> Option<Self::Item> {
19256        use unicode_segmentation::UnicodeSegmentation;
19257        if self.input.is_empty() {
19258            return None;
19259        }
19260
19261        let mut iter = self.input.graphemes(true).peekable();
19262        let mut offset = 0;
19263        let mut grapheme_len = 0;
19264        if let Some(first_grapheme) = iter.next() {
19265            let is_newline = first_grapheme == "\n";
19266            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19267            offset += first_grapheme.len();
19268            grapheme_len += 1;
19269            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19270                if let Some(grapheme) = iter.peek().copied() {
19271                    if should_stay_with_preceding_ideograph(grapheme) {
19272                        offset += grapheme.len();
19273                        grapheme_len += 1;
19274                    }
19275                }
19276            } else {
19277                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19278                let mut next_word_bound = words.peek().copied();
19279                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19280                    next_word_bound = words.next();
19281                }
19282                while let Some(grapheme) = iter.peek().copied() {
19283                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19284                        break;
19285                    };
19286                    if is_grapheme_whitespace(grapheme) != is_whitespace
19287                        || (grapheme == "\n") != is_newline
19288                    {
19289                        break;
19290                    };
19291                    offset += grapheme.len();
19292                    grapheme_len += 1;
19293                    iter.next();
19294                }
19295            }
19296            let token = &self.input[..offset];
19297            self.input = &self.input[offset..];
19298            if token == "\n" {
19299                Some(WordBreakToken::Newline)
19300            } else if is_whitespace {
19301                Some(WordBreakToken::InlineWhitespace {
19302                    token,
19303                    grapheme_len,
19304                })
19305            } else {
19306                Some(WordBreakToken::Word {
19307                    token,
19308                    grapheme_len,
19309                })
19310            }
19311        } else {
19312            None
19313        }
19314    }
19315}
19316
19317#[test]
19318fn test_word_breaking_tokenizer() {
19319    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19320        ("", &[]),
19321        ("  ", &[whitespace("  ", 2)]),
19322        ("Ʒ", &[word("Ʒ", 1)]),
19323        ("Ǽ", &[word("Ǽ", 1)]),
19324        ("", &[word("", 1)]),
19325        ("⋑⋑", &[word("⋑⋑", 2)]),
19326        (
19327            "原理,进而",
19328            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19329        ),
19330        (
19331            "hello world",
19332            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19333        ),
19334        (
19335            "hello, world",
19336            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19337        ),
19338        (
19339            "  hello world",
19340            &[
19341                whitespace("  ", 2),
19342                word("hello", 5),
19343                whitespace(" ", 1),
19344                word("world", 5),
19345            ],
19346        ),
19347        (
19348            "这是什么 \n 钢笔",
19349            &[
19350                word("", 1),
19351                word("", 1),
19352                word("", 1),
19353                word("", 1),
19354                whitespace(" ", 1),
19355                newline(),
19356                whitespace(" ", 1),
19357                word("", 1),
19358                word("", 1),
19359            ],
19360        ),
19361        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19362    ];
19363
19364    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19365        WordBreakToken::Word {
19366            token,
19367            grapheme_len,
19368        }
19369    }
19370
19371    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19372        WordBreakToken::InlineWhitespace {
19373            token,
19374            grapheme_len,
19375        }
19376    }
19377
19378    fn newline() -> WordBreakToken<'static> {
19379        WordBreakToken::Newline
19380    }
19381
19382    for (input, result) in tests {
19383        assert_eq!(
19384            WordBreakingTokenizer::new(input)
19385                .collect::<Vec<_>>()
19386                .as_slice(),
19387            *result,
19388        );
19389    }
19390}
19391
19392fn wrap_with_prefix(
19393    line_prefix: String,
19394    unwrapped_text: String,
19395    wrap_column: usize,
19396    tab_size: NonZeroU32,
19397    preserve_existing_whitespace: bool,
19398) -> String {
19399    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19400    let mut wrapped_text = String::new();
19401    let mut current_line = line_prefix.clone();
19402
19403    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19404    let mut current_line_len = line_prefix_len;
19405    let mut in_whitespace = false;
19406    for token in tokenizer {
19407        let have_preceding_whitespace = in_whitespace;
19408        match token {
19409            WordBreakToken::Word {
19410                token,
19411                grapheme_len,
19412            } => {
19413                in_whitespace = false;
19414                if current_line_len + grapheme_len > wrap_column
19415                    && current_line_len != line_prefix_len
19416                {
19417                    wrapped_text.push_str(current_line.trim_end());
19418                    wrapped_text.push('\n');
19419                    current_line.truncate(line_prefix.len());
19420                    current_line_len = line_prefix_len;
19421                }
19422                current_line.push_str(token);
19423                current_line_len += grapheme_len;
19424            }
19425            WordBreakToken::InlineWhitespace {
19426                mut token,
19427                mut grapheme_len,
19428            } => {
19429                in_whitespace = true;
19430                if have_preceding_whitespace && !preserve_existing_whitespace {
19431                    continue;
19432                }
19433                if !preserve_existing_whitespace {
19434                    token = " ";
19435                    grapheme_len = 1;
19436                }
19437                if current_line_len + grapheme_len > wrap_column {
19438                    wrapped_text.push_str(current_line.trim_end());
19439                    wrapped_text.push('\n');
19440                    current_line.truncate(line_prefix.len());
19441                    current_line_len = line_prefix_len;
19442                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19443                    current_line.push_str(token);
19444                    current_line_len += grapheme_len;
19445                }
19446            }
19447            WordBreakToken::Newline => {
19448                in_whitespace = true;
19449                if preserve_existing_whitespace {
19450                    wrapped_text.push_str(current_line.trim_end());
19451                    wrapped_text.push('\n');
19452                    current_line.truncate(line_prefix.len());
19453                    current_line_len = line_prefix_len;
19454                } else if have_preceding_whitespace {
19455                    continue;
19456                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19457                {
19458                    wrapped_text.push_str(current_line.trim_end());
19459                    wrapped_text.push('\n');
19460                    current_line.truncate(line_prefix.len());
19461                    current_line_len = line_prefix_len;
19462                } else if current_line_len != line_prefix_len {
19463                    current_line.push(' ');
19464                    current_line_len += 1;
19465                }
19466            }
19467        }
19468    }
19469
19470    if !current_line.is_empty() {
19471        wrapped_text.push_str(&current_line);
19472    }
19473    wrapped_text
19474}
19475
19476#[test]
19477fn test_wrap_with_prefix() {
19478    assert_eq!(
19479        wrap_with_prefix(
19480            "# ".to_string(),
19481            "abcdefg".to_string(),
19482            4,
19483            NonZeroU32::new(4).unwrap(),
19484            false,
19485        ),
19486        "# abcdefg"
19487    );
19488    assert_eq!(
19489        wrap_with_prefix(
19490            "".to_string(),
19491            "\thello world".to_string(),
19492            8,
19493            NonZeroU32::new(4).unwrap(),
19494            false,
19495        ),
19496        "hello\nworld"
19497    );
19498    assert_eq!(
19499        wrap_with_prefix(
19500            "// ".to_string(),
19501            "xx \nyy zz aa bb cc".to_string(),
19502            12,
19503            NonZeroU32::new(4).unwrap(),
19504            false,
19505        ),
19506        "// xx yy zz\n// aa bb cc"
19507    );
19508    assert_eq!(
19509        wrap_with_prefix(
19510            String::new(),
19511            "这是什么 \n 钢笔".to_string(),
19512            3,
19513            NonZeroU32::new(4).unwrap(),
19514            false,
19515        ),
19516        "这是什\n么 钢\n"
19517    );
19518}
19519
19520pub trait CollaborationHub {
19521    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19522    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19523    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19524}
19525
19526impl CollaborationHub for Entity<Project> {
19527    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19528        self.read(cx).collaborators()
19529    }
19530
19531    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19532        self.read(cx).user_store().read(cx).participant_indices()
19533    }
19534
19535    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19536        let this = self.read(cx);
19537        let user_ids = this.collaborators().values().map(|c| c.user_id);
19538        this.user_store().read_with(cx, |user_store, cx| {
19539            user_store.participant_names(user_ids, cx)
19540        })
19541    }
19542}
19543
19544pub trait SemanticsProvider {
19545    fn hover(
19546        &self,
19547        buffer: &Entity<Buffer>,
19548        position: text::Anchor,
19549        cx: &mut App,
19550    ) -> Option<Task<Vec<project::Hover>>>;
19551
19552    fn inline_values(
19553        &self,
19554        buffer_handle: Entity<Buffer>,
19555        range: Range<text::Anchor>,
19556        cx: &mut App,
19557    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19558
19559    fn inlay_hints(
19560        &self,
19561        buffer_handle: Entity<Buffer>,
19562        range: Range<text::Anchor>,
19563        cx: &mut App,
19564    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19565
19566    fn resolve_inlay_hint(
19567        &self,
19568        hint: InlayHint,
19569        buffer_handle: Entity<Buffer>,
19570        server_id: LanguageServerId,
19571        cx: &mut App,
19572    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19573
19574    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19575
19576    fn document_highlights(
19577        &self,
19578        buffer: &Entity<Buffer>,
19579        position: text::Anchor,
19580        cx: &mut App,
19581    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19582
19583    fn definitions(
19584        &self,
19585        buffer: &Entity<Buffer>,
19586        position: text::Anchor,
19587        kind: GotoDefinitionKind,
19588        cx: &mut App,
19589    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19590
19591    fn range_for_rename(
19592        &self,
19593        buffer: &Entity<Buffer>,
19594        position: text::Anchor,
19595        cx: &mut App,
19596    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19597
19598    fn perform_rename(
19599        &self,
19600        buffer: &Entity<Buffer>,
19601        position: text::Anchor,
19602        new_name: String,
19603        cx: &mut App,
19604    ) -> Option<Task<Result<ProjectTransaction>>>;
19605}
19606
19607pub trait CompletionProvider {
19608    fn completions(
19609        &self,
19610        excerpt_id: ExcerptId,
19611        buffer: &Entity<Buffer>,
19612        buffer_position: text::Anchor,
19613        trigger: CompletionContext,
19614        window: &mut Window,
19615        cx: &mut Context<Editor>,
19616    ) -> Task<Result<Option<Vec<Completion>>>>;
19617
19618    fn resolve_completions(
19619        &self,
19620        buffer: Entity<Buffer>,
19621        completion_indices: Vec<usize>,
19622        completions: Rc<RefCell<Box<[Completion]>>>,
19623        cx: &mut Context<Editor>,
19624    ) -> Task<Result<bool>>;
19625
19626    fn apply_additional_edits_for_completion(
19627        &self,
19628        _buffer: Entity<Buffer>,
19629        _completions: Rc<RefCell<Box<[Completion]>>>,
19630        _completion_index: usize,
19631        _push_to_history: bool,
19632        _cx: &mut Context<Editor>,
19633    ) -> Task<Result<Option<language::Transaction>>> {
19634        Task::ready(Ok(None))
19635    }
19636
19637    fn is_completion_trigger(
19638        &self,
19639        buffer: &Entity<Buffer>,
19640        position: language::Anchor,
19641        text: &str,
19642        trigger_in_words: bool,
19643        cx: &mut Context<Editor>,
19644    ) -> bool;
19645
19646    fn sort_completions(&self) -> bool {
19647        true
19648    }
19649
19650    fn filter_completions(&self) -> bool {
19651        true
19652    }
19653}
19654
19655pub trait CodeActionProvider {
19656    fn id(&self) -> Arc<str>;
19657
19658    fn code_actions(
19659        &self,
19660        buffer: &Entity<Buffer>,
19661        range: Range<text::Anchor>,
19662        window: &mut Window,
19663        cx: &mut App,
19664    ) -> Task<Result<Vec<CodeAction>>>;
19665
19666    fn apply_code_action(
19667        &self,
19668        buffer_handle: Entity<Buffer>,
19669        action: CodeAction,
19670        excerpt_id: ExcerptId,
19671        push_to_history: bool,
19672        window: &mut Window,
19673        cx: &mut App,
19674    ) -> Task<Result<ProjectTransaction>>;
19675}
19676
19677impl CodeActionProvider for Entity<Project> {
19678    fn id(&self) -> Arc<str> {
19679        "project".into()
19680    }
19681
19682    fn code_actions(
19683        &self,
19684        buffer: &Entity<Buffer>,
19685        range: Range<text::Anchor>,
19686        _window: &mut Window,
19687        cx: &mut App,
19688    ) -> Task<Result<Vec<CodeAction>>> {
19689        self.update(cx, |project, cx| {
19690            let code_lens = project.code_lens(buffer, range.clone(), cx);
19691            let code_actions = project.code_actions(buffer, range, None, cx);
19692            cx.background_spawn(async move {
19693                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19694                Ok(code_lens
19695                    .context("code lens fetch")?
19696                    .into_iter()
19697                    .chain(code_actions.context("code action fetch")?)
19698                    .collect())
19699            })
19700        })
19701    }
19702
19703    fn apply_code_action(
19704        &self,
19705        buffer_handle: Entity<Buffer>,
19706        action: CodeAction,
19707        _excerpt_id: ExcerptId,
19708        push_to_history: bool,
19709        _window: &mut Window,
19710        cx: &mut App,
19711    ) -> Task<Result<ProjectTransaction>> {
19712        self.update(cx, |project, cx| {
19713            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19714        })
19715    }
19716}
19717
19718fn snippet_completions(
19719    project: &Project,
19720    buffer: &Entity<Buffer>,
19721    buffer_position: text::Anchor,
19722    cx: &mut App,
19723) -> Task<Result<Vec<Completion>>> {
19724    let languages = buffer.read(cx).languages_at(buffer_position);
19725    let snippet_store = project.snippets().read(cx);
19726
19727    let scopes: Vec<_> = languages
19728        .iter()
19729        .filter_map(|language| {
19730            let language_name = language.lsp_id();
19731            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19732
19733            if snippets.is_empty() {
19734                None
19735            } else {
19736                Some((language.default_scope(), snippets))
19737            }
19738        })
19739        .collect();
19740
19741    if scopes.is_empty() {
19742        return Task::ready(Ok(vec![]));
19743    }
19744
19745    let snapshot = buffer.read(cx).text_snapshot();
19746    let chars: String = snapshot
19747        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19748        .collect();
19749    let executor = cx.background_executor().clone();
19750
19751    cx.background_spawn(async move {
19752        let mut all_results: Vec<Completion> = Vec::new();
19753        for (scope, snippets) in scopes.into_iter() {
19754            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19755            let mut last_word = chars
19756                .chars()
19757                .take_while(|c| classifier.is_word(*c))
19758                .collect::<String>();
19759            last_word = last_word.chars().rev().collect();
19760
19761            if last_word.is_empty() {
19762                return Ok(vec![]);
19763            }
19764
19765            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19766            let to_lsp = |point: &text::Anchor| {
19767                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19768                point_to_lsp(end)
19769            };
19770            let lsp_end = to_lsp(&buffer_position);
19771
19772            let candidates = snippets
19773                .iter()
19774                .enumerate()
19775                .flat_map(|(ix, snippet)| {
19776                    snippet
19777                        .prefix
19778                        .iter()
19779                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19780                })
19781                .collect::<Vec<StringMatchCandidate>>();
19782
19783            let mut matches = fuzzy::match_strings(
19784                &candidates,
19785                &last_word,
19786                last_word.chars().any(|c| c.is_uppercase()),
19787                100,
19788                &Default::default(),
19789                executor.clone(),
19790            )
19791            .await;
19792
19793            // Remove all candidates where the query's start does not match the start of any word in the candidate
19794            if let Some(query_start) = last_word.chars().next() {
19795                matches.retain(|string_match| {
19796                    split_words(&string_match.string).any(|word| {
19797                        // Check that the first codepoint of the word as lowercase matches the first
19798                        // codepoint of the query as lowercase
19799                        word.chars()
19800                            .flat_map(|codepoint| codepoint.to_lowercase())
19801                            .zip(query_start.to_lowercase())
19802                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19803                    })
19804                });
19805            }
19806
19807            let matched_strings = matches
19808                .into_iter()
19809                .map(|m| m.string)
19810                .collect::<HashSet<_>>();
19811
19812            let mut result: Vec<Completion> = snippets
19813                .iter()
19814                .filter_map(|snippet| {
19815                    let matching_prefix = snippet
19816                        .prefix
19817                        .iter()
19818                        .find(|prefix| matched_strings.contains(*prefix))?;
19819                    let start = as_offset - last_word.len();
19820                    let start = snapshot.anchor_before(start);
19821                    let range = start..buffer_position;
19822                    let lsp_start = to_lsp(&start);
19823                    let lsp_range = lsp::Range {
19824                        start: lsp_start,
19825                        end: lsp_end,
19826                    };
19827                    Some(Completion {
19828                        replace_range: range,
19829                        new_text: snippet.body.clone(),
19830                        source: CompletionSource::Lsp {
19831                            insert_range: None,
19832                            server_id: LanguageServerId(usize::MAX),
19833                            resolved: true,
19834                            lsp_completion: Box::new(lsp::CompletionItem {
19835                                label: snippet.prefix.first().unwrap().clone(),
19836                                kind: Some(CompletionItemKind::SNIPPET),
19837                                label_details: snippet.description.as_ref().map(|description| {
19838                                    lsp::CompletionItemLabelDetails {
19839                                        detail: Some(description.clone()),
19840                                        description: None,
19841                                    }
19842                                }),
19843                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19844                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19845                                    lsp::InsertReplaceEdit {
19846                                        new_text: snippet.body.clone(),
19847                                        insert: lsp_range,
19848                                        replace: lsp_range,
19849                                    },
19850                                )),
19851                                filter_text: Some(snippet.body.clone()),
19852                                sort_text: Some(char::MAX.to_string()),
19853                                ..lsp::CompletionItem::default()
19854                            }),
19855                            lsp_defaults: None,
19856                        },
19857                        label: CodeLabel {
19858                            text: matching_prefix.clone(),
19859                            runs: Vec::new(),
19860                            filter_range: 0..matching_prefix.len(),
19861                        },
19862                        icon_path: None,
19863                        documentation: snippet.description.clone().map(|description| {
19864                            CompletionDocumentation::SingleLine(description.into())
19865                        }),
19866                        insert_text_mode: None,
19867                        confirm: None,
19868                    })
19869                })
19870                .collect();
19871
19872            all_results.append(&mut result);
19873        }
19874
19875        Ok(all_results)
19876    })
19877}
19878
19879impl CompletionProvider for Entity<Project> {
19880    fn completions(
19881        &self,
19882        _excerpt_id: ExcerptId,
19883        buffer: &Entity<Buffer>,
19884        buffer_position: text::Anchor,
19885        options: CompletionContext,
19886        _window: &mut Window,
19887        cx: &mut Context<Editor>,
19888    ) -> Task<Result<Option<Vec<Completion>>>> {
19889        self.update(cx, |project, cx| {
19890            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19891            let project_completions = project.completions(buffer, buffer_position, options, cx);
19892            cx.background_spawn(async move {
19893                let snippets_completions = snippets.await?;
19894                match project_completions.await? {
19895                    Some(mut completions) => {
19896                        completions.extend(snippets_completions);
19897                        Ok(Some(completions))
19898                    }
19899                    None => {
19900                        if snippets_completions.is_empty() {
19901                            Ok(None)
19902                        } else {
19903                            Ok(Some(snippets_completions))
19904                        }
19905                    }
19906                }
19907            })
19908        })
19909    }
19910
19911    fn resolve_completions(
19912        &self,
19913        buffer: Entity<Buffer>,
19914        completion_indices: Vec<usize>,
19915        completions: Rc<RefCell<Box<[Completion]>>>,
19916        cx: &mut Context<Editor>,
19917    ) -> Task<Result<bool>> {
19918        self.update(cx, |project, cx| {
19919            project.lsp_store().update(cx, |lsp_store, cx| {
19920                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19921            })
19922        })
19923    }
19924
19925    fn apply_additional_edits_for_completion(
19926        &self,
19927        buffer: Entity<Buffer>,
19928        completions: Rc<RefCell<Box<[Completion]>>>,
19929        completion_index: usize,
19930        push_to_history: bool,
19931        cx: &mut Context<Editor>,
19932    ) -> Task<Result<Option<language::Transaction>>> {
19933        self.update(cx, |project, cx| {
19934            project.lsp_store().update(cx, |lsp_store, cx| {
19935                lsp_store.apply_additional_edits_for_completion(
19936                    buffer,
19937                    completions,
19938                    completion_index,
19939                    push_to_history,
19940                    cx,
19941                )
19942            })
19943        })
19944    }
19945
19946    fn is_completion_trigger(
19947        &self,
19948        buffer: &Entity<Buffer>,
19949        position: language::Anchor,
19950        text: &str,
19951        trigger_in_words: bool,
19952        cx: &mut Context<Editor>,
19953    ) -> bool {
19954        let mut chars = text.chars();
19955        let char = if let Some(char) = chars.next() {
19956            char
19957        } else {
19958            return false;
19959        };
19960        if chars.next().is_some() {
19961            return false;
19962        }
19963
19964        let buffer = buffer.read(cx);
19965        let snapshot = buffer.snapshot();
19966        if !snapshot.settings_at(position, cx).show_completions_on_input {
19967            return false;
19968        }
19969        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19970        if trigger_in_words && classifier.is_word(char) {
19971            return true;
19972        }
19973
19974        buffer.completion_triggers().contains(text)
19975    }
19976}
19977
19978impl SemanticsProvider for Entity<Project> {
19979    fn hover(
19980        &self,
19981        buffer: &Entity<Buffer>,
19982        position: text::Anchor,
19983        cx: &mut App,
19984    ) -> Option<Task<Vec<project::Hover>>> {
19985        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19986    }
19987
19988    fn document_highlights(
19989        &self,
19990        buffer: &Entity<Buffer>,
19991        position: text::Anchor,
19992        cx: &mut App,
19993    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19994        Some(self.update(cx, |project, cx| {
19995            project.document_highlights(buffer, position, cx)
19996        }))
19997    }
19998
19999    fn definitions(
20000        &self,
20001        buffer: &Entity<Buffer>,
20002        position: text::Anchor,
20003        kind: GotoDefinitionKind,
20004        cx: &mut App,
20005    ) -> Option<Task<Result<Vec<LocationLink>>>> {
20006        Some(self.update(cx, |project, cx| match kind {
20007            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
20008            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
20009            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
20010            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
20011        }))
20012    }
20013
20014    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
20015        // TODO: make this work for remote projects
20016        self.update(cx, |project, cx| {
20017            if project
20018                .active_debug_session(cx)
20019                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
20020            {
20021                return true;
20022            }
20023
20024            buffer.update(cx, |buffer, cx| {
20025                project.any_language_server_supports_inlay_hints(buffer, cx)
20026            })
20027        })
20028    }
20029
20030    fn inline_values(
20031        &self,
20032        buffer_handle: Entity<Buffer>,
20033        range: Range<text::Anchor>,
20034        cx: &mut App,
20035    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
20036        self.update(cx, |project, cx| {
20037            let (session, active_stack_frame) = project.active_debug_session(cx)?;
20038
20039            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
20040        })
20041    }
20042
20043    fn inlay_hints(
20044        &self,
20045        buffer_handle: Entity<Buffer>,
20046        range: Range<text::Anchor>,
20047        cx: &mut App,
20048    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
20049        Some(self.update(cx, |project, cx| {
20050            project.inlay_hints(buffer_handle, range, cx)
20051        }))
20052    }
20053
20054    fn resolve_inlay_hint(
20055        &self,
20056        hint: InlayHint,
20057        buffer_handle: Entity<Buffer>,
20058        server_id: LanguageServerId,
20059        cx: &mut App,
20060    ) -> Option<Task<anyhow::Result<InlayHint>>> {
20061        Some(self.update(cx, |project, cx| {
20062            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
20063        }))
20064    }
20065
20066    fn range_for_rename(
20067        &self,
20068        buffer: &Entity<Buffer>,
20069        position: text::Anchor,
20070        cx: &mut App,
20071    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
20072        Some(self.update(cx, |project, cx| {
20073            let buffer = buffer.clone();
20074            let task = project.prepare_rename(buffer.clone(), position, cx);
20075            cx.spawn(async move |_, cx| {
20076                Ok(match task.await? {
20077                    PrepareRenameResponse::Success(range) => Some(range),
20078                    PrepareRenameResponse::InvalidPosition => None,
20079                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
20080                        // Fallback on using TreeSitter info to determine identifier range
20081                        buffer.update(cx, |buffer, _| {
20082                            let snapshot = buffer.snapshot();
20083                            let (range, kind) = snapshot.surrounding_word(position);
20084                            if kind != Some(CharKind::Word) {
20085                                return None;
20086                            }
20087                            Some(
20088                                snapshot.anchor_before(range.start)
20089                                    ..snapshot.anchor_after(range.end),
20090                            )
20091                        })?
20092                    }
20093                })
20094            })
20095        }))
20096    }
20097
20098    fn perform_rename(
20099        &self,
20100        buffer: &Entity<Buffer>,
20101        position: text::Anchor,
20102        new_name: String,
20103        cx: &mut App,
20104    ) -> Option<Task<Result<ProjectTransaction>>> {
20105        Some(self.update(cx, |project, cx| {
20106            project.perform_rename(buffer.clone(), position, new_name, cx)
20107        }))
20108    }
20109}
20110
20111fn inlay_hint_settings(
20112    location: Anchor,
20113    snapshot: &MultiBufferSnapshot,
20114    cx: &mut Context<Editor>,
20115) -> InlayHintSettings {
20116    let file = snapshot.file_at(location);
20117    let language = snapshot.language_at(location).map(|l| l.name());
20118    language_settings(language, file, cx).inlay_hints
20119}
20120
20121fn consume_contiguous_rows(
20122    contiguous_row_selections: &mut Vec<Selection<Point>>,
20123    selection: &Selection<Point>,
20124    display_map: &DisplaySnapshot,
20125    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
20126) -> (MultiBufferRow, MultiBufferRow) {
20127    contiguous_row_selections.push(selection.clone());
20128    let start_row = MultiBufferRow(selection.start.row);
20129    let mut end_row = ending_row(selection, display_map);
20130
20131    while let Some(next_selection) = selections.peek() {
20132        if next_selection.start.row <= end_row.0 {
20133            end_row = ending_row(next_selection, display_map);
20134            contiguous_row_selections.push(selections.next().unwrap().clone());
20135        } else {
20136            break;
20137        }
20138    }
20139    (start_row, end_row)
20140}
20141
20142fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
20143    if next_selection.end.column > 0 || next_selection.is_empty() {
20144        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
20145    } else {
20146        MultiBufferRow(next_selection.end.row)
20147    }
20148}
20149
20150impl EditorSnapshot {
20151    pub fn remote_selections_in_range<'a>(
20152        &'a self,
20153        range: &'a Range<Anchor>,
20154        collaboration_hub: &dyn CollaborationHub,
20155        cx: &'a App,
20156    ) -> impl 'a + Iterator<Item = RemoteSelection> {
20157        let participant_names = collaboration_hub.user_names(cx);
20158        let participant_indices = collaboration_hub.user_participant_indices(cx);
20159        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
20160        let collaborators_by_replica_id = collaborators_by_peer_id
20161            .iter()
20162            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
20163            .collect::<HashMap<_, _>>();
20164        self.buffer_snapshot
20165            .selections_in_range(range, false)
20166            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
20167                if replica_id == AGENT_REPLICA_ID {
20168                    Some(RemoteSelection {
20169                        replica_id,
20170                        selection,
20171                        cursor_shape,
20172                        line_mode,
20173                        collaborator_id: CollaboratorId::Agent,
20174                        user_name: Some("Agent".into()),
20175                        color: cx.theme().players().agent(),
20176                    })
20177                } else {
20178                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
20179                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
20180                    let user_name = participant_names.get(&collaborator.user_id).cloned();
20181                    Some(RemoteSelection {
20182                        replica_id,
20183                        selection,
20184                        cursor_shape,
20185                        line_mode,
20186                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
20187                        user_name,
20188                        color: if let Some(index) = participant_index {
20189                            cx.theme().players().color_for_participant(index.0)
20190                        } else {
20191                            cx.theme().players().absent()
20192                        },
20193                    })
20194                }
20195            })
20196    }
20197
20198    pub fn hunks_for_ranges(
20199        &self,
20200        ranges: impl IntoIterator<Item = Range<Point>>,
20201    ) -> Vec<MultiBufferDiffHunk> {
20202        let mut hunks = Vec::new();
20203        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
20204            HashMap::default();
20205        for query_range in ranges {
20206            let query_rows =
20207                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
20208            for hunk in self.buffer_snapshot.diff_hunks_in_range(
20209                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
20210            ) {
20211                // Include deleted hunks that are adjacent to the query range, because
20212                // otherwise they would be missed.
20213                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
20214                if hunk.status().is_deleted() {
20215                    intersects_range |= hunk.row_range.start == query_rows.end;
20216                    intersects_range |= hunk.row_range.end == query_rows.start;
20217                }
20218                if intersects_range {
20219                    if !processed_buffer_rows
20220                        .entry(hunk.buffer_id)
20221                        .or_default()
20222                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
20223                    {
20224                        continue;
20225                    }
20226                    hunks.push(hunk);
20227                }
20228            }
20229        }
20230
20231        hunks
20232    }
20233
20234    fn display_diff_hunks_for_rows<'a>(
20235        &'a self,
20236        display_rows: Range<DisplayRow>,
20237        folded_buffers: &'a HashSet<BufferId>,
20238    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20239        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20240        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20241
20242        self.buffer_snapshot
20243            .diff_hunks_in_range(buffer_start..buffer_end)
20244            .filter_map(|hunk| {
20245                if folded_buffers.contains(&hunk.buffer_id) {
20246                    return None;
20247                }
20248
20249                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20250                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20251
20252                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20253                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20254
20255                let display_hunk = if hunk_display_start.column() != 0 {
20256                    DisplayDiffHunk::Folded {
20257                        display_row: hunk_display_start.row(),
20258                    }
20259                } else {
20260                    let mut end_row = hunk_display_end.row();
20261                    if hunk_display_end.column() > 0 {
20262                        end_row.0 += 1;
20263                    }
20264                    let is_created_file = hunk.is_created_file();
20265                    DisplayDiffHunk::Unfolded {
20266                        status: hunk.status(),
20267                        diff_base_byte_range: hunk.diff_base_byte_range,
20268                        display_row_range: hunk_display_start.row()..end_row,
20269                        multi_buffer_range: Anchor::range_in_buffer(
20270                            hunk.excerpt_id,
20271                            hunk.buffer_id,
20272                            hunk.buffer_range,
20273                        ),
20274                        is_created_file,
20275                    }
20276                };
20277
20278                Some(display_hunk)
20279            })
20280    }
20281
20282    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20283        self.display_snapshot.buffer_snapshot.language_at(position)
20284    }
20285
20286    pub fn is_focused(&self) -> bool {
20287        self.is_focused
20288    }
20289
20290    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20291        self.placeholder_text.as_ref()
20292    }
20293
20294    pub fn scroll_position(&self) -> gpui::Point<f32> {
20295        self.scroll_anchor.scroll_position(&self.display_snapshot)
20296    }
20297
20298    fn gutter_dimensions(
20299        &self,
20300        font_id: FontId,
20301        font_size: Pixels,
20302        max_line_number_width: Pixels,
20303        cx: &App,
20304    ) -> Option<GutterDimensions> {
20305        if !self.show_gutter {
20306            return None;
20307        }
20308
20309        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20310        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20311
20312        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20313            matches!(
20314                ProjectSettings::get_global(cx).git.git_gutter,
20315                Some(GitGutterSetting::TrackedFiles)
20316            )
20317        });
20318        let gutter_settings = EditorSettings::get_global(cx).gutter;
20319        let show_line_numbers = self
20320            .show_line_numbers
20321            .unwrap_or(gutter_settings.line_numbers);
20322        let line_gutter_width = if show_line_numbers {
20323            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20324            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20325            max_line_number_width.max(min_width_for_number_on_gutter)
20326        } else {
20327            0.0.into()
20328        };
20329
20330        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20331        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20332
20333        let git_blame_entries_width =
20334            self.git_blame_gutter_max_author_length
20335                .map(|max_author_length| {
20336                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20337                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20338
20339                    /// The number of characters to dedicate to gaps and margins.
20340                    const SPACING_WIDTH: usize = 4;
20341
20342                    let max_char_count = max_author_length.min(renderer.max_author_length())
20343                        + ::git::SHORT_SHA_LENGTH
20344                        + MAX_RELATIVE_TIMESTAMP.len()
20345                        + SPACING_WIDTH;
20346
20347                    em_advance * max_char_count
20348                });
20349
20350        let is_singleton = self.buffer_snapshot.is_singleton();
20351
20352        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20353        left_padding += if !is_singleton {
20354            em_width * 4.0
20355        } else if show_runnables || show_breakpoints {
20356            em_width * 3.0
20357        } else if show_git_gutter && show_line_numbers {
20358            em_width * 2.0
20359        } else if show_git_gutter || show_line_numbers {
20360            em_width
20361        } else {
20362            px(0.)
20363        };
20364
20365        let shows_folds = is_singleton && gutter_settings.folds;
20366
20367        let right_padding = if shows_folds && show_line_numbers {
20368            em_width * 4.0
20369        } else if shows_folds || (!is_singleton && show_line_numbers) {
20370            em_width * 3.0
20371        } else if show_line_numbers {
20372            em_width
20373        } else {
20374            px(0.)
20375        };
20376
20377        Some(GutterDimensions {
20378            left_padding,
20379            right_padding,
20380            width: line_gutter_width + left_padding + right_padding,
20381            margin: GutterDimensions::default_gutter_margin(font_id, font_size, cx),
20382            git_blame_entries_width,
20383        })
20384    }
20385
20386    pub fn render_crease_toggle(
20387        &self,
20388        buffer_row: MultiBufferRow,
20389        row_contains_cursor: bool,
20390        editor: Entity<Editor>,
20391        window: &mut Window,
20392        cx: &mut App,
20393    ) -> Option<AnyElement> {
20394        let folded = self.is_line_folded(buffer_row);
20395        let mut is_foldable = false;
20396
20397        if let Some(crease) = self
20398            .crease_snapshot
20399            .query_row(buffer_row, &self.buffer_snapshot)
20400        {
20401            is_foldable = true;
20402            match crease {
20403                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20404                    if let Some(render_toggle) = render_toggle {
20405                        let toggle_callback =
20406                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20407                                if folded {
20408                                    editor.update(cx, |editor, cx| {
20409                                        editor.fold_at(buffer_row, window, cx)
20410                                    });
20411                                } else {
20412                                    editor.update(cx, |editor, cx| {
20413                                        editor.unfold_at(buffer_row, window, cx)
20414                                    });
20415                                }
20416                            });
20417                        return Some((render_toggle)(
20418                            buffer_row,
20419                            folded,
20420                            toggle_callback,
20421                            window,
20422                            cx,
20423                        ));
20424                    }
20425                }
20426            }
20427        }
20428
20429        is_foldable |= self.starts_indent(buffer_row);
20430
20431        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20432            Some(
20433                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20434                    .toggle_state(folded)
20435                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20436                        if folded {
20437                            this.unfold_at(buffer_row, window, cx);
20438                        } else {
20439                            this.fold_at(buffer_row, window, cx);
20440                        }
20441                    }))
20442                    .into_any_element(),
20443            )
20444        } else {
20445            None
20446        }
20447    }
20448
20449    pub fn render_crease_trailer(
20450        &self,
20451        buffer_row: MultiBufferRow,
20452        window: &mut Window,
20453        cx: &mut App,
20454    ) -> Option<AnyElement> {
20455        let folded = self.is_line_folded(buffer_row);
20456        if let Crease::Inline { render_trailer, .. } = self
20457            .crease_snapshot
20458            .query_row(buffer_row, &self.buffer_snapshot)?
20459        {
20460            let render_trailer = render_trailer.as_ref()?;
20461            Some(render_trailer(buffer_row, folded, window, cx))
20462        } else {
20463            None
20464        }
20465    }
20466}
20467
20468impl Deref for EditorSnapshot {
20469    type Target = DisplaySnapshot;
20470
20471    fn deref(&self) -> &Self::Target {
20472        &self.display_snapshot
20473    }
20474}
20475
20476#[derive(Clone, Debug, PartialEq, Eq)]
20477pub enum EditorEvent {
20478    InputIgnored {
20479        text: Arc<str>,
20480    },
20481    InputHandled {
20482        utf16_range_to_replace: Option<Range<isize>>,
20483        text: Arc<str>,
20484    },
20485    ExcerptsAdded {
20486        buffer: Entity<Buffer>,
20487        predecessor: ExcerptId,
20488        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20489    },
20490    ExcerptsRemoved {
20491        ids: Vec<ExcerptId>,
20492        removed_buffer_ids: Vec<BufferId>,
20493    },
20494    BufferFoldToggled {
20495        ids: Vec<ExcerptId>,
20496        folded: bool,
20497    },
20498    ExcerptsEdited {
20499        ids: Vec<ExcerptId>,
20500    },
20501    ExcerptsExpanded {
20502        ids: Vec<ExcerptId>,
20503    },
20504    BufferEdited,
20505    Edited {
20506        transaction_id: clock::Lamport,
20507    },
20508    Reparsed(BufferId),
20509    Focused,
20510    FocusedIn,
20511    Blurred,
20512    DirtyChanged,
20513    Saved,
20514    TitleChanged,
20515    DiffBaseChanged,
20516    SelectionsChanged {
20517        local: bool,
20518    },
20519    ScrollPositionChanged {
20520        local: bool,
20521        autoscroll: bool,
20522    },
20523    Closed,
20524    TransactionUndone {
20525        transaction_id: clock::Lamport,
20526    },
20527    TransactionBegun {
20528        transaction_id: clock::Lamport,
20529    },
20530    Reloaded,
20531    CursorShapeChanged,
20532    PushedToNavHistory {
20533        anchor: Anchor,
20534        is_deactivate: bool,
20535    },
20536}
20537
20538impl EventEmitter<EditorEvent> for Editor {}
20539
20540impl Focusable for Editor {
20541    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20542        self.focus_handle.clone()
20543    }
20544}
20545
20546impl Render for Editor {
20547    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20548        let settings = ThemeSettings::get_global(cx);
20549
20550        let mut text_style = match self.mode {
20551            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20552                color: cx.theme().colors().editor_foreground,
20553                font_family: settings.ui_font.family.clone(),
20554                font_features: settings.ui_font.features.clone(),
20555                font_fallbacks: settings.ui_font.fallbacks.clone(),
20556                font_size: rems(0.875).into(),
20557                font_weight: settings.ui_font.weight,
20558                line_height: relative(settings.buffer_line_height.value()),
20559                ..Default::default()
20560            },
20561            EditorMode::Full { .. } | EditorMode::Minimap { .. } => TextStyle {
20562                color: cx.theme().colors().editor_foreground,
20563                font_family: settings.buffer_font.family.clone(),
20564                font_features: settings.buffer_font.features.clone(),
20565                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20566                font_size: settings.buffer_font_size(cx).into(),
20567                font_weight: settings.buffer_font.weight,
20568                line_height: relative(settings.buffer_line_height.value()),
20569                ..Default::default()
20570            },
20571        };
20572        if let Some(text_style_refinement) = &self.text_style_refinement {
20573            text_style.refine(text_style_refinement)
20574        }
20575
20576        let background = match self.mode {
20577            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20578            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20579            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20580            EditorMode::Minimap { .. } => cx.theme().colors().editor_background.opacity(0.7),
20581        };
20582
20583        EditorElement::new(
20584            &cx.entity(),
20585            EditorStyle {
20586                background,
20587                local_player: cx.theme().players().local(),
20588                text: text_style,
20589                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20590                syntax: cx.theme().syntax().clone(),
20591                status: cx.theme().status().clone(),
20592                inlay_hints_style: make_inlay_hints_style(cx),
20593                inline_completion_styles: make_suggestion_styles(cx),
20594                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20595                show_underlines: !self.mode.is_minimap(),
20596            },
20597        )
20598    }
20599}
20600
20601impl EntityInputHandler for Editor {
20602    fn text_for_range(
20603        &mut self,
20604        range_utf16: Range<usize>,
20605        adjusted_range: &mut Option<Range<usize>>,
20606        _: &mut Window,
20607        cx: &mut Context<Self>,
20608    ) -> Option<String> {
20609        let snapshot = self.buffer.read(cx).read(cx);
20610        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20611        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20612        if (start.0..end.0) != range_utf16 {
20613            adjusted_range.replace(start.0..end.0);
20614        }
20615        Some(snapshot.text_for_range(start..end).collect())
20616    }
20617
20618    fn selected_text_range(
20619        &mut self,
20620        ignore_disabled_input: bool,
20621        _: &mut Window,
20622        cx: &mut Context<Self>,
20623    ) -> Option<UTF16Selection> {
20624        // Prevent the IME menu from appearing when holding down an alphabetic key
20625        // while input is disabled.
20626        if !ignore_disabled_input && !self.input_enabled {
20627            return None;
20628        }
20629
20630        let selection = self.selections.newest::<OffsetUtf16>(cx);
20631        let range = selection.range();
20632
20633        Some(UTF16Selection {
20634            range: range.start.0..range.end.0,
20635            reversed: selection.reversed,
20636        })
20637    }
20638
20639    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20640        let snapshot = self.buffer.read(cx).read(cx);
20641        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20642        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20643    }
20644
20645    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20646        self.clear_highlights::<InputComposition>(cx);
20647        self.ime_transaction.take();
20648    }
20649
20650    fn replace_text_in_range(
20651        &mut self,
20652        range_utf16: Option<Range<usize>>,
20653        text: &str,
20654        window: &mut Window,
20655        cx: &mut Context<Self>,
20656    ) {
20657        if !self.input_enabled {
20658            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20659            return;
20660        }
20661
20662        self.transact(window, cx, |this, window, cx| {
20663            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20664                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20665                Some(this.selection_replacement_ranges(range_utf16, cx))
20666            } else {
20667                this.marked_text_ranges(cx)
20668            };
20669
20670            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20671                let newest_selection_id = this.selections.newest_anchor().id;
20672                this.selections
20673                    .all::<OffsetUtf16>(cx)
20674                    .iter()
20675                    .zip(ranges_to_replace.iter())
20676                    .find_map(|(selection, range)| {
20677                        if selection.id == newest_selection_id {
20678                            Some(
20679                                (range.start.0 as isize - selection.head().0 as isize)
20680                                    ..(range.end.0 as isize - selection.head().0 as isize),
20681                            )
20682                        } else {
20683                            None
20684                        }
20685                    })
20686            });
20687
20688            cx.emit(EditorEvent::InputHandled {
20689                utf16_range_to_replace: range_to_replace,
20690                text: text.into(),
20691            });
20692
20693            if let Some(new_selected_ranges) = new_selected_ranges {
20694                this.change_selections(None, window, cx, |selections| {
20695                    selections.select_ranges(new_selected_ranges)
20696                });
20697                this.backspace(&Default::default(), window, cx);
20698            }
20699
20700            this.handle_input(text, window, cx);
20701        });
20702
20703        if let Some(transaction) = self.ime_transaction {
20704            self.buffer.update(cx, |buffer, cx| {
20705                buffer.group_until_transaction(transaction, cx);
20706            });
20707        }
20708
20709        self.unmark_text(window, cx);
20710    }
20711
20712    fn replace_and_mark_text_in_range(
20713        &mut self,
20714        range_utf16: Option<Range<usize>>,
20715        text: &str,
20716        new_selected_range_utf16: Option<Range<usize>>,
20717        window: &mut Window,
20718        cx: &mut Context<Self>,
20719    ) {
20720        if !self.input_enabled {
20721            return;
20722        }
20723
20724        let transaction = self.transact(window, cx, |this, window, cx| {
20725            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20726                let snapshot = this.buffer.read(cx).read(cx);
20727                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20728                    for marked_range in &mut marked_ranges {
20729                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20730                        marked_range.start.0 += relative_range_utf16.start;
20731                        marked_range.start =
20732                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20733                        marked_range.end =
20734                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20735                    }
20736                }
20737                Some(marked_ranges)
20738            } else if let Some(range_utf16) = range_utf16 {
20739                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20740                Some(this.selection_replacement_ranges(range_utf16, cx))
20741            } else {
20742                None
20743            };
20744
20745            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20746                let newest_selection_id = this.selections.newest_anchor().id;
20747                this.selections
20748                    .all::<OffsetUtf16>(cx)
20749                    .iter()
20750                    .zip(ranges_to_replace.iter())
20751                    .find_map(|(selection, range)| {
20752                        if selection.id == newest_selection_id {
20753                            Some(
20754                                (range.start.0 as isize - selection.head().0 as isize)
20755                                    ..(range.end.0 as isize - selection.head().0 as isize),
20756                            )
20757                        } else {
20758                            None
20759                        }
20760                    })
20761            });
20762
20763            cx.emit(EditorEvent::InputHandled {
20764                utf16_range_to_replace: range_to_replace,
20765                text: text.into(),
20766            });
20767
20768            if let Some(ranges) = ranges_to_replace {
20769                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20770            }
20771
20772            let marked_ranges = {
20773                let snapshot = this.buffer.read(cx).read(cx);
20774                this.selections
20775                    .disjoint_anchors()
20776                    .iter()
20777                    .map(|selection| {
20778                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20779                    })
20780                    .collect::<Vec<_>>()
20781            };
20782
20783            if text.is_empty() {
20784                this.unmark_text(window, cx);
20785            } else {
20786                this.highlight_text::<InputComposition>(
20787                    marked_ranges.clone(),
20788                    HighlightStyle {
20789                        underline: Some(UnderlineStyle {
20790                            thickness: px(1.),
20791                            color: None,
20792                            wavy: false,
20793                        }),
20794                        ..Default::default()
20795                    },
20796                    cx,
20797                );
20798            }
20799
20800            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20801            let use_autoclose = this.use_autoclose;
20802            let use_auto_surround = this.use_auto_surround;
20803            this.set_use_autoclose(false);
20804            this.set_use_auto_surround(false);
20805            this.handle_input(text, window, cx);
20806            this.set_use_autoclose(use_autoclose);
20807            this.set_use_auto_surround(use_auto_surround);
20808
20809            if let Some(new_selected_range) = new_selected_range_utf16 {
20810                let snapshot = this.buffer.read(cx).read(cx);
20811                let new_selected_ranges = marked_ranges
20812                    .into_iter()
20813                    .map(|marked_range| {
20814                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20815                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20816                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20817                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20818                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20819                    })
20820                    .collect::<Vec<_>>();
20821
20822                drop(snapshot);
20823                this.change_selections(None, window, cx, |selections| {
20824                    selections.select_ranges(new_selected_ranges)
20825                });
20826            }
20827        });
20828
20829        self.ime_transaction = self.ime_transaction.or(transaction);
20830        if let Some(transaction) = self.ime_transaction {
20831            self.buffer.update(cx, |buffer, cx| {
20832                buffer.group_until_transaction(transaction, cx);
20833            });
20834        }
20835
20836        if self.text_highlights::<InputComposition>(cx).is_none() {
20837            self.ime_transaction.take();
20838        }
20839    }
20840
20841    fn bounds_for_range(
20842        &mut self,
20843        range_utf16: Range<usize>,
20844        element_bounds: gpui::Bounds<Pixels>,
20845        window: &mut Window,
20846        cx: &mut Context<Self>,
20847    ) -> Option<gpui::Bounds<Pixels>> {
20848        let text_layout_details = self.text_layout_details(window);
20849        let gpui::Size {
20850            width: em_width,
20851            height: line_height,
20852        } = self.character_size(window);
20853
20854        let snapshot = self.snapshot(window, cx);
20855        let scroll_position = snapshot.scroll_position();
20856        let scroll_left = scroll_position.x * em_width;
20857
20858        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20859        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20860            + self.gutter_dimensions.width
20861            + self.gutter_dimensions.margin;
20862        let y = line_height * (start.row().as_f32() - scroll_position.y);
20863
20864        Some(Bounds {
20865            origin: element_bounds.origin + point(x, y),
20866            size: size(em_width, line_height),
20867        })
20868    }
20869
20870    fn character_index_for_point(
20871        &mut self,
20872        point: gpui::Point<Pixels>,
20873        _window: &mut Window,
20874        _cx: &mut Context<Self>,
20875    ) -> Option<usize> {
20876        let position_map = self.last_position_map.as_ref()?;
20877        if !position_map.text_hitbox.contains(&point) {
20878            return None;
20879        }
20880        let display_point = position_map.point_for_position(point).previous_valid;
20881        let anchor = position_map
20882            .snapshot
20883            .display_point_to_anchor(display_point, Bias::Left);
20884        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20885        Some(utf16_offset.0)
20886    }
20887}
20888
20889trait SelectionExt {
20890    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20891    fn spanned_rows(
20892        &self,
20893        include_end_if_at_line_start: bool,
20894        map: &DisplaySnapshot,
20895    ) -> Range<MultiBufferRow>;
20896}
20897
20898impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20899    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20900        let start = self
20901            .start
20902            .to_point(&map.buffer_snapshot)
20903            .to_display_point(map);
20904        let end = self
20905            .end
20906            .to_point(&map.buffer_snapshot)
20907            .to_display_point(map);
20908        if self.reversed {
20909            end..start
20910        } else {
20911            start..end
20912        }
20913    }
20914
20915    fn spanned_rows(
20916        &self,
20917        include_end_if_at_line_start: bool,
20918        map: &DisplaySnapshot,
20919    ) -> Range<MultiBufferRow> {
20920        let start = self.start.to_point(&map.buffer_snapshot);
20921        let mut end = self.end.to_point(&map.buffer_snapshot);
20922        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20923            end.row -= 1;
20924        }
20925
20926        let buffer_start = map.prev_line_boundary(start).0;
20927        let buffer_end = map.next_line_boundary(end).0;
20928        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20929    }
20930}
20931
20932impl<T: InvalidationRegion> InvalidationStack<T> {
20933    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20934    where
20935        S: Clone + ToOffset,
20936    {
20937        while let Some(region) = self.last() {
20938            let all_selections_inside_invalidation_ranges =
20939                if selections.len() == region.ranges().len() {
20940                    selections
20941                        .iter()
20942                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20943                        .all(|(selection, invalidation_range)| {
20944                            let head = selection.head().to_offset(buffer);
20945                            invalidation_range.start <= head && invalidation_range.end >= head
20946                        })
20947                } else {
20948                    false
20949                };
20950
20951            if all_selections_inside_invalidation_ranges {
20952                break;
20953            } else {
20954                self.pop();
20955            }
20956        }
20957    }
20958}
20959
20960impl<T> Default for InvalidationStack<T> {
20961    fn default() -> Self {
20962        Self(Default::default())
20963    }
20964}
20965
20966impl<T> Deref for InvalidationStack<T> {
20967    type Target = Vec<T>;
20968
20969    fn deref(&self) -> &Self::Target {
20970        &self.0
20971    }
20972}
20973
20974impl<T> DerefMut for InvalidationStack<T> {
20975    fn deref_mut(&mut self) -> &mut Self::Target {
20976        &mut self.0
20977    }
20978}
20979
20980impl InvalidationRegion for SnippetState {
20981    fn ranges(&self) -> &[Range<Anchor>] {
20982        &self.ranges[self.active_index]
20983    }
20984}
20985
20986fn inline_completion_edit_text(
20987    current_snapshot: &BufferSnapshot,
20988    edits: &[(Range<Anchor>, String)],
20989    edit_preview: &EditPreview,
20990    include_deletions: bool,
20991    cx: &App,
20992) -> HighlightedText {
20993    let edits = edits
20994        .iter()
20995        .map(|(anchor, text)| {
20996            (
20997                anchor.start.text_anchor..anchor.end.text_anchor,
20998                text.clone(),
20999            )
21000        })
21001        .collect::<Vec<_>>();
21002
21003    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
21004}
21005
21006pub fn diagnostic_style(severity: lsp::DiagnosticSeverity, colors: &StatusColors) -> Hsla {
21007    match severity {
21008        lsp::DiagnosticSeverity::ERROR => colors.error,
21009        lsp::DiagnosticSeverity::WARNING => colors.warning,
21010        lsp::DiagnosticSeverity::INFORMATION => colors.info,
21011        lsp::DiagnosticSeverity::HINT => colors.info,
21012        _ => colors.ignored,
21013    }
21014}
21015
21016pub fn styled_runs_for_code_label<'a>(
21017    label: &'a CodeLabel,
21018    syntax_theme: &'a theme::SyntaxTheme,
21019) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
21020    let fade_out = HighlightStyle {
21021        fade_out: Some(0.35),
21022        ..Default::default()
21023    };
21024
21025    let mut prev_end = label.filter_range.end;
21026    label
21027        .runs
21028        .iter()
21029        .enumerate()
21030        .flat_map(move |(ix, (range, highlight_id))| {
21031            let style = if let Some(style) = highlight_id.style(syntax_theme) {
21032                style
21033            } else {
21034                return Default::default();
21035            };
21036            let mut muted_style = style;
21037            muted_style.highlight(fade_out);
21038
21039            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
21040            if range.start >= label.filter_range.end {
21041                if range.start > prev_end {
21042                    runs.push((prev_end..range.start, fade_out));
21043                }
21044                runs.push((range.clone(), muted_style));
21045            } else if range.end <= label.filter_range.end {
21046                runs.push((range.clone(), style));
21047            } else {
21048                runs.push((range.start..label.filter_range.end, style));
21049                runs.push((label.filter_range.end..range.end, muted_style));
21050            }
21051            prev_end = cmp::max(prev_end, range.end);
21052
21053            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
21054                runs.push((prev_end..label.text.len(), fade_out));
21055            }
21056
21057            runs
21058        })
21059}
21060
21061pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
21062    let mut prev_index = 0;
21063    let mut prev_codepoint: Option<char> = None;
21064    text.char_indices()
21065        .chain([(text.len(), '\0')])
21066        .filter_map(move |(index, codepoint)| {
21067            let prev_codepoint = prev_codepoint.replace(codepoint)?;
21068            let is_boundary = index == text.len()
21069                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
21070                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
21071            if is_boundary {
21072                let chunk = &text[prev_index..index];
21073                prev_index = index;
21074                Some(chunk)
21075            } else {
21076                None
21077            }
21078        })
21079}
21080
21081pub trait RangeToAnchorExt: Sized {
21082    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
21083
21084    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
21085        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
21086        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
21087    }
21088}
21089
21090impl<T: ToOffset> RangeToAnchorExt for Range<T> {
21091    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
21092        let start_offset = self.start.to_offset(snapshot);
21093        let end_offset = self.end.to_offset(snapshot);
21094        if start_offset == end_offset {
21095            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
21096        } else {
21097            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
21098        }
21099    }
21100}
21101
21102pub trait RowExt {
21103    fn as_f32(&self) -> f32;
21104
21105    fn next_row(&self) -> Self;
21106
21107    fn previous_row(&self) -> Self;
21108
21109    fn minus(&self, other: Self) -> u32;
21110}
21111
21112impl RowExt for DisplayRow {
21113    fn as_f32(&self) -> f32 {
21114        self.0 as f32
21115    }
21116
21117    fn next_row(&self) -> Self {
21118        Self(self.0 + 1)
21119    }
21120
21121    fn previous_row(&self) -> Self {
21122        Self(self.0.saturating_sub(1))
21123    }
21124
21125    fn minus(&self, other: Self) -> u32 {
21126        self.0 - other.0
21127    }
21128}
21129
21130impl RowExt for MultiBufferRow {
21131    fn as_f32(&self) -> f32 {
21132        self.0 as f32
21133    }
21134
21135    fn next_row(&self) -> Self {
21136        Self(self.0 + 1)
21137    }
21138
21139    fn previous_row(&self) -> Self {
21140        Self(self.0.saturating_sub(1))
21141    }
21142
21143    fn minus(&self, other: Self) -> u32 {
21144        self.0 - other.0
21145    }
21146}
21147
21148trait RowRangeExt {
21149    type Row;
21150
21151    fn len(&self) -> usize;
21152
21153    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
21154}
21155
21156impl RowRangeExt for Range<MultiBufferRow> {
21157    type Row = MultiBufferRow;
21158
21159    fn len(&self) -> usize {
21160        (self.end.0 - self.start.0) as usize
21161    }
21162
21163    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
21164        (self.start.0..self.end.0).map(MultiBufferRow)
21165    }
21166}
21167
21168impl RowRangeExt for Range<DisplayRow> {
21169    type Row = DisplayRow;
21170
21171    fn len(&self) -> usize {
21172        (self.end.0 - self.start.0) as usize
21173    }
21174
21175    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
21176        (self.start.0..self.end.0).map(DisplayRow)
21177    }
21178}
21179
21180/// If select range has more than one line, we
21181/// just point the cursor to range.start.
21182fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
21183    if range.start.row == range.end.row {
21184        range
21185    } else {
21186        range.start..range.start
21187    }
21188}
21189pub struct KillRing(ClipboardItem);
21190impl Global for KillRing {}
21191
21192const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
21193
21194enum BreakpointPromptEditAction {
21195    Log,
21196    Condition,
21197    HitCondition,
21198}
21199
21200struct BreakpointPromptEditor {
21201    pub(crate) prompt: Entity<Editor>,
21202    editor: WeakEntity<Editor>,
21203    breakpoint_anchor: Anchor,
21204    breakpoint: Breakpoint,
21205    edit_action: BreakpointPromptEditAction,
21206    block_ids: HashSet<CustomBlockId>,
21207    editor_margins: Arc<Mutex<EditorMargins>>,
21208    _subscriptions: Vec<Subscription>,
21209}
21210
21211impl BreakpointPromptEditor {
21212    const MAX_LINES: u8 = 4;
21213
21214    fn new(
21215        editor: WeakEntity<Editor>,
21216        breakpoint_anchor: Anchor,
21217        breakpoint: Breakpoint,
21218        edit_action: BreakpointPromptEditAction,
21219        window: &mut Window,
21220        cx: &mut Context<Self>,
21221    ) -> Self {
21222        let base_text = match edit_action {
21223            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
21224            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
21225            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
21226        }
21227        .map(|msg| msg.to_string())
21228        .unwrap_or_default();
21229
21230        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
21231        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
21232
21233        let prompt = cx.new(|cx| {
21234            let mut prompt = Editor::new(
21235                EditorMode::AutoHeight {
21236                    max_lines: Self::MAX_LINES as usize,
21237                },
21238                buffer,
21239                None,
21240                window,
21241                cx,
21242            );
21243            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21244            prompt.set_show_cursor_when_unfocused(false, cx);
21245            prompt.set_placeholder_text(
21246                match edit_action {
21247                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21248                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21249                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21250                },
21251                cx,
21252            );
21253
21254            prompt
21255        });
21256
21257        Self {
21258            prompt,
21259            editor,
21260            breakpoint_anchor,
21261            breakpoint,
21262            edit_action,
21263            editor_margins: Arc::new(Mutex::new(EditorMargins::default())),
21264            block_ids: Default::default(),
21265            _subscriptions: vec![],
21266        }
21267    }
21268
21269    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21270        self.block_ids.extend(block_ids)
21271    }
21272
21273    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21274        if let Some(editor) = self.editor.upgrade() {
21275            let message = self
21276                .prompt
21277                .read(cx)
21278                .buffer
21279                .read(cx)
21280                .as_singleton()
21281                .expect("A multi buffer in breakpoint prompt isn't possible")
21282                .read(cx)
21283                .as_rope()
21284                .to_string();
21285
21286            editor.update(cx, |editor, cx| {
21287                editor.edit_breakpoint_at_anchor(
21288                    self.breakpoint_anchor,
21289                    self.breakpoint.clone(),
21290                    match self.edit_action {
21291                        BreakpointPromptEditAction::Log => {
21292                            BreakpointEditAction::EditLogMessage(message.into())
21293                        }
21294                        BreakpointPromptEditAction::Condition => {
21295                            BreakpointEditAction::EditCondition(message.into())
21296                        }
21297                        BreakpointPromptEditAction::HitCondition => {
21298                            BreakpointEditAction::EditHitCondition(message.into())
21299                        }
21300                    },
21301                    cx,
21302                );
21303
21304                editor.remove_blocks(self.block_ids.clone(), None, cx);
21305                cx.focus_self(window);
21306            });
21307        }
21308    }
21309
21310    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21311        self.editor
21312            .update(cx, |editor, cx| {
21313                editor.remove_blocks(self.block_ids.clone(), None, cx);
21314                window.focus(&editor.focus_handle);
21315            })
21316            .log_err();
21317    }
21318
21319    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21320        let settings = ThemeSettings::get_global(cx);
21321        let text_style = TextStyle {
21322            color: if self.prompt.read(cx).read_only(cx) {
21323                cx.theme().colors().text_disabled
21324            } else {
21325                cx.theme().colors().text
21326            },
21327            font_family: settings.buffer_font.family.clone(),
21328            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21329            font_size: settings.buffer_font_size(cx).into(),
21330            font_weight: settings.buffer_font.weight,
21331            line_height: relative(settings.buffer_line_height.value()),
21332            ..Default::default()
21333        };
21334        EditorElement::new(
21335            &self.prompt,
21336            EditorStyle {
21337                background: cx.theme().colors().editor_background,
21338                local_player: cx.theme().players().local(),
21339                text: text_style,
21340                ..Default::default()
21341            },
21342        )
21343    }
21344}
21345
21346impl Render for BreakpointPromptEditor {
21347    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21348        let editor_margins = *self.editor_margins.lock();
21349        let gutter_dimensions = editor_margins.gutter;
21350        h_flex()
21351            .key_context("Editor")
21352            .bg(cx.theme().colors().editor_background)
21353            .border_y_1()
21354            .border_color(cx.theme().status().info_border)
21355            .size_full()
21356            .py(window.line_height() / 2.5)
21357            .on_action(cx.listener(Self::confirm))
21358            .on_action(cx.listener(Self::cancel))
21359            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21360            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21361    }
21362}
21363
21364impl Focusable for BreakpointPromptEditor {
21365    fn focus_handle(&self, cx: &App) -> FocusHandle {
21366        self.prompt.focus_handle(cx)
21367    }
21368}
21369
21370fn all_edits_insertions_or_deletions(
21371    edits: &Vec<(Range<Anchor>, String)>,
21372    snapshot: &MultiBufferSnapshot,
21373) -> bool {
21374    let mut all_insertions = true;
21375    let mut all_deletions = true;
21376
21377    for (range, new_text) in edits.iter() {
21378        let range_is_empty = range.to_offset(&snapshot).is_empty();
21379        let text_is_empty = new_text.is_empty();
21380
21381        if range_is_empty != text_is_empty {
21382            if range_is_empty {
21383                all_deletions = false;
21384            } else {
21385                all_insertions = false;
21386            }
21387        } else {
21388            return false;
21389        }
21390
21391        if !all_insertions && !all_deletions {
21392            return false;
21393        }
21394    }
21395    all_insertions || all_deletions
21396}
21397
21398struct MissingEditPredictionKeybindingTooltip;
21399
21400impl Render for MissingEditPredictionKeybindingTooltip {
21401    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21402        ui::tooltip_container(window, cx, |container, _, cx| {
21403            container
21404                .flex_shrink_0()
21405                .max_w_80()
21406                .min_h(rems_from_px(124.))
21407                .justify_between()
21408                .child(
21409                    v_flex()
21410                        .flex_1()
21411                        .text_ui_sm(cx)
21412                        .child(Label::new("Conflict with Accept Keybinding"))
21413                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21414                )
21415                .child(
21416                    h_flex()
21417                        .pb_1()
21418                        .gap_1()
21419                        .items_end()
21420                        .w_full()
21421                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21422                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21423                        }))
21424                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21425                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21426                        })),
21427                )
21428        })
21429    }
21430}
21431
21432#[derive(Debug, Clone, Copy, PartialEq)]
21433pub struct LineHighlight {
21434    pub background: Background,
21435    pub border: Option<gpui::Hsla>,
21436    pub include_gutter: bool,
21437    pub type_id: Option<TypeId>,
21438}
21439
21440fn render_diff_hunk_controls(
21441    row: u32,
21442    status: &DiffHunkStatus,
21443    hunk_range: Range<Anchor>,
21444    is_created_file: bool,
21445    line_height: Pixels,
21446    editor: &Entity<Editor>,
21447    _window: &mut Window,
21448    cx: &mut App,
21449) -> AnyElement {
21450    h_flex()
21451        .h(line_height)
21452        .mr_1()
21453        .gap_1()
21454        .px_0p5()
21455        .pb_1()
21456        .border_x_1()
21457        .border_b_1()
21458        .border_color(cx.theme().colors().border_variant)
21459        .rounded_b_lg()
21460        .bg(cx.theme().colors().editor_background)
21461        .gap_1()
21462        .occlude()
21463        .shadow_md()
21464        .child(if status.has_secondary_hunk() {
21465            Button::new(("stage", row as u64), "Stage")
21466                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21467                .tooltip({
21468                    let focus_handle = editor.focus_handle(cx);
21469                    move |window, cx| {
21470                        Tooltip::for_action_in(
21471                            "Stage Hunk",
21472                            &::git::ToggleStaged,
21473                            &focus_handle,
21474                            window,
21475                            cx,
21476                        )
21477                    }
21478                })
21479                .on_click({
21480                    let editor = editor.clone();
21481                    move |_event, _window, cx| {
21482                        editor.update(cx, |editor, cx| {
21483                            editor.stage_or_unstage_diff_hunks(
21484                                true,
21485                                vec![hunk_range.start..hunk_range.start],
21486                                cx,
21487                            );
21488                        });
21489                    }
21490                })
21491        } else {
21492            Button::new(("unstage", row as u64), "Unstage")
21493                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21494                .tooltip({
21495                    let focus_handle = editor.focus_handle(cx);
21496                    move |window, cx| {
21497                        Tooltip::for_action_in(
21498                            "Unstage Hunk",
21499                            &::git::ToggleStaged,
21500                            &focus_handle,
21501                            window,
21502                            cx,
21503                        )
21504                    }
21505                })
21506                .on_click({
21507                    let editor = editor.clone();
21508                    move |_event, _window, cx| {
21509                        editor.update(cx, |editor, cx| {
21510                            editor.stage_or_unstage_diff_hunks(
21511                                false,
21512                                vec![hunk_range.start..hunk_range.start],
21513                                cx,
21514                            );
21515                        });
21516                    }
21517                })
21518        })
21519        .child(
21520            Button::new(("restore", row as u64), "Restore")
21521                .tooltip({
21522                    let focus_handle = editor.focus_handle(cx);
21523                    move |window, cx| {
21524                        Tooltip::for_action_in(
21525                            "Restore Hunk",
21526                            &::git::Restore,
21527                            &focus_handle,
21528                            window,
21529                            cx,
21530                        )
21531                    }
21532                })
21533                .on_click({
21534                    let editor = editor.clone();
21535                    move |_event, window, cx| {
21536                        editor.update(cx, |editor, cx| {
21537                            let snapshot = editor.snapshot(window, cx);
21538                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21539                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21540                        });
21541                    }
21542                })
21543                .disabled(is_created_file),
21544        )
21545        .when(
21546            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21547            |el| {
21548                el.child(
21549                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21550                        .shape(IconButtonShape::Square)
21551                        .icon_size(IconSize::Small)
21552                        // .disabled(!has_multiple_hunks)
21553                        .tooltip({
21554                            let focus_handle = editor.focus_handle(cx);
21555                            move |window, cx| {
21556                                Tooltip::for_action_in(
21557                                    "Next Hunk",
21558                                    &GoToHunk,
21559                                    &focus_handle,
21560                                    window,
21561                                    cx,
21562                                )
21563                            }
21564                        })
21565                        .on_click({
21566                            let editor = editor.clone();
21567                            move |_event, window, cx| {
21568                                editor.update(cx, |editor, cx| {
21569                                    let snapshot = editor.snapshot(window, cx);
21570                                    let position =
21571                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21572                                    editor.go_to_hunk_before_or_after_position(
21573                                        &snapshot,
21574                                        position,
21575                                        Direction::Next,
21576                                        window,
21577                                        cx,
21578                                    );
21579                                    editor.expand_selected_diff_hunks(cx);
21580                                });
21581                            }
21582                        }),
21583                )
21584                .child(
21585                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21586                        .shape(IconButtonShape::Square)
21587                        .icon_size(IconSize::Small)
21588                        // .disabled(!has_multiple_hunks)
21589                        .tooltip({
21590                            let focus_handle = editor.focus_handle(cx);
21591                            move |window, cx| {
21592                                Tooltip::for_action_in(
21593                                    "Previous Hunk",
21594                                    &GoToPreviousHunk,
21595                                    &focus_handle,
21596                                    window,
21597                                    cx,
21598                                )
21599                            }
21600                        })
21601                        .on_click({
21602                            let editor = editor.clone();
21603                            move |_event, window, cx| {
21604                                editor.update(cx, |editor, cx| {
21605                                    let snapshot = editor.snapshot(window, cx);
21606                                    let point =
21607                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21608                                    editor.go_to_hunk_before_or_after_position(
21609                                        &snapshot,
21610                                        point,
21611                                        Direction::Prev,
21612                                        window,
21613                                        cx,
21614                                    );
21615                                    editor.expand_selected_diff_hunks(cx);
21616                                });
21617                            }
21618                        }),
21619                )
21620            },
21621        )
21622        .into_any_element()
21623}