editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132};
  133
  134pub use git::blame::BlameRenderer;
  135pub use proposed_changes_editor::{
  136    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  137};
  138use smallvec::smallvec;
  139use std::{cell::OnceCell, iter::Peekable};
  140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  141
  142pub use lsp::CompletionContext;
  143use lsp::{
  144    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  145    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  146};
  147
  148use language::BufferSnapshot;
  149pub use lsp_ext::lsp_tasks;
  150use movement::TextLayoutDetails;
  151pub use multi_buffer::{
  152    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  153    RowInfo, ToOffset, ToPoint,
  154};
  155use multi_buffer::{
  156    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  157    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  158};
  159use parking_lot::Mutex;
  160use project::{
  161    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  162    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  163    TaskSourceKind,
  164    debugger::breakpoint_store::Breakpoint,
  165    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  166    project_settings::{GitGutterSetting, ProjectSettings},
  167};
  168use rand::prelude::*;
  169use rpc::{ErrorExt, proto::*};
  170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  171use selections_collection::{
  172    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  173};
  174use serde::{Deserialize, Serialize};
  175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  176use smallvec::SmallVec;
  177use snippet::Snippet;
  178use std::sync::Arc;
  179use std::{
  180    any::TypeId,
  181    borrow::Cow,
  182    cell::RefCell,
  183    cmp::{self, Ordering, Reverse},
  184    mem,
  185    num::NonZeroU32,
  186    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  187    path::{Path, PathBuf},
  188    rc::Rc,
  189    time::{Duration, Instant},
  190};
  191pub use sum_tree::Bias;
  192use sum_tree::TreeMap;
  193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  194use theme::{
  195    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  196    observe_buffer_font_size_adjustment,
  197};
  198use ui::{
  199    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  200    IconSize, Key, Tooltip, h_flex, prelude::*,
  201};
  202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  203use workspace::{
  204    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  205    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  206    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  207    item::{ItemHandle, PreviewTabsSettings},
  208    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  209    searchable::SearchEvent,
  210};
  211
  212use crate::hover_links::{find_url, find_url_from_range};
  213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  214
  215pub const FILE_HEADER_HEIGHT: u32 = 2;
  216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  219const MAX_LINE_LEN: usize = 1024;
  220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  223#[doc(hidden)]
  224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  226
  227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  230
  231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  234
  235pub type RenderDiffHunkControlsFn = Arc<
  236    dyn Fn(
  237        u32,
  238        &DiffHunkStatus,
  239        Range<Anchor>,
  240        bool,
  241        Pixels,
  242        &Entity<Editor>,
  243        &mut Window,
  244        &mut App,
  245    ) -> AnyElement,
  246>;
  247
  248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  249    alt: true,
  250    shift: true,
  251    control: false,
  252    platform: false,
  253    function: false,
  254};
  255
  256struct InlineValueCache {
  257    enabled: bool,
  258    inlays: Vec<InlayId>,
  259    refresh_task: Task<Option<()>>,
  260}
  261
  262impl InlineValueCache {
  263    fn new(enabled: bool) -> Self {
  264        Self {
  265            enabled,
  266            inlays: Vec::new(),
  267            refresh_task: Task::ready(None),
  268        }
  269    }
  270}
  271
  272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  273pub enum InlayId {
  274    InlineCompletion(usize),
  275    Hint(usize),
  276    DebuggerValue(usize),
  277}
  278
  279impl InlayId {
  280    fn id(&self) -> usize {
  281        match self {
  282            Self::InlineCompletion(id) => *id,
  283            Self::Hint(id) => *id,
  284            Self::DebuggerValue(id) => *id,
  285        }
  286    }
  287}
  288
  289pub enum ActiveDebugLine {}
  290enum DocumentHighlightRead {}
  291enum DocumentHighlightWrite {}
  292enum InputComposition {}
  293enum SelectedTextHighlight {}
  294
  295pub enum ConflictsOuter {}
  296pub enum ConflictsOurs {}
  297pub enum ConflictsTheirs {}
  298pub enum ConflictsOursMarker {}
  299pub enum ConflictsTheirsMarker {}
  300
  301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  302pub enum Navigated {
  303    Yes,
  304    No,
  305}
  306
  307impl Navigated {
  308    pub fn from_bool(yes: bool) -> Navigated {
  309        if yes { Navigated::Yes } else { Navigated::No }
  310    }
  311}
  312
  313#[derive(Debug, Clone, PartialEq, Eq)]
  314enum DisplayDiffHunk {
  315    Folded {
  316        display_row: DisplayRow,
  317    },
  318    Unfolded {
  319        is_created_file: bool,
  320        diff_base_byte_range: Range<usize>,
  321        display_row_range: Range<DisplayRow>,
  322        multi_buffer_range: Range<Anchor>,
  323        status: DiffHunkStatus,
  324    },
  325}
  326
  327pub enum HideMouseCursorOrigin {
  328    TypingAction,
  329    MovementAction,
  330}
  331
  332pub fn init_settings(cx: &mut App) {
  333    EditorSettings::register(cx);
  334}
  335
  336pub fn init(cx: &mut App) {
  337    init_settings(cx);
  338
  339    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  340
  341    workspace::register_project_item::<Editor>(cx);
  342    workspace::FollowableViewRegistry::register::<Editor>(cx);
  343    workspace::register_serializable_item::<Editor>(cx);
  344
  345    cx.observe_new(
  346        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  347            workspace.register_action(Editor::new_file);
  348            workspace.register_action(Editor::new_file_vertical);
  349            workspace.register_action(Editor::new_file_horizontal);
  350            workspace.register_action(Editor::cancel_language_server_work);
  351        },
  352    )
  353    .detach();
  354
  355    cx.on_action(move |_: &workspace::NewFile, cx| {
  356        let app_state = workspace::AppState::global(cx);
  357        if let Some(app_state) = app_state.upgrade() {
  358            workspace::open_new(
  359                Default::default(),
  360                app_state,
  361                cx,
  362                |workspace, window, cx| {
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369    cx.on_action(move |_: &workspace::NewWindow, cx| {
  370        let app_state = workspace::AppState::global(cx);
  371        if let Some(app_state) = app_state.upgrade() {
  372            workspace::open_new(
  373                Default::default(),
  374                app_state,
  375                cx,
  376                |workspace, window, cx| {
  377                    cx.activate(true);
  378                    Editor::new_file(workspace, &Default::default(), window, cx)
  379                },
  380            )
  381            .detach();
  382        }
  383    });
  384}
  385
  386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  387    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  388}
  389
  390pub trait DiagnosticRenderer {
  391    fn render_group(
  392        &self,
  393        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  394        buffer_id: BufferId,
  395        snapshot: EditorSnapshot,
  396        editor: WeakEntity<Editor>,
  397        cx: &mut App,
  398    ) -> Vec<BlockProperties<Anchor>>;
  399
  400    fn render_hover(
  401        &self,
  402        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  403        range: Range<Point>,
  404        buffer_id: BufferId,
  405        cx: &mut App,
  406    ) -> Option<Entity<markdown::Markdown>>;
  407
  408    fn open_link(
  409        &self,
  410        editor: &mut Editor,
  411        link: SharedString,
  412        window: &mut Window,
  413        cx: &mut Context<Editor>,
  414    );
  415}
  416
  417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  418
  419impl GlobalDiagnosticRenderer {
  420    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  421        cx.try_global::<Self>().map(|g| g.0.clone())
  422    }
  423}
  424
  425impl gpui::Global for GlobalDiagnosticRenderer {}
  426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  427    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  428}
  429
  430pub struct SearchWithinRange;
  431
  432trait InvalidationRegion {
  433    fn ranges(&self) -> &[Range<Anchor>];
  434}
  435
  436#[derive(Clone, Debug, PartialEq)]
  437pub enum SelectPhase {
  438    Begin {
  439        position: DisplayPoint,
  440        add: bool,
  441        click_count: usize,
  442    },
  443    BeginColumnar {
  444        position: DisplayPoint,
  445        reset: bool,
  446        goal_column: u32,
  447    },
  448    Extend {
  449        position: DisplayPoint,
  450        click_count: usize,
  451    },
  452    Update {
  453        position: DisplayPoint,
  454        goal_column: u32,
  455        scroll_delta: gpui::Point<f32>,
  456    },
  457    End,
  458}
  459
  460#[derive(Clone, Debug)]
  461pub enum SelectMode {
  462    Character,
  463    Word(Range<Anchor>),
  464    Line(Range<Anchor>),
  465    All,
  466}
  467
  468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  469pub enum EditorMode {
  470    SingleLine {
  471        auto_width: bool,
  472    },
  473    AutoHeight {
  474        max_lines: usize,
  475    },
  476    Full {
  477        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  478        scale_ui_elements_with_buffer_font_size: bool,
  479        /// When set to `true`, the editor will render a background for the active line.
  480        show_active_line_background: bool,
  481        /// When set to `true`, the editor's height will be determined by its content.
  482        sized_by_content: bool,
  483    },
  484}
  485
  486impl EditorMode {
  487    pub fn full() -> Self {
  488        Self::Full {
  489            scale_ui_elements_with_buffer_font_size: true,
  490            show_active_line_background: true,
  491            sized_by_content: false,
  492        }
  493    }
  494
  495    pub fn is_full(&self) -> bool {
  496        matches!(self, Self::Full { .. })
  497    }
  498}
  499
  500#[derive(Copy, Clone, Debug)]
  501pub enum SoftWrap {
  502    /// Prefer not to wrap at all.
  503    ///
  504    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  505    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  506    GitDiff,
  507    /// Prefer a single line generally, unless an overly long line is encountered.
  508    None,
  509    /// Soft wrap lines that exceed the editor width.
  510    EditorWidth,
  511    /// Soft wrap lines at the preferred line length.
  512    Column(u32),
  513    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  514    Bounded(u32),
  515}
  516
  517#[derive(Clone)]
  518pub struct EditorStyle {
  519    pub background: Hsla,
  520    pub horizontal_padding: Pixels,
  521    pub local_player: PlayerColor,
  522    pub text: TextStyle,
  523    pub scrollbar_width: Pixels,
  524    pub syntax: Arc<SyntaxTheme>,
  525    pub status: StatusColors,
  526    pub inlay_hints_style: HighlightStyle,
  527    pub inline_completion_styles: InlineCompletionStyles,
  528    pub unnecessary_code_fade: f32,
  529}
  530
  531impl Default for EditorStyle {
  532    fn default() -> Self {
  533        Self {
  534            background: Hsla::default(),
  535            horizontal_padding: Pixels::default(),
  536            local_player: PlayerColor::default(),
  537            text: TextStyle::default(),
  538            scrollbar_width: Pixels::default(),
  539            syntax: Default::default(),
  540            // HACK: Status colors don't have a real default.
  541            // We should look into removing the status colors from the editor
  542            // style and retrieve them directly from the theme.
  543            status: StatusColors::dark(),
  544            inlay_hints_style: HighlightStyle::default(),
  545            inline_completion_styles: InlineCompletionStyles {
  546                insertion: HighlightStyle::default(),
  547                whitespace: HighlightStyle::default(),
  548            },
  549            unnecessary_code_fade: Default::default(),
  550        }
  551    }
  552}
  553
  554pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  555    let show_background = language_settings::language_settings(None, None, cx)
  556        .inlay_hints
  557        .show_background;
  558
  559    HighlightStyle {
  560        color: Some(cx.theme().status().hint),
  561        background_color: show_background.then(|| cx.theme().status().hint_background),
  562        ..HighlightStyle::default()
  563    }
  564}
  565
  566pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  567    InlineCompletionStyles {
  568        insertion: HighlightStyle {
  569            color: Some(cx.theme().status().predictive),
  570            ..HighlightStyle::default()
  571        },
  572        whitespace: HighlightStyle {
  573            background_color: Some(cx.theme().status().created_background),
  574            ..HighlightStyle::default()
  575        },
  576    }
  577}
  578
  579type CompletionId = usize;
  580
  581pub(crate) enum EditDisplayMode {
  582    TabAccept,
  583    DiffPopover,
  584    Inline,
  585}
  586
  587enum InlineCompletion {
  588    Edit {
  589        edits: Vec<(Range<Anchor>, String)>,
  590        edit_preview: Option<EditPreview>,
  591        display_mode: EditDisplayMode,
  592        snapshot: BufferSnapshot,
  593    },
  594    Move {
  595        target: Anchor,
  596        snapshot: BufferSnapshot,
  597    },
  598}
  599
  600struct InlineCompletionState {
  601    inlay_ids: Vec<InlayId>,
  602    completion: InlineCompletion,
  603    completion_id: Option<SharedString>,
  604    invalidation_range: Range<Anchor>,
  605}
  606
  607enum EditPredictionSettings {
  608    Disabled,
  609    Enabled {
  610        show_in_menu: bool,
  611        preview_requires_modifier: bool,
  612    },
  613}
  614
  615enum InlineCompletionHighlight {}
  616
  617#[derive(Debug, Clone)]
  618struct InlineDiagnostic {
  619    message: SharedString,
  620    group_id: usize,
  621    is_primary: bool,
  622    start: Point,
  623    severity: DiagnosticSeverity,
  624}
  625
  626pub enum MenuInlineCompletionsPolicy {
  627    Never,
  628    ByProvider,
  629}
  630
  631pub enum EditPredictionPreview {
  632    /// Modifier is not pressed
  633    Inactive { released_too_fast: bool },
  634    /// Modifier pressed
  635    Active {
  636        since: Instant,
  637        previous_scroll_position: Option<ScrollAnchor>,
  638    },
  639}
  640
  641impl EditPredictionPreview {
  642    pub fn released_too_fast(&self) -> bool {
  643        match self {
  644            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  645            EditPredictionPreview::Active { .. } => false,
  646        }
  647    }
  648
  649    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  650        if let EditPredictionPreview::Active {
  651            previous_scroll_position,
  652            ..
  653        } = self
  654        {
  655            *previous_scroll_position = scroll_position;
  656        }
  657    }
  658}
  659
  660pub struct ContextMenuOptions {
  661    pub min_entries_visible: usize,
  662    pub max_entries_visible: usize,
  663    pub placement: Option<ContextMenuPlacement>,
  664}
  665
  666#[derive(Debug, Clone, PartialEq, Eq)]
  667pub enum ContextMenuPlacement {
  668    Above,
  669    Below,
  670}
  671
  672#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  673struct EditorActionId(usize);
  674
  675impl EditorActionId {
  676    pub fn post_inc(&mut self) -> Self {
  677        let answer = self.0;
  678
  679        *self = Self(answer + 1);
  680
  681        Self(answer)
  682    }
  683}
  684
  685// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  686// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  687
  688type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  689type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  690
  691#[derive(Default)]
  692struct ScrollbarMarkerState {
  693    scrollbar_size: Size<Pixels>,
  694    dirty: bool,
  695    markers: Arc<[PaintQuad]>,
  696    pending_refresh: Option<Task<Result<()>>>,
  697}
  698
  699impl ScrollbarMarkerState {
  700    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  701        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  702    }
  703}
  704
  705#[derive(Clone, Debug)]
  706struct RunnableTasks {
  707    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  708    offset: multi_buffer::Anchor,
  709    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  710    column: u32,
  711    // Values of all named captures, including those starting with '_'
  712    extra_variables: HashMap<String, String>,
  713    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  714    context_range: Range<BufferOffset>,
  715}
  716
  717impl RunnableTasks {
  718    fn resolve<'a>(
  719        &'a self,
  720        cx: &'a task::TaskContext,
  721    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  722        self.templates.iter().filter_map(|(kind, template)| {
  723            template
  724                .resolve_task(&kind.to_id_base(), cx)
  725                .map(|task| (kind.clone(), task))
  726        })
  727    }
  728}
  729
  730#[derive(Clone)]
  731struct ResolvedTasks {
  732    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  733    position: Anchor,
  734}
  735
  736#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  737struct BufferOffset(usize);
  738
  739// Addons allow storing per-editor state in other crates (e.g. Vim)
  740pub trait Addon: 'static {
  741    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  742
  743    fn render_buffer_header_controls(
  744        &self,
  745        _: &ExcerptInfo,
  746        _: &Window,
  747        _: &App,
  748    ) -> Option<AnyElement> {
  749        None
  750    }
  751
  752    fn to_any(&self) -> &dyn std::any::Any;
  753
  754    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  755        None
  756    }
  757}
  758
  759/// A set of caret positions, registered when the editor was edited.
  760pub struct ChangeList {
  761    changes: Vec<Vec<Anchor>>,
  762    /// Currently "selected" change.
  763    position: Option<usize>,
  764}
  765
  766impl ChangeList {
  767    pub fn new() -> Self {
  768        Self {
  769            changes: Vec::new(),
  770            position: None,
  771        }
  772    }
  773
  774    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  775    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  776    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  777        if self.changes.is_empty() {
  778            return None;
  779        }
  780
  781        let prev = self.position.unwrap_or(self.changes.len());
  782        let next = if direction == Direction::Prev {
  783            prev.saturating_sub(count)
  784        } else {
  785            (prev + count).min(self.changes.len() - 1)
  786        };
  787        self.position = Some(next);
  788        self.changes.get(next).map(|anchors| anchors.as_slice())
  789    }
  790
  791    /// Adds a new change to the list, resetting the change list position.
  792    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  793        self.position.take();
  794        if pop_state {
  795            self.changes.pop();
  796        }
  797        self.changes.push(new_positions.clone());
  798    }
  799
  800    pub fn last(&self) -> Option<&[Anchor]> {
  801        self.changes.last().map(|anchors| anchors.as_slice())
  802    }
  803}
  804
  805#[derive(Clone)]
  806struct InlineBlamePopoverState {
  807    scroll_handle: ScrollHandle,
  808    commit_message: Option<ParsedCommitMessage>,
  809    markdown: Entity<Markdown>,
  810}
  811
  812struct InlineBlamePopover {
  813    position: gpui::Point<Pixels>,
  814    show_task: Option<Task<()>>,
  815    hide_task: Option<Task<()>>,
  816    popover_bounds: Option<Bounds<Pixels>>,
  817    popover_state: InlineBlamePopoverState,
  818}
  819
  820/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  821/// a breakpoint on them.
  822#[derive(Clone, Copy, Debug)]
  823struct PhantomBreakpointIndicator {
  824    display_row: DisplayRow,
  825    /// There's a small debounce between hovering over the line and showing the indicator.
  826    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  827    is_active: bool,
  828    collides_with_existing_breakpoint: bool,
  829}
  830/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  831///
  832/// See the [module level documentation](self) for more information.
  833pub struct Editor {
  834    focus_handle: FocusHandle,
  835    last_focused_descendant: Option<WeakFocusHandle>,
  836    /// The text buffer being edited
  837    buffer: Entity<MultiBuffer>,
  838    /// Map of how text in the buffer should be displayed.
  839    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  840    pub display_map: Entity<DisplayMap>,
  841    pub selections: SelectionsCollection,
  842    pub scroll_manager: ScrollManager,
  843    /// When inline assist editors are linked, they all render cursors because
  844    /// typing enters text into each of them, even the ones that aren't focused.
  845    pub(crate) show_cursor_when_unfocused: bool,
  846    columnar_selection_tail: Option<Anchor>,
  847    add_selections_state: Option<AddSelectionsState>,
  848    select_next_state: Option<SelectNextState>,
  849    select_prev_state: Option<SelectNextState>,
  850    selection_history: SelectionHistory,
  851    autoclose_regions: Vec<AutocloseRegion>,
  852    snippet_stack: InvalidationStack<SnippetState>,
  853    select_syntax_node_history: SelectSyntaxNodeHistory,
  854    ime_transaction: Option<TransactionId>,
  855    active_diagnostics: ActiveDiagnostic,
  856    show_inline_diagnostics: bool,
  857    inline_diagnostics_update: Task<()>,
  858    inline_diagnostics_enabled: bool,
  859    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  860    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  861    hard_wrap: Option<usize>,
  862
  863    // TODO: make this a access method
  864    pub project: Option<Entity<Project>>,
  865    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  866    completion_provider: Option<Box<dyn CompletionProvider>>,
  867    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  868    blink_manager: Entity<BlinkManager>,
  869    show_cursor_names: bool,
  870    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  871    pub show_local_selections: bool,
  872    mode: EditorMode,
  873    show_breadcrumbs: bool,
  874    show_gutter: bool,
  875    show_scrollbars: bool,
  876    disable_expand_excerpt_buttons: bool,
  877    show_line_numbers: Option<bool>,
  878    use_relative_line_numbers: Option<bool>,
  879    show_git_diff_gutter: Option<bool>,
  880    show_code_actions: Option<bool>,
  881    show_runnables: Option<bool>,
  882    show_breakpoints: Option<bool>,
  883    show_wrap_guides: Option<bool>,
  884    show_indent_guides: Option<bool>,
  885    placeholder_text: Option<Arc<str>>,
  886    highlight_order: usize,
  887    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  888    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  889    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  890    scrollbar_marker_state: ScrollbarMarkerState,
  891    active_indent_guides_state: ActiveIndentGuidesState,
  892    nav_history: Option<ItemNavHistory>,
  893    context_menu: RefCell<Option<CodeContextMenu>>,
  894    context_menu_options: Option<ContextMenuOptions>,
  895    mouse_context_menu: Option<MouseContextMenu>,
  896    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  897    inline_blame_popover: Option<InlineBlamePopover>,
  898    signature_help_state: SignatureHelpState,
  899    auto_signature_help: Option<bool>,
  900    find_all_references_task_sources: Vec<Anchor>,
  901    next_completion_id: CompletionId,
  902    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  903    code_actions_task: Option<Task<Result<()>>>,
  904    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  905    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  906    document_highlights_task: Option<Task<()>>,
  907    linked_editing_range_task: Option<Task<Option<()>>>,
  908    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  909    pending_rename: Option<RenameState>,
  910    searchable: bool,
  911    cursor_shape: CursorShape,
  912    current_line_highlight: Option<CurrentLineHighlight>,
  913    collapse_matches: bool,
  914    autoindent_mode: Option<AutoindentMode>,
  915    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  916    input_enabled: bool,
  917    use_modal_editing: bool,
  918    read_only: bool,
  919    leader_id: Option<CollaboratorId>,
  920    remote_id: Option<ViewId>,
  921    pub hover_state: HoverState,
  922    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  923    gutter_hovered: bool,
  924    hovered_link_state: Option<HoveredLinkState>,
  925    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  926    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  927    active_inline_completion: Option<InlineCompletionState>,
  928    /// Used to prevent flickering as the user types while the menu is open
  929    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  930    edit_prediction_settings: EditPredictionSettings,
  931    inline_completions_hidden_for_vim_mode: bool,
  932    show_inline_completions_override: Option<bool>,
  933    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  934    edit_prediction_preview: EditPredictionPreview,
  935    edit_prediction_indent_conflict: bool,
  936    edit_prediction_requires_modifier_in_indent_conflict: bool,
  937    inlay_hint_cache: InlayHintCache,
  938    next_inlay_id: usize,
  939    _subscriptions: Vec<Subscription>,
  940    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  941    gutter_dimensions: GutterDimensions,
  942    style: Option<EditorStyle>,
  943    text_style_refinement: Option<TextStyleRefinement>,
  944    next_editor_action_id: EditorActionId,
  945    editor_actions:
  946        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  947    use_autoclose: bool,
  948    use_auto_surround: bool,
  949    auto_replace_emoji_shortcode: bool,
  950    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  951    show_git_blame_gutter: bool,
  952    show_git_blame_inline: bool,
  953    show_git_blame_inline_delay_task: Option<Task<()>>,
  954    git_blame_inline_enabled: bool,
  955    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  956    serialize_dirty_buffers: bool,
  957    show_selection_menu: Option<bool>,
  958    blame: Option<Entity<GitBlame>>,
  959    blame_subscription: Option<Subscription>,
  960    custom_context_menu: Option<
  961        Box<
  962            dyn 'static
  963                + Fn(
  964                    &mut Self,
  965                    DisplayPoint,
  966                    &mut Window,
  967                    &mut Context<Self>,
  968                ) -> Option<Entity<ui::ContextMenu>>,
  969        >,
  970    >,
  971    last_bounds: Option<Bounds<Pixels>>,
  972    last_position_map: Option<Rc<PositionMap>>,
  973    expect_bounds_change: Option<Bounds<Pixels>>,
  974    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  975    tasks_update_task: Option<Task<()>>,
  976    breakpoint_store: Option<Entity<BreakpointStore>>,
  977    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
  978    in_project_search: bool,
  979    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  980    breadcrumb_header: Option<String>,
  981    focused_block: Option<FocusedBlock>,
  982    next_scroll_position: NextScrollCursorCenterTopBottom,
  983    addons: HashMap<TypeId, Box<dyn Addon>>,
  984    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  985    load_diff_task: Option<Shared<Task<()>>>,
  986    /// Whether we are temporarily displaying a diff other than git's
  987    temporary_diff_override: bool,
  988    selection_mark_mode: bool,
  989    toggle_fold_multiple_buffers: Task<()>,
  990    _scroll_cursor_center_top_bottom_task: Task<()>,
  991    serialize_selections: Task<()>,
  992    serialize_folds: Task<()>,
  993    mouse_cursor_hidden: bool,
  994    hide_mouse_mode: HideMouseMode,
  995    pub change_list: ChangeList,
  996    inline_value_cache: InlineValueCache,
  997}
  998
  999#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
 1000enum NextScrollCursorCenterTopBottom {
 1001    #[default]
 1002    Center,
 1003    Top,
 1004    Bottom,
 1005}
 1006
 1007impl NextScrollCursorCenterTopBottom {
 1008    fn next(&self) -> Self {
 1009        match self {
 1010            Self::Center => Self::Top,
 1011            Self::Top => Self::Bottom,
 1012            Self::Bottom => Self::Center,
 1013        }
 1014    }
 1015}
 1016
 1017#[derive(Clone)]
 1018pub struct EditorSnapshot {
 1019    pub mode: EditorMode,
 1020    show_gutter: bool,
 1021    show_line_numbers: Option<bool>,
 1022    show_git_diff_gutter: Option<bool>,
 1023    show_code_actions: Option<bool>,
 1024    show_runnables: Option<bool>,
 1025    show_breakpoints: Option<bool>,
 1026    git_blame_gutter_max_author_length: Option<usize>,
 1027    pub display_snapshot: DisplaySnapshot,
 1028    pub placeholder_text: Option<Arc<str>>,
 1029    is_focused: bool,
 1030    scroll_anchor: ScrollAnchor,
 1031    ongoing_scroll: OngoingScroll,
 1032    current_line_highlight: CurrentLineHighlight,
 1033    gutter_hovered: bool,
 1034}
 1035
 1036#[derive(Default, Debug, Clone, Copy)]
 1037pub struct GutterDimensions {
 1038    pub left_padding: Pixels,
 1039    pub right_padding: Pixels,
 1040    pub width: Pixels,
 1041    pub margin: Pixels,
 1042    pub git_blame_entries_width: Option<Pixels>,
 1043}
 1044
 1045impl GutterDimensions {
 1046    /// The full width of the space taken up by the gutter.
 1047    pub fn full_width(&self) -> Pixels {
 1048        self.margin + self.width
 1049    }
 1050
 1051    /// The width of the space reserved for the fold indicators,
 1052    /// use alongside 'justify_end' and `gutter_width` to
 1053    /// right align content with the line numbers
 1054    pub fn fold_area_width(&self) -> Pixels {
 1055        self.margin + self.right_padding
 1056    }
 1057}
 1058
 1059#[derive(Debug)]
 1060pub struct RemoteSelection {
 1061    pub replica_id: ReplicaId,
 1062    pub selection: Selection<Anchor>,
 1063    pub cursor_shape: CursorShape,
 1064    pub collaborator_id: CollaboratorId,
 1065    pub line_mode: bool,
 1066    pub user_name: Option<SharedString>,
 1067    pub color: PlayerColor,
 1068}
 1069
 1070#[derive(Clone, Debug)]
 1071struct SelectionHistoryEntry {
 1072    selections: Arc<[Selection<Anchor>]>,
 1073    select_next_state: Option<SelectNextState>,
 1074    select_prev_state: Option<SelectNextState>,
 1075    add_selections_state: Option<AddSelectionsState>,
 1076}
 1077
 1078enum SelectionHistoryMode {
 1079    Normal,
 1080    Undoing,
 1081    Redoing,
 1082}
 1083
 1084#[derive(Clone, PartialEq, Eq, Hash)]
 1085struct HoveredCursor {
 1086    replica_id: u16,
 1087    selection_id: usize,
 1088}
 1089
 1090impl Default for SelectionHistoryMode {
 1091    fn default() -> Self {
 1092        Self::Normal
 1093    }
 1094}
 1095
 1096#[derive(Default)]
 1097struct SelectionHistory {
 1098    #[allow(clippy::type_complexity)]
 1099    selections_by_transaction:
 1100        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1101    mode: SelectionHistoryMode,
 1102    undo_stack: VecDeque<SelectionHistoryEntry>,
 1103    redo_stack: VecDeque<SelectionHistoryEntry>,
 1104}
 1105
 1106impl SelectionHistory {
 1107    fn insert_transaction(
 1108        &mut self,
 1109        transaction_id: TransactionId,
 1110        selections: Arc<[Selection<Anchor>]>,
 1111    ) {
 1112        self.selections_by_transaction
 1113            .insert(transaction_id, (selections, None));
 1114    }
 1115
 1116    #[allow(clippy::type_complexity)]
 1117    fn transaction(
 1118        &self,
 1119        transaction_id: TransactionId,
 1120    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1121        self.selections_by_transaction.get(&transaction_id)
 1122    }
 1123
 1124    #[allow(clippy::type_complexity)]
 1125    fn transaction_mut(
 1126        &mut self,
 1127        transaction_id: TransactionId,
 1128    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1129        self.selections_by_transaction.get_mut(&transaction_id)
 1130    }
 1131
 1132    fn push(&mut self, entry: SelectionHistoryEntry) {
 1133        if !entry.selections.is_empty() {
 1134            match self.mode {
 1135                SelectionHistoryMode::Normal => {
 1136                    self.push_undo(entry);
 1137                    self.redo_stack.clear();
 1138                }
 1139                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1140                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1141            }
 1142        }
 1143    }
 1144
 1145    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1146        if self
 1147            .undo_stack
 1148            .back()
 1149            .map_or(true, |e| e.selections != entry.selections)
 1150        {
 1151            self.undo_stack.push_back(entry);
 1152            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1153                self.undo_stack.pop_front();
 1154            }
 1155        }
 1156    }
 1157
 1158    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1159        if self
 1160            .redo_stack
 1161            .back()
 1162            .map_or(true, |e| e.selections != entry.selections)
 1163        {
 1164            self.redo_stack.push_back(entry);
 1165            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1166                self.redo_stack.pop_front();
 1167            }
 1168        }
 1169    }
 1170}
 1171
 1172#[derive(Clone, Copy)]
 1173pub struct RowHighlightOptions {
 1174    pub autoscroll: bool,
 1175    pub include_gutter: bool,
 1176}
 1177
 1178impl Default for RowHighlightOptions {
 1179    fn default() -> Self {
 1180        Self {
 1181            autoscroll: Default::default(),
 1182            include_gutter: true,
 1183        }
 1184    }
 1185}
 1186
 1187struct RowHighlight {
 1188    index: usize,
 1189    range: Range<Anchor>,
 1190    color: Hsla,
 1191    options: RowHighlightOptions,
 1192    type_id: TypeId,
 1193}
 1194
 1195#[derive(Clone, Debug)]
 1196struct AddSelectionsState {
 1197    above: bool,
 1198    stack: Vec<usize>,
 1199}
 1200
 1201#[derive(Clone)]
 1202struct SelectNextState {
 1203    query: AhoCorasick,
 1204    wordwise: bool,
 1205    done: bool,
 1206}
 1207
 1208impl std::fmt::Debug for SelectNextState {
 1209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1210        f.debug_struct(std::any::type_name::<Self>())
 1211            .field("wordwise", &self.wordwise)
 1212            .field("done", &self.done)
 1213            .finish()
 1214    }
 1215}
 1216
 1217#[derive(Debug)]
 1218struct AutocloseRegion {
 1219    selection_id: usize,
 1220    range: Range<Anchor>,
 1221    pair: BracketPair,
 1222}
 1223
 1224#[derive(Debug)]
 1225struct SnippetState {
 1226    ranges: Vec<Vec<Range<Anchor>>>,
 1227    active_index: usize,
 1228    choices: Vec<Option<Vec<String>>>,
 1229}
 1230
 1231#[doc(hidden)]
 1232pub struct RenameState {
 1233    pub range: Range<Anchor>,
 1234    pub old_name: Arc<str>,
 1235    pub editor: Entity<Editor>,
 1236    block_id: CustomBlockId,
 1237}
 1238
 1239struct InvalidationStack<T>(Vec<T>);
 1240
 1241struct RegisteredInlineCompletionProvider {
 1242    provider: Arc<dyn InlineCompletionProviderHandle>,
 1243    _subscription: Subscription,
 1244}
 1245
 1246#[derive(Debug, PartialEq, Eq)]
 1247pub struct ActiveDiagnosticGroup {
 1248    pub active_range: Range<Anchor>,
 1249    pub active_message: String,
 1250    pub group_id: usize,
 1251    pub blocks: HashSet<CustomBlockId>,
 1252}
 1253
 1254#[derive(Debug, PartialEq, Eq)]
 1255#[allow(clippy::large_enum_variant)]
 1256pub(crate) enum ActiveDiagnostic {
 1257    None,
 1258    All,
 1259    Group(ActiveDiagnosticGroup),
 1260}
 1261
 1262#[derive(Serialize, Deserialize, Clone, Debug)]
 1263pub struct ClipboardSelection {
 1264    /// The number of bytes in this selection.
 1265    pub len: usize,
 1266    /// Whether this was a full-line selection.
 1267    pub is_entire_line: bool,
 1268    /// The indentation of the first line when this content was originally copied.
 1269    pub first_line_indent: u32,
 1270}
 1271
 1272// selections, scroll behavior, was newest selection reversed
 1273type SelectSyntaxNodeHistoryState = (
 1274    Box<[Selection<usize>]>,
 1275    SelectSyntaxNodeScrollBehavior,
 1276    bool,
 1277);
 1278
 1279#[derive(Default)]
 1280struct SelectSyntaxNodeHistory {
 1281    stack: Vec<SelectSyntaxNodeHistoryState>,
 1282    // disable temporarily to allow changing selections without losing the stack
 1283    pub disable_clearing: bool,
 1284}
 1285
 1286impl SelectSyntaxNodeHistory {
 1287    pub fn try_clear(&mut self) {
 1288        if !self.disable_clearing {
 1289            self.stack.clear();
 1290        }
 1291    }
 1292
 1293    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1294        self.stack.push(selection);
 1295    }
 1296
 1297    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1298        self.stack.pop()
 1299    }
 1300}
 1301
 1302enum SelectSyntaxNodeScrollBehavior {
 1303    CursorTop,
 1304    FitSelection,
 1305    CursorBottom,
 1306}
 1307
 1308#[derive(Debug)]
 1309pub(crate) struct NavigationData {
 1310    cursor_anchor: Anchor,
 1311    cursor_position: Point,
 1312    scroll_anchor: ScrollAnchor,
 1313    scroll_top_row: u32,
 1314}
 1315
 1316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1317pub enum GotoDefinitionKind {
 1318    Symbol,
 1319    Declaration,
 1320    Type,
 1321    Implementation,
 1322}
 1323
 1324#[derive(Debug, Clone)]
 1325enum InlayHintRefreshReason {
 1326    ModifiersChanged(bool),
 1327    Toggle(bool),
 1328    SettingsChange(InlayHintSettings),
 1329    NewLinesShown,
 1330    BufferEdited(HashSet<Arc<Language>>),
 1331    RefreshRequested,
 1332    ExcerptsRemoved(Vec<ExcerptId>),
 1333}
 1334
 1335impl InlayHintRefreshReason {
 1336    fn description(&self) -> &'static str {
 1337        match self {
 1338            Self::ModifiersChanged(_) => "modifiers changed",
 1339            Self::Toggle(_) => "toggle",
 1340            Self::SettingsChange(_) => "settings change",
 1341            Self::NewLinesShown => "new lines shown",
 1342            Self::BufferEdited(_) => "buffer edited",
 1343            Self::RefreshRequested => "refresh requested",
 1344            Self::ExcerptsRemoved(_) => "excerpts removed",
 1345        }
 1346    }
 1347}
 1348
 1349pub enum FormatTarget {
 1350    Buffers,
 1351    Ranges(Vec<Range<MultiBufferPoint>>),
 1352}
 1353
 1354pub(crate) struct FocusedBlock {
 1355    id: BlockId,
 1356    focus_handle: WeakFocusHandle,
 1357}
 1358
 1359#[derive(Clone)]
 1360enum JumpData {
 1361    MultiBufferRow {
 1362        row: MultiBufferRow,
 1363        line_offset_from_top: u32,
 1364    },
 1365    MultiBufferPoint {
 1366        excerpt_id: ExcerptId,
 1367        position: Point,
 1368        anchor: text::Anchor,
 1369        line_offset_from_top: u32,
 1370    },
 1371}
 1372
 1373pub enum MultibufferSelectionMode {
 1374    First,
 1375    All,
 1376}
 1377
 1378#[derive(Clone, Copy, Debug, Default)]
 1379pub struct RewrapOptions {
 1380    pub override_language_settings: bool,
 1381    pub preserve_existing_whitespace: bool,
 1382}
 1383
 1384impl Editor {
 1385    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1386        let buffer = cx.new(|cx| Buffer::local("", cx));
 1387        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1388        Self::new(
 1389            EditorMode::SingleLine { auto_width: false },
 1390            buffer,
 1391            None,
 1392            window,
 1393            cx,
 1394        )
 1395    }
 1396
 1397    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1398        let buffer = cx.new(|cx| Buffer::local("", cx));
 1399        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1400        Self::new(EditorMode::full(), buffer, None, window, cx)
 1401    }
 1402
 1403    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1404        let buffer = cx.new(|cx| Buffer::local("", cx));
 1405        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1406        Self::new(
 1407            EditorMode::SingleLine { auto_width: true },
 1408            buffer,
 1409            None,
 1410            window,
 1411            cx,
 1412        )
 1413    }
 1414
 1415    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1416        let buffer = cx.new(|cx| Buffer::local("", cx));
 1417        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1418        Self::new(
 1419            EditorMode::AutoHeight { max_lines },
 1420            buffer,
 1421            None,
 1422            window,
 1423            cx,
 1424        )
 1425    }
 1426
 1427    pub fn for_buffer(
 1428        buffer: Entity<Buffer>,
 1429        project: Option<Entity<Project>>,
 1430        window: &mut Window,
 1431        cx: &mut Context<Self>,
 1432    ) -> Self {
 1433        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1434        Self::new(EditorMode::full(), buffer, project, window, cx)
 1435    }
 1436
 1437    pub fn for_multibuffer(
 1438        buffer: Entity<MultiBuffer>,
 1439        project: Option<Entity<Project>>,
 1440        window: &mut Window,
 1441        cx: &mut Context<Self>,
 1442    ) -> Self {
 1443        Self::new(EditorMode::full(), buffer, project, window, cx)
 1444    }
 1445
 1446    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1447        let mut clone = Self::new(
 1448            self.mode,
 1449            self.buffer.clone(),
 1450            self.project.clone(),
 1451            window,
 1452            cx,
 1453        );
 1454        self.display_map.update(cx, |display_map, cx| {
 1455            let snapshot = display_map.snapshot(cx);
 1456            clone.display_map.update(cx, |display_map, cx| {
 1457                display_map.set_state(&snapshot, cx);
 1458            });
 1459        });
 1460        clone.folds_did_change(cx);
 1461        clone.selections.clone_state(&self.selections);
 1462        clone.scroll_manager.clone_state(&self.scroll_manager);
 1463        clone.searchable = self.searchable;
 1464        clone.read_only = self.read_only;
 1465        clone
 1466    }
 1467
 1468    pub fn new(
 1469        mode: EditorMode,
 1470        buffer: Entity<MultiBuffer>,
 1471        project: Option<Entity<Project>>,
 1472        window: &mut Window,
 1473        cx: &mut Context<Self>,
 1474    ) -> Self {
 1475        let style = window.text_style();
 1476        let font_size = style.font_size.to_pixels(window.rem_size());
 1477        let editor = cx.entity().downgrade();
 1478        let fold_placeholder = FoldPlaceholder {
 1479            constrain_width: true,
 1480            render: Arc::new(move |fold_id, fold_range, cx| {
 1481                let editor = editor.clone();
 1482                div()
 1483                    .id(fold_id)
 1484                    .bg(cx.theme().colors().ghost_element_background)
 1485                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1486                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1487                    .rounded_xs()
 1488                    .size_full()
 1489                    .cursor_pointer()
 1490                    .child("")
 1491                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1492                    .on_click(move |_, _window, cx| {
 1493                        editor
 1494                            .update(cx, |editor, cx| {
 1495                                editor.unfold_ranges(
 1496                                    &[fold_range.start..fold_range.end],
 1497                                    true,
 1498                                    false,
 1499                                    cx,
 1500                                );
 1501                                cx.stop_propagation();
 1502                            })
 1503                            .ok();
 1504                    })
 1505                    .into_any()
 1506            }),
 1507            merge_adjacent: true,
 1508            ..Default::default()
 1509        };
 1510        let display_map = cx.new(|cx| {
 1511            DisplayMap::new(
 1512                buffer.clone(),
 1513                style.font(),
 1514                font_size,
 1515                None,
 1516                FILE_HEADER_HEIGHT,
 1517                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1518                fold_placeholder,
 1519                cx,
 1520            )
 1521        });
 1522
 1523        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1524
 1525        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1526
 1527        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1528            .then(|| language_settings::SoftWrap::None);
 1529
 1530        let mut project_subscriptions = Vec::new();
 1531        if mode.is_full() {
 1532            if let Some(project) = project.as_ref() {
 1533                project_subscriptions.push(cx.subscribe_in(
 1534                    project,
 1535                    window,
 1536                    |editor, _, event, window, cx| match event {
 1537                        project::Event::RefreshCodeLens => {
 1538                            // we always query lens with actions, without storing them, always refreshing them
 1539                        }
 1540                        project::Event::RefreshInlayHints => {
 1541                            editor
 1542                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1543                        }
 1544                        project::Event::SnippetEdit(id, snippet_edits) => {
 1545                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1546                                let focus_handle = editor.focus_handle(cx);
 1547                                if focus_handle.is_focused(window) {
 1548                                    let snapshot = buffer.read(cx).snapshot();
 1549                                    for (range, snippet) in snippet_edits {
 1550                                        let editor_range =
 1551                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1552                                        editor
 1553                                            .insert_snippet(
 1554                                                &[editor_range],
 1555                                                snippet.clone(),
 1556                                                window,
 1557                                                cx,
 1558                                            )
 1559                                            .ok();
 1560                                    }
 1561                                }
 1562                            }
 1563                        }
 1564                        _ => {}
 1565                    },
 1566                ));
 1567                if let Some(task_inventory) = project
 1568                    .read(cx)
 1569                    .task_store()
 1570                    .read(cx)
 1571                    .task_inventory()
 1572                    .cloned()
 1573                {
 1574                    project_subscriptions.push(cx.observe_in(
 1575                        &task_inventory,
 1576                        window,
 1577                        |editor, _, window, cx| {
 1578                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1579                        },
 1580                    ));
 1581                };
 1582
 1583                project_subscriptions.push(cx.subscribe_in(
 1584                    &project.read(cx).breakpoint_store(),
 1585                    window,
 1586                    |editor, _, event, window, cx| match event {
 1587                        BreakpointStoreEvent::ClearDebugLines => {
 1588                            editor.clear_row_highlights::<ActiveDebugLine>();
 1589                            editor.refresh_inline_values(cx);
 1590                        }
 1591                        BreakpointStoreEvent::SetDebugLine => {
 1592                            if editor.go_to_active_debug_line(window, cx) {
 1593                                cx.stop_propagation();
 1594                            }
 1595
 1596                            editor.refresh_inline_values(cx);
 1597                        }
 1598                        _ => {}
 1599                    },
 1600                ));
 1601            }
 1602        }
 1603
 1604        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1605
 1606        let inlay_hint_settings =
 1607            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1608        let focus_handle = cx.focus_handle();
 1609        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1610            .detach();
 1611        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1612            .detach();
 1613        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1614            .detach();
 1615        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1616            .detach();
 1617
 1618        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1619            Some(false)
 1620        } else {
 1621            None
 1622        };
 1623
 1624        let breakpoint_store = match (mode, project.as_ref()) {
 1625            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1626            _ => None,
 1627        };
 1628
 1629        let mut code_action_providers = Vec::new();
 1630        let mut load_uncommitted_diff = None;
 1631        if let Some(project) = project.clone() {
 1632            load_uncommitted_diff = Some(
 1633                update_uncommitted_diff_for_buffer(
 1634                    cx.entity(),
 1635                    &project,
 1636                    buffer.read(cx).all_buffers(),
 1637                    buffer.clone(),
 1638                    cx,
 1639                )
 1640                .shared(),
 1641            );
 1642            code_action_providers.push(Rc::new(project) as Rc<_>);
 1643        }
 1644
 1645        let mut this = Self {
 1646            focus_handle,
 1647            show_cursor_when_unfocused: false,
 1648            last_focused_descendant: None,
 1649            buffer: buffer.clone(),
 1650            display_map: display_map.clone(),
 1651            selections,
 1652            scroll_manager: ScrollManager::new(cx),
 1653            columnar_selection_tail: None,
 1654            add_selections_state: None,
 1655            select_next_state: None,
 1656            select_prev_state: None,
 1657            selection_history: Default::default(),
 1658            autoclose_regions: Default::default(),
 1659            snippet_stack: Default::default(),
 1660            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1661            ime_transaction: Default::default(),
 1662            active_diagnostics: ActiveDiagnostic::None,
 1663            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1664            inline_diagnostics_update: Task::ready(()),
 1665            inline_diagnostics: Vec::new(),
 1666            soft_wrap_mode_override,
 1667            hard_wrap: None,
 1668            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1669            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1670            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1671            project,
 1672            blink_manager: blink_manager.clone(),
 1673            show_local_selections: true,
 1674            show_scrollbars: true,
 1675            mode,
 1676            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1677            show_gutter: mode.is_full(),
 1678            show_line_numbers: None,
 1679            use_relative_line_numbers: None,
 1680            disable_expand_excerpt_buttons: false,
 1681            show_git_diff_gutter: None,
 1682            show_code_actions: None,
 1683            show_runnables: None,
 1684            show_breakpoints: None,
 1685            show_wrap_guides: None,
 1686            show_indent_guides,
 1687            placeholder_text: None,
 1688            highlight_order: 0,
 1689            highlighted_rows: HashMap::default(),
 1690            background_highlights: Default::default(),
 1691            gutter_highlights: TreeMap::default(),
 1692            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1693            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1694            nav_history: None,
 1695            context_menu: RefCell::new(None),
 1696            context_menu_options: None,
 1697            mouse_context_menu: None,
 1698            completion_tasks: Default::default(),
 1699            inline_blame_popover: Default::default(),
 1700            signature_help_state: SignatureHelpState::default(),
 1701            auto_signature_help: None,
 1702            find_all_references_task_sources: Vec::new(),
 1703            next_completion_id: 0,
 1704            next_inlay_id: 0,
 1705            code_action_providers,
 1706            available_code_actions: Default::default(),
 1707            code_actions_task: Default::default(),
 1708            quick_selection_highlight_task: Default::default(),
 1709            debounced_selection_highlight_task: Default::default(),
 1710            document_highlights_task: Default::default(),
 1711            linked_editing_range_task: Default::default(),
 1712            pending_rename: Default::default(),
 1713            searchable: true,
 1714            cursor_shape: EditorSettings::get_global(cx)
 1715                .cursor_shape
 1716                .unwrap_or_default(),
 1717            current_line_highlight: None,
 1718            autoindent_mode: Some(AutoindentMode::EachLine),
 1719            collapse_matches: false,
 1720            workspace: None,
 1721            input_enabled: true,
 1722            use_modal_editing: mode.is_full(),
 1723            read_only: false,
 1724            use_autoclose: true,
 1725            use_auto_surround: true,
 1726            auto_replace_emoji_shortcode: false,
 1727            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1728            leader_id: None,
 1729            remote_id: None,
 1730            hover_state: Default::default(),
 1731            pending_mouse_down: None,
 1732            hovered_link_state: Default::default(),
 1733            edit_prediction_provider: None,
 1734            active_inline_completion: None,
 1735            stale_inline_completion_in_menu: None,
 1736            edit_prediction_preview: EditPredictionPreview::Inactive {
 1737                released_too_fast: false,
 1738            },
 1739            inline_diagnostics_enabled: mode.is_full(),
 1740            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1741            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1742
 1743            gutter_hovered: false,
 1744            pixel_position_of_newest_cursor: None,
 1745            last_bounds: None,
 1746            last_position_map: None,
 1747            expect_bounds_change: None,
 1748            gutter_dimensions: GutterDimensions::default(),
 1749            style: None,
 1750            show_cursor_names: false,
 1751            hovered_cursors: Default::default(),
 1752            next_editor_action_id: EditorActionId::default(),
 1753            editor_actions: Rc::default(),
 1754            inline_completions_hidden_for_vim_mode: false,
 1755            show_inline_completions_override: None,
 1756            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1757            edit_prediction_settings: EditPredictionSettings::Disabled,
 1758            edit_prediction_indent_conflict: false,
 1759            edit_prediction_requires_modifier_in_indent_conflict: true,
 1760            custom_context_menu: None,
 1761            show_git_blame_gutter: false,
 1762            show_git_blame_inline: false,
 1763            show_selection_menu: None,
 1764            show_git_blame_inline_delay_task: None,
 1765            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1766            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1767            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1768                .session
 1769                .restore_unsaved_buffers,
 1770            blame: None,
 1771            blame_subscription: None,
 1772            tasks: Default::default(),
 1773
 1774            breakpoint_store,
 1775            gutter_breakpoint_indicator: (None, None),
 1776            _subscriptions: vec![
 1777                cx.observe(&buffer, Self::on_buffer_changed),
 1778                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1779                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1780                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1781                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1782                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1783                cx.observe_window_activation(window, |editor, window, cx| {
 1784                    let active = window.is_window_active();
 1785                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1786                        if active {
 1787                            blink_manager.enable(cx);
 1788                        } else {
 1789                            blink_manager.disable(cx);
 1790                        }
 1791                    });
 1792                }),
 1793            ],
 1794            tasks_update_task: None,
 1795            linked_edit_ranges: Default::default(),
 1796            in_project_search: false,
 1797            previous_search_ranges: None,
 1798            breadcrumb_header: None,
 1799            focused_block: None,
 1800            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1801            addons: HashMap::default(),
 1802            registered_buffers: HashMap::default(),
 1803            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1804            selection_mark_mode: false,
 1805            toggle_fold_multiple_buffers: Task::ready(()),
 1806            serialize_selections: Task::ready(()),
 1807            serialize_folds: Task::ready(()),
 1808            text_style_refinement: None,
 1809            load_diff_task: load_uncommitted_diff,
 1810            temporary_diff_override: false,
 1811            mouse_cursor_hidden: false,
 1812            hide_mouse_mode: EditorSettings::get_global(cx)
 1813                .hide_mouse
 1814                .unwrap_or_default(),
 1815            change_list: ChangeList::new(),
 1816        };
 1817        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1818            this._subscriptions
 1819                .push(cx.observe(breakpoints, |_, _, cx| {
 1820                    cx.notify();
 1821                }));
 1822        }
 1823        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1824        this._subscriptions.extend(project_subscriptions);
 1825
 1826        this._subscriptions.push(cx.subscribe_in(
 1827            &cx.entity(),
 1828            window,
 1829            |editor, _, e: &EditorEvent, window, cx| match e {
 1830                EditorEvent::ScrollPositionChanged { local, .. } => {
 1831                    if *local {
 1832                        let new_anchor = editor.scroll_manager.anchor();
 1833                        let snapshot = editor.snapshot(window, cx);
 1834                        editor.update_restoration_data(cx, move |data| {
 1835                            data.scroll_position = (
 1836                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1837                                new_anchor.offset,
 1838                            );
 1839                        });
 1840                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1841                        editor.inline_blame_popover.take();
 1842                    }
 1843                }
 1844                EditorEvent::Edited { .. } => {
 1845                    if !vim_enabled(cx) {
 1846                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1847                        let pop_state = editor
 1848                            .change_list
 1849                            .last()
 1850                            .map(|previous| {
 1851                                previous.len() == selections.len()
 1852                                    && previous.iter().enumerate().all(|(ix, p)| {
 1853                                        p.to_display_point(&map).row()
 1854                                            == selections[ix].head().row()
 1855                                    })
 1856                            })
 1857                            .unwrap_or(false);
 1858                        let new_positions = selections
 1859                            .into_iter()
 1860                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1861                            .collect();
 1862                        editor
 1863                            .change_list
 1864                            .push_to_change_list(pop_state, new_positions);
 1865                    }
 1866                }
 1867                _ => (),
 1868            },
 1869        ));
 1870
 1871        if let Some(dap_store) = this
 1872            .project
 1873            .as_ref()
 1874            .map(|project| project.read(cx).dap_store())
 1875        {
 1876            let weak_editor = cx.weak_entity();
 1877
 1878            this._subscriptions
 1879                .push(
 1880                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1881                        let session_entity = cx.entity();
 1882                        weak_editor
 1883                            .update(cx, |editor, cx| {
 1884                                editor._subscriptions.push(
 1885                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1886                                );
 1887                            })
 1888                            .ok();
 1889                    }),
 1890                );
 1891
 1892            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1893                this._subscriptions
 1894                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1895            }
 1896        }
 1897
 1898        this.end_selection(window, cx);
 1899        this.scroll_manager.show_scrollbars(window, cx);
 1900        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1901
 1902        if mode.is_full() {
 1903            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1904            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1905
 1906            if this.git_blame_inline_enabled {
 1907                this.git_blame_inline_enabled = true;
 1908                this.start_git_blame_inline(false, window, cx);
 1909            }
 1910
 1911            this.go_to_active_debug_line(window, cx);
 1912
 1913            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1914                if let Some(project) = this.project.as_ref() {
 1915                    let handle = project.update(cx, |project, cx| {
 1916                        project.register_buffer_with_language_servers(&buffer, cx)
 1917                    });
 1918                    this.registered_buffers
 1919                        .insert(buffer.read(cx).remote_id(), handle);
 1920                }
 1921            }
 1922        }
 1923
 1924        this.report_editor_event("Editor Opened", None, cx);
 1925        this
 1926    }
 1927
 1928    pub fn deploy_mouse_context_menu(
 1929        &mut self,
 1930        position: gpui::Point<Pixels>,
 1931        context_menu: Entity<ContextMenu>,
 1932        window: &mut Window,
 1933        cx: &mut Context<Self>,
 1934    ) {
 1935        self.mouse_context_menu = Some(MouseContextMenu::new(
 1936            self,
 1937            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1938            context_menu,
 1939            window,
 1940            cx,
 1941        ));
 1942    }
 1943
 1944    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1945        self.mouse_context_menu
 1946            .as_ref()
 1947            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1948    }
 1949
 1950    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1951        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1952    }
 1953
 1954    fn key_context_internal(
 1955        &self,
 1956        has_active_edit_prediction: bool,
 1957        window: &Window,
 1958        cx: &App,
 1959    ) -> KeyContext {
 1960        let mut key_context = KeyContext::new_with_defaults();
 1961        key_context.add("Editor");
 1962        let mode = match self.mode {
 1963            EditorMode::SingleLine { .. } => "single_line",
 1964            EditorMode::AutoHeight { .. } => "auto_height",
 1965            EditorMode::Full { .. } => "full",
 1966        };
 1967
 1968        if EditorSettings::jupyter_enabled(cx) {
 1969            key_context.add("jupyter");
 1970        }
 1971
 1972        key_context.set("mode", mode);
 1973        if self.pending_rename.is_some() {
 1974            key_context.add("renaming");
 1975        }
 1976
 1977        match self.context_menu.borrow().as_ref() {
 1978            Some(CodeContextMenu::Completions(_)) => {
 1979                key_context.add("menu");
 1980                key_context.add("showing_completions");
 1981            }
 1982            Some(CodeContextMenu::CodeActions(_)) => {
 1983                key_context.add("menu");
 1984                key_context.add("showing_code_actions")
 1985            }
 1986            None => {}
 1987        }
 1988
 1989        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1990        if !self.focus_handle(cx).contains_focused(window, cx)
 1991            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1992        {
 1993            for addon in self.addons.values() {
 1994                addon.extend_key_context(&mut key_context, cx)
 1995            }
 1996        }
 1997
 1998        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1999            if let Some(extension) = singleton_buffer
 2000                .read(cx)
 2001                .file()
 2002                .and_then(|file| file.path().extension()?.to_str())
 2003            {
 2004                key_context.set("extension", extension.to_string());
 2005            }
 2006        } else {
 2007            key_context.add("multibuffer");
 2008        }
 2009
 2010        if has_active_edit_prediction {
 2011            if self.edit_prediction_in_conflict() {
 2012                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2013            } else {
 2014                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2015                key_context.add("copilot_suggestion");
 2016            }
 2017        }
 2018
 2019        if self.selection_mark_mode {
 2020            key_context.add("selection_mode");
 2021        }
 2022
 2023        key_context
 2024    }
 2025
 2026    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2027        self.mouse_cursor_hidden = match origin {
 2028            HideMouseCursorOrigin::TypingAction => {
 2029                matches!(
 2030                    self.hide_mouse_mode,
 2031                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2032                )
 2033            }
 2034            HideMouseCursorOrigin::MovementAction => {
 2035                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2036            }
 2037        };
 2038    }
 2039
 2040    pub fn edit_prediction_in_conflict(&self) -> bool {
 2041        if !self.show_edit_predictions_in_menu() {
 2042            return false;
 2043        }
 2044
 2045        let showing_completions = self
 2046            .context_menu
 2047            .borrow()
 2048            .as_ref()
 2049            .map_or(false, |context| {
 2050                matches!(context, CodeContextMenu::Completions(_))
 2051            });
 2052
 2053        showing_completions
 2054            || self.edit_prediction_requires_modifier()
 2055            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2056            // bindings to insert tab characters.
 2057            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2058    }
 2059
 2060    pub fn accept_edit_prediction_keybind(
 2061        &self,
 2062        window: &Window,
 2063        cx: &App,
 2064    ) -> AcceptEditPredictionBinding {
 2065        let key_context = self.key_context_internal(true, window, cx);
 2066        let in_conflict = self.edit_prediction_in_conflict();
 2067
 2068        AcceptEditPredictionBinding(
 2069            window
 2070                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2071                .into_iter()
 2072                .filter(|binding| {
 2073                    !in_conflict
 2074                        || binding
 2075                            .keystrokes()
 2076                            .first()
 2077                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2078                })
 2079                .rev()
 2080                .min_by_key(|binding| {
 2081                    binding
 2082                        .keystrokes()
 2083                        .first()
 2084                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2085                }),
 2086        )
 2087    }
 2088
 2089    pub fn new_file(
 2090        workspace: &mut Workspace,
 2091        _: &workspace::NewFile,
 2092        window: &mut Window,
 2093        cx: &mut Context<Workspace>,
 2094    ) {
 2095        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2096            "Failed to create buffer",
 2097            window,
 2098            cx,
 2099            |e, _, _| match e.error_code() {
 2100                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2101                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2102                e.error_tag("required").unwrap_or("the latest version")
 2103            )),
 2104                _ => None,
 2105            },
 2106        );
 2107    }
 2108
 2109    pub fn new_in_workspace(
 2110        workspace: &mut Workspace,
 2111        window: &mut Window,
 2112        cx: &mut Context<Workspace>,
 2113    ) -> Task<Result<Entity<Editor>>> {
 2114        let project = workspace.project().clone();
 2115        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2116
 2117        cx.spawn_in(window, async move |workspace, cx| {
 2118            let buffer = create.await?;
 2119            workspace.update_in(cx, |workspace, window, cx| {
 2120                let editor =
 2121                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2122                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2123                editor
 2124            })
 2125        })
 2126    }
 2127
 2128    fn new_file_vertical(
 2129        workspace: &mut Workspace,
 2130        _: &workspace::NewFileSplitVertical,
 2131        window: &mut Window,
 2132        cx: &mut Context<Workspace>,
 2133    ) {
 2134        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2135    }
 2136
 2137    fn new_file_horizontal(
 2138        workspace: &mut Workspace,
 2139        _: &workspace::NewFileSplitHorizontal,
 2140        window: &mut Window,
 2141        cx: &mut Context<Workspace>,
 2142    ) {
 2143        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2144    }
 2145
 2146    fn new_file_in_direction(
 2147        workspace: &mut Workspace,
 2148        direction: SplitDirection,
 2149        window: &mut Window,
 2150        cx: &mut Context<Workspace>,
 2151    ) {
 2152        let project = workspace.project().clone();
 2153        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2154
 2155        cx.spawn_in(window, async move |workspace, cx| {
 2156            let buffer = create.await?;
 2157            workspace.update_in(cx, move |workspace, window, cx| {
 2158                workspace.split_item(
 2159                    direction,
 2160                    Box::new(
 2161                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2162                    ),
 2163                    window,
 2164                    cx,
 2165                )
 2166            })?;
 2167            anyhow::Ok(())
 2168        })
 2169        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2170            match e.error_code() {
 2171                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2172                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2173                e.error_tag("required").unwrap_or("the latest version")
 2174            )),
 2175                _ => None,
 2176            }
 2177        });
 2178    }
 2179
 2180    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2181        self.leader_id
 2182    }
 2183
 2184    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2185        &self.buffer
 2186    }
 2187
 2188    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2189        self.workspace.as_ref()?.0.upgrade()
 2190    }
 2191
 2192    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2193        self.buffer().read(cx).title(cx)
 2194    }
 2195
 2196    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2197        let git_blame_gutter_max_author_length = self
 2198            .render_git_blame_gutter(cx)
 2199            .then(|| {
 2200                if let Some(blame) = self.blame.as_ref() {
 2201                    let max_author_length =
 2202                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2203                    Some(max_author_length)
 2204                } else {
 2205                    None
 2206                }
 2207            })
 2208            .flatten();
 2209
 2210        EditorSnapshot {
 2211            mode: self.mode,
 2212            show_gutter: self.show_gutter,
 2213            show_line_numbers: self.show_line_numbers,
 2214            show_git_diff_gutter: self.show_git_diff_gutter,
 2215            show_code_actions: self.show_code_actions,
 2216            show_runnables: self.show_runnables,
 2217            show_breakpoints: self.show_breakpoints,
 2218            git_blame_gutter_max_author_length,
 2219            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2220            scroll_anchor: self.scroll_manager.anchor(),
 2221            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2222            placeholder_text: self.placeholder_text.clone(),
 2223            is_focused: self.focus_handle.is_focused(window),
 2224            current_line_highlight: self
 2225                .current_line_highlight
 2226                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2227            gutter_hovered: self.gutter_hovered,
 2228        }
 2229    }
 2230
 2231    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2232        self.buffer.read(cx).language_at(point, cx)
 2233    }
 2234
 2235    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2236        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2237    }
 2238
 2239    pub fn active_excerpt(
 2240        &self,
 2241        cx: &App,
 2242    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2243        self.buffer
 2244            .read(cx)
 2245            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2246    }
 2247
 2248    pub fn mode(&self) -> EditorMode {
 2249        self.mode
 2250    }
 2251
 2252    pub fn set_mode(&mut self, mode: EditorMode) {
 2253        self.mode = mode;
 2254    }
 2255
 2256    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2257        self.collaboration_hub.as_deref()
 2258    }
 2259
 2260    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2261        self.collaboration_hub = Some(hub);
 2262    }
 2263
 2264    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2265        self.in_project_search = in_project_search;
 2266    }
 2267
 2268    pub fn set_custom_context_menu(
 2269        &mut self,
 2270        f: impl 'static
 2271        + Fn(
 2272            &mut Self,
 2273            DisplayPoint,
 2274            &mut Window,
 2275            &mut Context<Self>,
 2276        ) -> Option<Entity<ui::ContextMenu>>,
 2277    ) {
 2278        self.custom_context_menu = Some(Box::new(f))
 2279    }
 2280
 2281    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2282        self.completion_provider = provider;
 2283    }
 2284
 2285    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2286        self.semantics_provider.clone()
 2287    }
 2288
 2289    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2290        self.semantics_provider = provider;
 2291    }
 2292
 2293    pub fn set_edit_prediction_provider<T>(
 2294        &mut self,
 2295        provider: Option<Entity<T>>,
 2296        window: &mut Window,
 2297        cx: &mut Context<Self>,
 2298    ) where
 2299        T: EditPredictionProvider,
 2300    {
 2301        self.edit_prediction_provider =
 2302            provider.map(|provider| RegisteredInlineCompletionProvider {
 2303                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2304                    if this.focus_handle.is_focused(window) {
 2305                        this.update_visible_inline_completion(window, cx);
 2306                    }
 2307                }),
 2308                provider: Arc::new(provider),
 2309            });
 2310        self.update_edit_prediction_settings(cx);
 2311        self.refresh_inline_completion(false, false, window, cx);
 2312    }
 2313
 2314    pub fn placeholder_text(&self) -> Option<&str> {
 2315        self.placeholder_text.as_deref()
 2316    }
 2317
 2318    pub fn set_placeholder_text(
 2319        &mut self,
 2320        placeholder_text: impl Into<Arc<str>>,
 2321        cx: &mut Context<Self>,
 2322    ) {
 2323        let placeholder_text = Some(placeholder_text.into());
 2324        if self.placeholder_text != placeholder_text {
 2325            self.placeholder_text = placeholder_text;
 2326            cx.notify();
 2327        }
 2328    }
 2329
 2330    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2331        self.cursor_shape = cursor_shape;
 2332
 2333        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2334        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2335
 2336        cx.notify();
 2337    }
 2338
 2339    pub fn set_current_line_highlight(
 2340        &mut self,
 2341        current_line_highlight: Option<CurrentLineHighlight>,
 2342    ) {
 2343        self.current_line_highlight = current_line_highlight;
 2344    }
 2345
 2346    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2347        self.collapse_matches = collapse_matches;
 2348    }
 2349
 2350    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2351        let buffers = self.buffer.read(cx).all_buffers();
 2352        let Some(project) = self.project.as_ref() else {
 2353            return;
 2354        };
 2355        project.update(cx, |project, cx| {
 2356            for buffer in buffers {
 2357                self.registered_buffers
 2358                    .entry(buffer.read(cx).remote_id())
 2359                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2360            }
 2361        })
 2362    }
 2363
 2364    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2365        if self.collapse_matches {
 2366            return range.start..range.start;
 2367        }
 2368        range.clone()
 2369    }
 2370
 2371    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2372        if self.display_map.read(cx).clip_at_line_ends != clip {
 2373            self.display_map
 2374                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2375        }
 2376    }
 2377
 2378    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2379        self.input_enabled = input_enabled;
 2380    }
 2381
 2382    pub fn set_inline_completions_hidden_for_vim_mode(
 2383        &mut self,
 2384        hidden: bool,
 2385        window: &mut Window,
 2386        cx: &mut Context<Self>,
 2387    ) {
 2388        if hidden != self.inline_completions_hidden_for_vim_mode {
 2389            self.inline_completions_hidden_for_vim_mode = hidden;
 2390            if hidden {
 2391                self.update_visible_inline_completion(window, cx);
 2392            } else {
 2393                self.refresh_inline_completion(true, false, window, cx);
 2394            }
 2395        }
 2396    }
 2397
 2398    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2399        self.menu_inline_completions_policy = value;
 2400    }
 2401
 2402    pub fn set_autoindent(&mut self, autoindent: bool) {
 2403        if autoindent {
 2404            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2405        } else {
 2406            self.autoindent_mode = None;
 2407        }
 2408    }
 2409
 2410    pub fn read_only(&self, cx: &App) -> bool {
 2411        self.read_only || self.buffer.read(cx).read_only()
 2412    }
 2413
 2414    pub fn set_read_only(&mut self, read_only: bool) {
 2415        self.read_only = read_only;
 2416    }
 2417
 2418    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2419        self.use_autoclose = autoclose;
 2420    }
 2421
 2422    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2423        self.use_auto_surround = auto_surround;
 2424    }
 2425
 2426    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2427        self.auto_replace_emoji_shortcode = auto_replace;
 2428    }
 2429
 2430    pub fn toggle_edit_predictions(
 2431        &mut self,
 2432        _: &ToggleEditPrediction,
 2433        window: &mut Window,
 2434        cx: &mut Context<Self>,
 2435    ) {
 2436        if self.show_inline_completions_override.is_some() {
 2437            self.set_show_edit_predictions(None, window, cx);
 2438        } else {
 2439            let show_edit_predictions = !self.edit_predictions_enabled();
 2440            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2441        }
 2442    }
 2443
 2444    pub fn set_show_edit_predictions(
 2445        &mut self,
 2446        show_edit_predictions: Option<bool>,
 2447        window: &mut Window,
 2448        cx: &mut Context<Self>,
 2449    ) {
 2450        self.show_inline_completions_override = show_edit_predictions;
 2451        self.update_edit_prediction_settings(cx);
 2452
 2453        if let Some(false) = show_edit_predictions {
 2454            self.discard_inline_completion(false, cx);
 2455        } else {
 2456            self.refresh_inline_completion(false, true, window, cx);
 2457        }
 2458    }
 2459
 2460    fn inline_completions_disabled_in_scope(
 2461        &self,
 2462        buffer: &Entity<Buffer>,
 2463        buffer_position: language::Anchor,
 2464        cx: &App,
 2465    ) -> bool {
 2466        let snapshot = buffer.read(cx).snapshot();
 2467        let settings = snapshot.settings_at(buffer_position, cx);
 2468
 2469        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2470            return false;
 2471        };
 2472
 2473        scope.override_name().map_or(false, |scope_name| {
 2474            settings
 2475                .edit_predictions_disabled_in
 2476                .iter()
 2477                .any(|s| s == scope_name)
 2478        })
 2479    }
 2480
 2481    pub fn set_use_modal_editing(&mut self, to: bool) {
 2482        self.use_modal_editing = to;
 2483    }
 2484
 2485    pub fn use_modal_editing(&self) -> bool {
 2486        self.use_modal_editing
 2487    }
 2488
 2489    fn selections_did_change(
 2490        &mut self,
 2491        local: bool,
 2492        old_cursor_position: &Anchor,
 2493        show_completions: bool,
 2494        window: &mut Window,
 2495        cx: &mut Context<Self>,
 2496    ) {
 2497        window.invalidate_character_coordinates();
 2498
 2499        // Copy selections to primary selection buffer
 2500        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2501        if local {
 2502            let selections = self.selections.all::<usize>(cx);
 2503            let buffer_handle = self.buffer.read(cx).read(cx);
 2504
 2505            let mut text = String::new();
 2506            for (index, selection) in selections.iter().enumerate() {
 2507                let text_for_selection = buffer_handle
 2508                    .text_for_range(selection.start..selection.end)
 2509                    .collect::<String>();
 2510
 2511                text.push_str(&text_for_selection);
 2512                if index != selections.len() - 1 {
 2513                    text.push('\n');
 2514                }
 2515            }
 2516
 2517            if !text.is_empty() {
 2518                cx.write_to_primary(ClipboardItem::new_string(text));
 2519            }
 2520        }
 2521
 2522        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2523            self.buffer.update(cx, |buffer, cx| {
 2524                buffer.set_active_selections(
 2525                    &self.selections.disjoint_anchors(),
 2526                    self.selections.line_mode,
 2527                    self.cursor_shape,
 2528                    cx,
 2529                )
 2530            });
 2531        }
 2532        let display_map = self
 2533            .display_map
 2534            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2535        let buffer = &display_map.buffer_snapshot;
 2536        self.add_selections_state = None;
 2537        self.select_next_state = None;
 2538        self.select_prev_state = None;
 2539        self.select_syntax_node_history.try_clear();
 2540        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2541        self.snippet_stack
 2542            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2543        self.take_rename(false, window, cx);
 2544
 2545        let new_cursor_position = self.selections.newest_anchor().head();
 2546
 2547        self.push_to_nav_history(
 2548            *old_cursor_position,
 2549            Some(new_cursor_position.to_point(buffer)),
 2550            false,
 2551            cx,
 2552        );
 2553
 2554        if local {
 2555            let new_cursor_position = self.selections.newest_anchor().head();
 2556            let mut context_menu = self.context_menu.borrow_mut();
 2557            let completion_menu = match context_menu.as_ref() {
 2558                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2559                _ => {
 2560                    *context_menu = None;
 2561                    None
 2562                }
 2563            };
 2564            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2565                if !self.registered_buffers.contains_key(&buffer_id) {
 2566                    if let Some(project) = self.project.as_ref() {
 2567                        project.update(cx, |project, cx| {
 2568                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2569                                return;
 2570                            };
 2571                            self.registered_buffers.insert(
 2572                                buffer_id,
 2573                                project.register_buffer_with_language_servers(&buffer, cx),
 2574                            );
 2575                        })
 2576                    }
 2577                }
 2578            }
 2579
 2580            if let Some(completion_menu) = completion_menu {
 2581                let cursor_position = new_cursor_position.to_offset(buffer);
 2582                let (word_range, kind) =
 2583                    buffer.surrounding_word(completion_menu.initial_position, true);
 2584                if kind == Some(CharKind::Word)
 2585                    && word_range.to_inclusive().contains(&cursor_position)
 2586                {
 2587                    let mut completion_menu = completion_menu.clone();
 2588                    drop(context_menu);
 2589
 2590                    let query = Self::completion_query(buffer, cursor_position);
 2591                    cx.spawn(async move |this, cx| {
 2592                        completion_menu
 2593                            .filter(query.as_deref(), cx.background_executor().clone())
 2594                            .await;
 2595
 2596                        this.update(cx, |this, cx| {
 2597                            let mut context_menu = this.context_menu.borrow_mut();
 2598                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2599                            else {
 2600                                return;
 2601                            };
 2602
 2603                            if menu.id > completion_menu.id {
 2604                                return;
 2605                            }
 2606
 2607                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2608                            drop(context_menu);
 2609                            cx.notify();
 2610                        })
 2611                    })
 2612                    .detach();
 2613
 2614                    if show_completions {
 2615                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2616                    }
 2617                } else {
 2618                    drop(context_menu);
 2619                    self.hide_context_menu(window, cx);
 2620                }
 2621            } else {
 2622                drop(context_menu);
 2623            }
 2624
 2625            hide_hover(self, cx);
 2626
 2627            if old_cursor_position.to_display_point(&display_map).row()
 2628                != new_cursor_position.to_display_point(&display_map).row()
 2629            {
 2630                self.available_code_actions.take();
 2631            }
 2632            self.refresh_code_actions(window, cx);
 2633            self.refresh_document_highlights(cx);
 2634            self.refresh_selected_text_highlights(false, window, cx);
 2635            refresh_matching_bracket_highlights(self, window, cx);
 2636            self.update_visible_inline_completion(window, cx);
 2637            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2638            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2639            self.inline_blame_popover.take();
 2640            if self.git_blame_inline_enabled {
 2641                self.start_inline_blame_timer(window, cx);
 2642            }
 2643        }
 2644
 2645        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2646        cx.emit(EditorEvent::SelectionsChanged { local });
 2647
 2648        let selections = &self.selections.disjoint;
 2649        if selections.len() == 1 {
 2650            cx.emit(SearchEvent::ActiveMatchChanged)
 2651        }
 2652        if local {
 2653            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2654                let inmemory_selections = selections
 2655                    .iter()
 2656                    .map(|s| {
 2657                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2658                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2659                    })
 2660                    .collect();
 2661                self.update_restoration_data(cx, |data| {
 2662                    data.selections = inmemory_selections;
 2663                });
 2664
 2665                if WorkspaceSettings::get(None, cx).restore_on_startup
 2666                    != RestoreOnStartupBehavior::None
 2667                {
 2668                    if let Some(workspace_id) =
 2669                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2670                    {
 2671                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2672                        let selections = selections.clone();
 2673                        let background_executor = cx.background_executor().clone();
 2674                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2675                        self.serialize_selections = cx.background_spawn(async move {
 2676                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2677                    let db_selections = selections
 2678                        .iter()
 2679                        .map(|selection| {
 2680                            (
 2681                                selection.start.to_offset(&snapshot),
 2682                                selection.end.to_offset(&snapshot),
 2683                            )
 2684                        })
 2685                        .collect();
 2686
 2687                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2688                        .await
 2689                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2690                        .log_err();
 2691                });
 2692                    }
 2693                }
 2694            }
 2695        }
 2696
 2697        cx.notify();
 2698    }
 2699
 2700    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2701        use text::ToOffset as _;
 2702        use text::ToPoint as _;
 2703
 2704        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2705            return;
 2706        }
 2707
 2708        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2709            return;
 2710        };
 2711
 2712        let snapshot = singleton.read(cx).snapshot();
 2713        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2714            let display_snapshot = display_map.snapshot(cx);
 2715
 2716            display_snapshot
 2717                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2718                .map(|fold| {
 2719                    fold.range.start.text_anchor.to_point(&snapshot)
 2720                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2721                })
 2722                .collect()
 2723        });
 2724        self.update_restoration_data(cx, |data| {
 2725            data.folds = inmemory_folds;
 2726        });
 2727
 2728        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2729            return;
 2730        };
 2731        let background_executor = cx.background_executor().clone();
 2732        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2733        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2734            display_map
 2735                .snapshot(cx)
 2736                .folds_in_range(0..snapshot.len())
 2737                .map(|fold| {
 2738                    (
 2739                        fold.range.start.text_anchor.to_offset(&snapshot),
 2740                        fold.range.end.text_anchor.to_offset(&snapshot),
 2741                    )
 2742                })
 2743                .collect()
 2744        });
 2745        self.serialize_folds = cx.background_spawn(async move {
 2746            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2747            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2748                .await
 2749                .with_context(|| {
 2750                    format!(
 2751                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2752                    )
 2753                })
 2754                .log_err();
 2755        });
 2756    }
 2757
 2758    pub fn sync_selections(
 2759        &mut self,
 2760        other: Entity<Editor>,
 2761        cx: &mut Context<Self>,
 2762    ) -> gpui::Subscription {
 2763        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2764        self.selections.change_with(cx, |selections| {
 2765            selections.select_anchors(other_selections);
 2766        });
 2767
 2768        let other_subscription =
 2769            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2770                EditorEvent::SelectionsChanged { local: true } => {
 2771                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2772                    if other_selections.is_empty() {
 2773                        return;
 2774                    }
 2775                    this.selections.change_with(cx, |selections| {
 2776                        selections.select_anchors(other_selections);
 2777                    });
 2778                }
 2779                _ => {}
 2780            });
 2781
 2782        let this_subscription =
 2783            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2784                EditorEvent::SelectionsChanged { local: true } => {
 2785                    let these_selections = this.selections.disjoint.to_vec();
 2786                    if these_selections.is_empty() {
 2787                        return;
 2788                    }
 2789                    other.update(cx, |other_editor, cx| {
 2790                        other_editor.selections.change_with(cx, |selections| {
 2791                            selections.select_anchors(these_selections);
 2792                        })
 2793                    });
 2794                }
 2795                _ => {}
 2796            });
 2797
 2798        Subscription::join(other_subscription, this_subscription)
 2799    }
 2800
 2801    pub fn change_selections<R>(
 2802        &mut self,
 2803        autoscroll: Option<Autoscroll>,
 2804        window: &mut Window,
 2805        cx: &mut Context<Self>,
 2806        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2807    ) -> R {
 2808        self.change_selections_inner(autoscroll, true, window, cx, change)
 2809    }
 2810
 2811    fn change_selections_inner<R>(
 2812        &mut self,
 2813        autoscroll: Option<Autoscroll>,
 2814        request_completions: bool,
 2815        window: &mut Window,
 2816        cx: &mut Context<Self>,
 2817        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2818    ) -> R {
 2819        let old_cursor_position = self.selections.newest_anchor().head();
 2820        self.push_to_selection_history();
 2821
 2822        let (changed, result) = self.selections.change_with(cx, change);
 2823
 2824        if changed {
 2825            if let Some(autoscroll) = autoscroll {
 2826                self.request_autoscroll(autoscroll, cx);
 2827            }
 2828            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2829
 2830            if self.should_open_signature_help_automatically(
 2831                &old_cursor_position,
 2832                self.signature_help_state.backspace_pressed(),
 2833                cx,
 2834            ) {
 2835                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2836            }
 2837            self.signature_help_state.set_backspace_pressed(false);
 2838        }
 2839
 2840        result
 2841    }
 2842
 2843    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2844    where
 2845        I: IntoIterator<Item = (Range<S>, T)>,
 2846        S: ToOffset,
 2847        T: Into<Arc<str>>,
 2848    {
 2849        if self.read_only(cx) {
 2850            return;
 2851        }
 2852
 2853        self.buffer
 2854            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2855    }
 2856
 2857    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2858    where
 2859        I: IntoIterator<Item = (Range<S>, T)>,
 2860        S: ToOffset,
 2861        T: Into<Arc<str>>,
 2862    {
 2863        if self.read_only(cx) {
 2864            return;
 2865        }
 2866
 2867        self.buffer.update(cx, |buffer, cx| {
 2868            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2869        });
 2870    }
 2871
 2872    pub fn edit_with_block_indent<I, S, T>(
 2873        &mut self,
 2874        edits: I,
 2875        original_indent_columns: Vec<Option<u32>>,
 2876        cx: &mut Context<Self>,
 2877    ) where
 2878        I: IntoIterator<Item = (Range<S>, T)>,
 2879        S: ToOffset,
 2880        T: Into<Arc<str>>,
 2881    {
 2882        if self.read_only(cx) {
 2883            return;
 2884        }
 2885
 2886        self.buffer.update(cx, |buffer, cx| {
 2887            buffer.edit(
 2888                edits,
 2889                Some(AutoindentMode::Block {
 2890                    original_indent_columns,
 2891                }),
 2892                cx,
 2893            )
 2894        });
 2895    }
 2896
 2897    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2898        self.hide_context_menu(window, cx);
 2899
 2900        match phase {
 2901            SelectPhase::Begin {
 2902                position,
 2903                add,
 2904                click_count,
 2905            } => self.begin_selection(position, add, click_count, window, cx),
 2906            SelectPhase::BeginColumnar {
 2907                position,
 2908                goal_column,
 2909                reset,
 2910            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2911            SelectPhase::Extend {
 2912                position,
 2913                click_count,
 2914            } => self.extend_selection(position, click_count, window, cx),
 2915            SelectPhase::Update {
 2916                position,
 2917                goal_column,
 2918                scroll_delta,
 2919            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2920            SelectPhase::End => self.end_selection(window, cx),
 2921        }
 2922    }
 2923
 2924    fn extend_selection(
 2925        &mut self,
 2926        position: DisplayPoint,
 2927        click_count: usize,
 2928        window: &mut Window,
 2929        cx: &mut Context<Self>,
 2930    ) {
 2931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2932        let tail = self.selections.newest::<usize>(cx).tail();
 2933        self.begin_selection(position, false, click_count, window, cx);
 2934
 2935        let position = position.to_offset(&display_map, Bias::Left);
 2936        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2937
 2938        let mut pending_selection = self
 2939            .selections
 2940            .pending_anchor()
 2941            .expect("extend_selection not called with pending selection");
 2942        if position >= tail {
 2943            pending_selection.start = tail_anchor;
 2944        } else {
 2945            pending_selection.end = tail_anchor;
 2946            pending_selection.reversed = true;
 2947        }
 2948
 2949        let mut pending_mode = self.selections.pending_mode().unwrap();
 2950        match &mut pending_mode {
 2951            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2952            _ => {}
 2953        }
 2954
 2955        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 2956
 2957        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 2958            s.set_pending(pending_selection, pending_mode)
 2959        });
 2960    }
 2961
 2962    fn begin_selection(
 2963        &mut self,
 2964        position: DisplayPoint,
 2965        add: bool,
 2966        click_count: usize,
 2967        window: &mut Window,
 2968        cx: &mut Context<Self>,
 2969    ) {
 2970        if !self.focus_handle.is_focused(window) {
 2971            self.last_focused_descendant = None;
 2972            window.focus(&self.focus_handle);
 2973        }
 2974
 2975        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2976        let buffer = &display_map.buffer_snapshot;
 2977        let position = display_map.clip_point(position, Bias::Left);
 2978
 2979        let start;
 2980        let end;
 2981        let mode;
 2982        let mut auto_scroll;
 2983        match click_count {
 2984            1 => {
 2985                start = buffer.anchor_before(position.to_point(&display_map));
 2986                end = start;
 2987                mode = SelectMode::Character;
 2988                auto_scroll = true;
 2989            }
 2990            2 => {
 2991                let range = movement::surrounding_word(&display_map, position);
 2992                start = buffer.anchor_before(range.start.to_point(&display_map));
 2993                end = buffer.anchor_before(range.end.to_point(&display_map));
 2994                mode = SelectMode::Word(start..end);
 2995                auto_scroll = true;
 2996            }
 2997            3 => {
 2998                let position = display_map
 2999                    .clip_point(position, Bias::Left)
 3000                    .to_point(&display_map);
 3001                let line_start = display_map.prev_line_boundary(position).0;
 3002                let next_line_start = buffer.clip_point(
 3003                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3004                    Bias::Left,
 3005                );
 3006                start = buffer.anchor_before(line_start);
 3007                end = buffer.anchor_before(next_line_start);
 3008                mode = SelectMode::Line(start..end);
 3009                auto_scroll = true;
 3010            }
 3011            _ => {
 3012                start = buffer.anchor_before(0);
 3013                end = buffer.anchor_before(buffer.len());
 3014                mode = SelectMode::All;
 3015                auto_scroll = false;
 3016            }
 3017        }
 3018        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3019
 3020        let point_to_delete: Option<usize> = {
 3021            let selected_points: Vec<Selection<Point>> =
 3022                self.selections.disjoint_in_range(start..end, cx);
 3023
 3024            if !add || click_count > 1 {
 3025                None
 3026            } else if !selected_points.is_empty() {
 3027                Some(selected_points[0].id)
 3028            } else {
 3029                let clicked_point_already_selected =
 3030                    self.selections.disjoint.iter().find(|selection| {
 3031                        selection.start.to_point(buffer) == start.to_point(buffer)
 3032                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3033                    });
 3034
 3035                clicked_point_already_selected.map(|selection| selection.id)
 3036            }
 3037        };
 3038
 3039        let selections_count = self.selections.count();
 3040
 3041        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3042            if let Some(point_to_delete) = point_to_delete {
 3043                s.delete(point_to_delete);
 3044
 3045                if selections_count == 1 {
 3046                    s.set_pending_anchor_range(start..end, mode);
 3047                }
 3048            } else {
 3049                if !add {
 3050                    s.clear_disjoint();
 3051                }
 3052
 3053                s.set_pending_anchor_range(start..end, mode);
 3054            }
 3055        });
 3056    }
 3057
 3058    fn begin_columnar_selection(
 3059        &mut self,
 3060        position: DisplayPoint,
 3061        goal_column: u32,
 3062        reset: bool,
 3063        window: &mut Window,
 3064        cx: &mut Context<Self>,
 3065    ) {
 3066        if !self.focus_handle.is_focused(window) {
 3067            self.last_focused_descendant = None;
 3068            window.focus(&self.focus_handle);
 3069        }
 3070
 3071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3072
 3073        if reset {
 3074            let pointer_position = display_map
 3075                .buffer_snapshot
 3076                .anchor_before(position.to_point(&display_map));
 3077
 3078            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3079                s.clear_disjoint();
 3080                s.set_pending_anchor_range(
 3081                    pointer_position..pointer_position,
 3082                    SelectMode::Character,
 3083                );
 3084            });
 3085        }
 3086
 3087        let tail = self.selections.newest::<Point>(cx).tail();
 3088        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3089
 3090        if !reset {
 3091            self.select_columns(
 3092                tail.to_display_point(&display_map),
 3093                position,
 3094                goal_column,
 3095                &display_map,
 3096                window,
 3097                cx,
 3098            );
 3099        }
 3100    }
 3101
 3102    fn update_selection(
 3103        &mut self,
 3104        position: DisplayPoint,
 3105        goal_column: u32,
 3106        scroll_delta: gpui::Point<f32>,
 3107        window: &mut Window,
 3108        cx: &mut Context<Self>,
 3109    ) {
 3110        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3111
 3112        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3113            let tail = tail.to_display_point(&display_map);
 3114            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3115        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3116            let buffer = self.buffer.read(cx).snapshot(cx);
 3117            let head;
 3118            let tail;
 3119            let mode = self.selections.pending_mode().unwrap();
 3120            match &mode {
 3121                SelectMode::Character => {
 3122                    head = position.to_point(&display_map);
 3123                    tail = pending.tail().to_point(&buffer);
 3124                }
 3125                SelectMode::Word(original_range) => {
 3126                    let original_display_range = original_range.start.to_display_point(&display_map)
 3127                        ..original_range.end.to_display_point(&display_map);
 3128                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3129                        ..original_display_range.end.to_point(&display_map);
 3130                    if movement::is_inside_word(&display_map, position)
 3131                        || original_display_range.contains(&position)
 3132                    {
 3133                        let word_range = movement::surrounding_word(&display_map, position);
 3134                        if word_range.start < original_display_range.start {
 3135                            head = word_range.start.to_point(&display_map);
 3136                        } else {
 3137                            head = word_range.end.to_point(&display_map);
 3138                        }
 3139                    } else {
 3140                        head = position.to_point(&display_map);
 3141                    }
 3142
 3143                    if head <= original_buffer_range.start {
 3144                        tail = original_buffer_range.end;
 3145                    } else {
 3146                        tail = original_buffer_range.start;
 3147                    }
 3148                }
 3149                SelectMode::Line(original_range) => {
 3150                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3151
 3152                    let position = display_map
 3153                        .clip_point(position, Bias::Left)
 3154                        .to_point(&display_map);
 3155                    let line_start = display_map.prev_line_boundary(position).0;
 3156                    let next_line_start = buffer.clip_point(
 3157                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3158                        Bias::Left,
 3159                    );
 3160
 3161                    if line_start < original_range.start {
 3162                        head = line_start
 3163                    } else {
 3164                        head = next_line_start
 3165                    }
 3166
 3167                    if head <= original_range.start {
 3168                        tail = original_range.end;
 3169                    } else {
 3170                        tail = original_range.start;
 3171                    }
 3172                }
 3173                SelectMode::All => {
 3174                    return;
 3175                }
 3176            };
 3177
 3178            if head < tail {
 3179                pending.start = buffer.anchor_before(head);
 3180                pending.end = buffer.anchor_before(tail);
 3181                pending.reversed = true;
 3182            } else {
 3183                pending.start = buffer.anchor_before(tail);
 3184                pending.end = buffer.anchor_before(head);
 3185                pending.reversed = false;
 3186            }
 3187
 3188            self.change_selections(None, window, cx, |s| {
 3189                s.set_pending(pending, mode);
 3190            });
 3191        } else {
 3192            log::error!("update_selection dispatched with no pending selection");
 3193            return;
 3194        }
 3195
 3196        self.apply_scroll_delta(scroll_delta, window, cx);
 3197        cx.notify();
 3198    }
 3199
 3200    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3201        self.columnar_selection_tail.take();
 3202        if self.selections.pending_anchor().is_some() {
 3203            let selections = self.selections.all::<usize>(cx);
 3204            self.change_selections(None, window, cx, |s| {
 3205                s.select(selections);
 3206                s.clear_pending();
 3207            });
 3208        }
 3209    }
 3210
 3211    fn select_columns(
 3212        &mut self,
 3213        tail: DisplayPoint,
 3214        head: DisplayPoint,
 3215        goal_column: u32,
 3216        display_map: &DisplaySnapshot,
 3217        window: &mut Window,
 3218        cx: &mut Context<Self>,
 3219    ) {
 3220        let start_row = cmp::min(tail.row(), head.row());
 3221        let end_row = cmp::max(tail.row(), head.row());
 3222        let start_column = cmp::min(tail.column(), goal_column);
 3223        let end_column = cmp::max(tail.column(), goal_column);
 3224        let reversed = start_column < tail.column();
 3225
 3226        let selection_ranges = (start_row.0..=end_row.0)
 3227            .map(DisplayRow)
 3228            .filter_map(|row| {
 3229                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3230                    let start = display_map
 3231                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3232                        .to_point(display_map);
 3233                    let end = display_map
 3234                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3235                        .to_point(display_map);
 3236                    if reversed {
 3237                        Some(end..start)
 3238                    } else {
 3239                        Some(start..end)
 3240                    }
 3241                } else {
 3242                    None
 3243                }
 3244            })
 3245            .collect::<Vec<_>>();
 3246
 3247        self.change_selections(None, window, cx, |s| {
 3248            s.select_ranges(selection_ranges);
 3249        });
 3250        cx.notify();
 3251    }
 3252
 3253    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3254        self.selections
 3255            .all_adjusted(cx)
 3256            .iter()
 3257            .any(|selection| !selection.is_empty())
 3258    }
 3259
 3260    pub fn has_pending_nonempty_selection(&self) -> bool {
 3261        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3262            Some(Selection { start, end, .. }) => start != end,
 3263            None => false,
 3264        };
 3265
 3266        pending_nonempty_selection
 3267            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3268    }
 3269
 3270    pub fn has_pending_selection(&self) -> bool {
 3271        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3272    }
 3273
 3274    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3275        self.selection_mark_mode = false;
 3276
 3277        if self.clear_expanded_diff_hunks(cx) {
 3278            cx.notify();
 3279            return;
 3280        }
 3281        if self.dismiss_menus_and_popups(true, window, cx) {
 3282            return;
 3283        }
 3284
 3285        if self.mode.is_full()
 3286            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3287        {
 3288            return;
 3289        }
 3290
 3291        cx.propagate();
 3292    }
 3293
 3294    pub fn dismiss_menus_and_popups(
 3295        &mut self,
 3296        is_user_requested: bool,
 3297        window: &mut Window,
 3298        cx: &mut Context<Self>,
 3299    ) -> bool {
 3300        if self.take_rename(false, window, cx).is_some() {
 3301            return true;
 3302        }
 3303
 3304        if hide_hover(self, cx) {
 3305            return true;
 3306        }
 3307
 3308        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3309            return true;
 3310        }
 3311
 3312        if self.hide_context_menu(window, cx).is_some() {
 3313            return true;
 3314        }
 3315
 3316        if self.mouse_context_menu.take().is_some() {
 3317            return true;
 3318        }
 3319
 3320        if is_user_requested && self.discard_inline_completion(true, cx) {
 3321            return true;
 3322        }
 3323
 3324        if self.snippet_stack.pop().is_some() {
 3325            return true;
 3326        }
 3327
 3328        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3329            self.dismiss_diagnostics(cx);
 3330            return true;
 3331        }
 3332
 3333        false
 3334    }
 3335
 3336    fn linked_editing_ranges_for(
 3337        &self,
 3338        selection: Range<text::Anchor>,
 3339        cx: &App,
 3340    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3341        if self.linked_edit_ranges.is_empty() {
 3342            return None;
 3343        }
 3344        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3345            selection.end.buffer_id.and_then(|end_buffer_id| {
 3346                if selection.start.buffer_id != Some(end_buffer_id) {
 3347                    return None;
 3348                }
 3349                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3350                let snapshot = buffer.read(cx).snapshot();
 3351                self.linked_edit_ranges
 3352                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3353                    .map(|ranges| (ranges, snapshot, buffer))
 3354            })?;
 3355        use text::ToOffset as TO;
 3356        // find offset from the start of current range to current cursor position
 3357        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3358
 3359        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3360        let start_difference = start_offset - start_byte_offset;
 3361        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3362        let end_difference = end_offset - start_byte_offset;
 3363        // Current range has associated linked ranges.
 3364        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3365        for range in linked_ranges.iter() {
 3366            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3367            let end_offset = start_offset + end_difference;
 3368            let start_offset = start_offset + start_difference;
 3369            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3370                continue;
 3371            }
 3372            if self.selections.disjoint_anchor_ranges().any(|s| {
 3373                if s.start.buffer_id != selection.start.buffer_id
 3374                    || s.end.buffer_id != selection.end.buffer_id
 3375                {
 3376                    return false;
 3377                }
 3378                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3379                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3380            }) {
 3381                continue;
 3382            }
 3383            let start = buffer_snapshot.anchor_after(start_offset);
 3384            let end = buffer_snapshot.anchor_after(end_offset);
 3385            linked_edits
 3386                .entry(buffer.clone())
 3387                .or_default()
 3388                .push(start..end);
 3389        }
 3390        Some(linked_edits)
 3391    }
 3392
 3393    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3394        let text: Arc<str> = text.into();
 3395
 3396        if self.read_only(cx) {
 3397            return;
 3398        }
 3399
 3400        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3401
 3402        let selections = self.selections.all_adjusted(cx);
 3403        let mut bracket_inserted = false;
 3404        let mut edits = Vec::new();
 3405        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3406        let mut new_selections = Vec::with_capacity(selections.len());
 3407        let mut new_autoclose_regions = Vec::new();
 3408        let snapshot = self.buffer.read(cx).read(cx);
 3409        let mut clear_linked_edit_ranges = false;
 3410
 3411        for (selection, autoclose_region) in
 3412            self.selections_with_autoclose_regions(selections, &snapshot)
 3413        {
 3414            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3415                // Determine if the inserted text matches the opening or closing
 3416                // bracket of any of this language's bracket pairs.
 3417                let mut bracket_pair = None;
 3418                let mut is_bracket_pair_start = false;
 3419                let mut is_bracket_pair_end = false;
 3420                if !text.is_empty() {
 3421                    let mut bracket_pair_matching_end = None;
 3422                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3423                    //  and they are removing the character that triggered IME popup.
 3424                    for (pair, enabled) in scope.brackets() {
 3425                        if !pair.close && !pair.surround {
 3426                            continue;
 3427                        }
 3428
 3429                        if enabled && pair.start.ends_with(text.as_ref()) {
 3430                            let prefix_len = pair.start.len() - text.len();
 3431                            let preceding_text_matches_prefix = prefix_len == 0
 3432                                || (selection.start.column >= (prefix_len as u32)
 3433                                    && snapshot.contains_str_at(
 3434                                        Point::new(
 3435                                            selection.start.row,
 3436                                            selection.start.column - (prefix_len as u32),
 3437                                        ),
 3438                                        &pair.start[..prefix_len],
 3439                                    ));
 3440                            if preceding_text_matches_prefix {
 3441                                bracket_pair = Some(pair.clone());
 3442                                is_bracket_pair_start = true;
 3443                                break;
 3444                            }
 3445                        }
 3446                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3447                        {
 3448                            // take first bracket pair matching end, but don't break in case a later bracket
 3449                            // pair matches start
 3450                            bracket_pair_matching_end = Some(pair.clone());
 3451                        }
 3452                    }
 3453                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3454                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3455                        is_bracket_pair_end = true;
 3456                    }
 3457                }
 3458
 3459                if let Some(bracket_pair) = bracket_pair {
 3460                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3461                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3462                    let auto_surround =
 3463                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3464                    if selection.is_empty() {
 3465                        if is_bracket_pair_start {
 3466                            // If the inserted text is a suffix of an opening bracket and the
 3467                            // selection is preceded by the rest of the opening bracket, then
 3468                            // insert the closing bracket.
 3469                            let following_text_allows_autoclose = snapshot
 3470                                .chars_at(selection.start)
 3471                                .next()
 3472                                .map_or(true, |c| scope.should_autoclose_before(c));
 3473
 3474                            let preceding_text_allows_autoclose = selection.start.column == 0
 3475                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3476                                    true,
 3477                                    |c| {
 3478                                        bracket_pair.start != bracket_pair.end
 3479                                            || !snapshot
 3480                                                .char_classifier_at(selection.start)
 3481                                                .is_word(c)
 3482                                    },
 3483                                );
 3484
 3485                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3486                                && bracket_pair.start.len() == 1
 3487                            {
 3488                                let target = bracket_pair.start.chars().next().unwrap();
 3489                                let current_line_count = snapshot
 3490                                    .reversed_chars_at(selection.start)
 3491                                    .take_while(|&c| c != '\n')
 3492                                    .filter(|&c| c == target)
 3493                                    .count();
 3494                                current_line_count % 2 == 1
 3495                            } else {
 3496                                false
 3497                            };
 3498
 3499                            if autoclose
 3500                                && bracket_pair.close
 3501                                && following_text_allows_autoclose
 3502                                && preceding_text_allows_autoclose
 3503                                && !is_closing_quote
 3504                            {
 3505                                let anchor = snapshot.anchor_before(selection.end);
 3506                                new_selections.push((selection.map(|_| anchor), text.len()));
 3507                                new_autoclose_regions.push((
 3508                                    anchor,
 3509                                    text.len(),
 3510                                    selection.id,
 3511                                    bracket_pair.clone(),
 3512                                ));
 3513                                edits.push((
 3514                                    selection.range(),
 3515                                    format!("{}{}", text, bracket_pair.end).into(),
 3516                                ));
 3517                                bracket_inserted = true;
 3518                                continue;
 3519                            }
 3520                        }
 3521
 3522                        if let Some(region) = autoclose_region {
 3523                            // If the selection is followed by an auto-inserted closing bracket,
 3524                            // then don't insert that closing bracket again; just move the selection
 3525                            // past the closing bracket.
 3526                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3527                                && text.as_ref() == region.pair.end.as_str();
 3528                            if should_skip {
 3529                                let anchor = snapshot.anchor_after(selection.end);
 3530                                new_selections
 3531                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3532                                continue;
 3533                            }
 3534                        }
 3535
 3536                        let always_treat_brackets_as_autoclosed = snapshot
 3537                            .language_settings_at(selection.start, cx)
 3538                            .always_treat_brackets_as_autoclosed;
 3539                        if always_treat_brackets_as_autoclosed
 3540                            && is_bracket_pair_end
 3541                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3542                        {
 3543                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3544                            // and the inserted text is a closing bracket and the selection is followed
 3545                            // by the closing bracket then move the selection past the closing bracket.
 3546                            let anchor = snapshot.anchor_after(selection.end);
 3547                            new_selections.push((selection.map(|_| anchor), text.len()));
 3548                            continue;
 3549                        }
 3550                    }
 3551                    // If an opening bracket is 1 character long and is typed while
 3552                    // text is selected, then surround that text with the bracket pair.
 3553                    else if auto_surround
 3554                        && bracket_pair.surround
 3555                        && is_bracket_pair_start
 3556                        && bracket_pair.start.chars().count() == 1
 3557                    {
 3558                        edits.push((selection.start..selection.start, text.clone()));
 3559                        edits.push((
 3560                            selection.end..selection.end,
 3561                            bracket_pair.end.as_str().into(),
 3562                        ));
 3563                        bracket_inserted = true;
 3564                        new_selections.push((
 3565                            Selection {
 3566                                id: selection.id,
 3567                                start: snapshot.anchor_after(selection.start),
 3568                                end: snapshot.anchor_before(selection.end),
 3569                                reversed: selection.reversed,
 3570                                goal: selection.goal,
 3571                            },
 3572                            0,
 3573                        ));
 3574                        continue;
 3575                    }
 3576                }
 3577            }
 3578
 3579            if self.auto_replace_emoji_shortcode
 3580                && selection.is_empty()
 3581                && text.as_ref().ends_with(':')
 3582            {
 3583                if let Some(possible_emoji_short_code) =
 3584                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3585                {
 3586                    if !possible_emoji_short_code.is_empty() {
 3587                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3588                            let emoji_shortcode_start = Point::new(
 3589                                selection.start.row,
 3590                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3591                            );
 3592
 3593                            // Remove shortcode from buffer
 3594                            edits.push((
 3595                                emoji_shortcode_start..selection.start,
 3596                                "".to_string().into(),
 3597                            ));
 3598                            new_selections.push((
 3599                                Selection {
 3600                                    id: selection.id,
 3601                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3602                                    end: snapshot.anchor_before(selection.start),
 3603                                    reversed: selection.reversed,
 3604                                    goal: selection.goal,
 3605                                },
 3606                                0,
 3607                            ));
 3608
 3609                            // Insert emoji
 3610                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3611                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3612                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3613
 3614                            continue;
 3615                        }
 3616                    }
 3617                }
 3618            }
 3619
 3620            // If not handling any auto-close operation, then just replace the selected
 3621            // text with the given input and move the selection to the end of the
 3622            // newly inserted text.
 3623            let anchor = snapshot.anchor_after(selection.end);
 3624            if !self.linked_edit_ranges.is_empty() {
 3625                let start_anchor = snapshot.anchor_before(selection.start);
 3626
 3627                let is_word_char = text.chars().next().map_or(true, |char| {
 3628                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3629                    classifier.is_word(char)
 3630                });
 3631
 3632                if is_word_char {
 3633                    if let Some(ranges) = self
 3634                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3635                    {
 3636                        for (buffer, edits) in ranges {
 3637                            linked_edits
 3638                                .entry(buffer.clone())
 3639                                .or_default()
 3640                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3641                        }
 3642                    }
 3643                } else {
 3644                    clear_linked_edit_ranges = true;
 3645                }
 3646            }
 3647
 3648            new_selections.push((selection.map(|_| anchor), 0));
 3649            edits.push((selection.start..selection.end, text.clone()));
 3650        }
 3651
 3652        drop(snapshot);
 3653
 3654        self.transact(window, cx, |this, window, cx| {
 3655            if clear_linked_edit_ranges {
 3656                this.linked_edit_ranges.clear();
 3657            }
 3658            let initial_buffer_versions =
 3659                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3660
 3661            this.buffer.update(cx, |buffer, cx| {
 3662                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3663            });
 3664            for (buffer, edits) in linked_edits {
 3665                buffer.update(cx, |buffer, cx| {
 3666                    let snapshot = buffer.snapshot();
 3667                    let edits = edits
 3668                        .into_iter()
 3669                        .map(|(range, text)| {
 3670                            use text::ToPoint as TP;
 3671                            let end_point = TP::to_point(&range.end, &snapshot);
 3672                            let start_point = TP::to_point(&range.start, &snapshot);
 3673                            (start_point..end_point, text)
 3674                        })
 3675                        .sorted_by_key(|(range, _)| range.start);
 3676                    buffer.edit(edits, None, cx);
 3677                })
 3678            }
 3679            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3680            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3681            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3682            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3683                .zip(new_selection_deltas)
 3684                .map(|(selection, delta)| Selection {
 3685                    id: selection.id,
 3686                    start: selection.start + delta,
 3687                    end: selection.end + delta,
 3688                    reversed: selection.reversed,
 3689                    goal: SelectionGoal::None,
 3690                })
 3691                .collect::<Vec<_>>();
 3692
 3693            let mut i = 0;
 3694            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3695                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3696                let start = map.buffer_snapshot.anchor_before(position);
 3697                let end = map.buffer_snapshot.anchor_after(position);
 3698                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3699                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3700                        Ordering::Less => i += 1,
 3701                        Ordering::Greater => break,
 3702                        Ordering::Equal => {
 3703                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3704                                Ordering::Less => i += 1,
 3705                                Ordering::Equal => break,
 3706                                Ordering::Greater => break,
 3707                            }
 3708                        }
 3709                    }
 3710                }
 3711                this.autoclose_regions.insert(
 3712                    i,
 3713                    AutocloseRegion {
 3714                        selection_id,
 3715                        range: start..end,
 3716                        pair,
 3717                    },
 3718                );
 3719            }
 3720
 3721            let had_active_inline_completion = this.has_active_inline_completion();
 3722            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3723                s.select(new_selections)
 3724            });
 3725
 3726            if !bracket_inserted {
 3727                if let Some(on_type_format_task) =
 3728                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3729                {
 3730                    on_type_format_task.detach_and_log_err(cx);
 3731                }
 3732            }
 3733
 3734            let editor_settings = EditorSettings::get_global(cx);
 3735            if bracket_inserted
 3736                && (editor_settings.auto_signature_help
 3737                    || editor_settings.show_signature_help_after_edits)
 3738            {
 3739                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3740            }
 3741
 3742            let trigger_in_words =
 3743                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3744            if this.hard_wrap.is_some() {
 3745                let latest: Range<Point> = this.selections.newest(cx).range();
 3746                if latest.is_empty()
 3747                    && this
 3748                        .buffer()
 3749                        .read(cx)
 3750                        .snapshot(cx)
 3751                        .line_len(MultiBufferRow(latest.start.row))
 3752                        == latest.start.column
 3753                {
 3754                    this.rewrap_impl(
 3755                        RewrapOptions {
 3756                            override_language_settings: true,
 3757                            preserve_existing_whitespace: true,
 3758                        },
 3759                        cx,
 3760                    )
 3761                }
 3762            }
 3763            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3764            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3765            this.refresh_inline_completion(true, false, window, cx);
 3766            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3767        });
 3768    }
 3769
 3770    fn find_possible_emoji_shortcode_at_position(
 3771        snapshot: &MultiBufferSnapshot,
 3772        position: Point,
 3773    ) -> Option<String> {
 3774        let mut chars = Vec::new();
 3775        let mut found_colon = false;
 3776        for char in snapshot.reversed_chars_at(position).take(100) {
 3777            // Found a possible emoji shortcode in the middle of the buffer
 3778            if found_colon {
 3779                if char.is_whitespace() {
 3780                    chars.reverse();
 3781                    return Some(chars.iter().collect());
 3782                }
 3783                // If the previous character is not a whitespace, we are in the middle of a word
 3784                // and we only want to complete the shortcode if the word is made up of other emojis
 3785                let mut containing_word = String::new();
 3786                for ch in snapshot
 3787                    .reversed_chars_at(position)
 3788                    .skip(chars.len() + 1)
 3789                    .take(100)
 3790                {
 3791                    if ch.is_whitespace() {
 3792                        break;
 3793                    }
 3794                    containing_word.push(ch);
 3795                }
 3796                let containing_word = containing_word.chars().rev().collect::<String>();
 3797                if util::word_consists_of_emojis(containing_word.as_str()) {
 3798                    chars.reverse();
 3799                    return Some(chars.iter().collect());
 3800                }
 3801            }
 3802
 3803            if char.is_whitespace() || !char.is_ascii() {
 3804                return None;
 3805            }
 3806            if char == ':' {
 3807                found_colon = true;
 3808            } else {
 3809                chars.push(char);
 3810            }
 3811        }
 3812        // Found a possible emoji shortcode at the beginning of the buffer
 3813        chars.reverse();
 3814        Some(chars.iter().collect())
 3815    }
 3816
 3817    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3818        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3819        self.transact(window, cx, |this, window, cx| {
 3820            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3821                let selections = this.selections.all::<usize>(cx);
 3822                let multi_buffer = this.buffer.read(cx);
 3823                let buffer = multi_buffer.snapshot(cx);
 3824                selections
 3825                    .iter()
 3826                    .map(|selection| {
 3827                        let start_point = selection.start.to_point(&buffer);
 3828                        let mut indent =
 3829                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3830                        indent.len = cmp::min(indent.len, start_point.column);
 3831                        let start = selection.start;
 3832                        let end = selection.end;
 3833                        let selection_is_empty = start == end;
 3834                        let language_scope = buffer.language_scope_at(start);
 3835                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3836                            &language_scope
 3837                        {
 3838                            let insert_extra_newline =
 3839                                insert_extra_newline_brackets(&buffer, start..end, language)
 3840                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3841
 3842                            // Comment extension on newline is allowed only for cursor selections
 3843                            let comment_delimiter = maybe!({
 3844                                if !selection_is_empty {
 3845                                    return None;
 3846                                }
 3847
 3848                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3849                                    return None;
 3850                                }
 3851
 3852                                let delimiters = language.line_comment_prefixes();
 3853                                let max_len_of_delimiter =
 3854                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3855                                let (snapshot, range) =
 3856                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3857
 3858                                let mut index_of_first_non_whitespace = 0;
 3859                                let comment_candidate = snapshot
 3860                                    .chars_for_range(range)
 3861                                    .skip_while(|c| {
 3862                                        let should_skip = c.is_whitespace();
 3863                                        if should_skip {
 3864                                            index_of_first_non_whitespace += 1;
 3865                                        }
 3866                                        should_skip
 3867                                    })
 3868                                    .take(max_len_of_delimiter)
 3869                                    .collect::<String>();
 3870                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3871                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3872                                })?;
 3873                                let cursor_is_placed_after_comment_marker =
 3874                                    index_of_first_non_whitespace + comment_prefix.len()
 3875                                        <= start_point.column as usize;
 3876                                if cursor_is_placed_after_comment_marker {
 3877                                    Some(comment_prefix.clone())
 3878                                } else {
 3879                                    None
 3880                                }
 3881                            });
 3882                            (comment_delimiter, insert_extra_newline)
 3883                        } else {
 3884                            (None, false)
 3885                        };
 3886
 3887                        let capacity_for_delimiter = comment_delimiter
 3888                            .as_deref()
 3889                            .map(str::len)
 3890                            .unwrap_or_default();
 3891                        let mut new_text =
 3892                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3893                        new_text.push('\n');
 3894                        new_text.extend(indent.chars());
 3895                        if let Some(delimiter) = &comment_delimiter {
 3896                            new_text.push_str(delimiter);
 3897                        }
 3898                        if insert_extra_newline {
 3899                            new_text = new_text.repeat(2);
 3900                        }
 3901
 3902                        let anchor = buffer.anchor_after(end);
 3903                        let new_selection = selection.map(|_| anchor);
 3904                        (
 3905                            (start..end, new_text),
 3906                            (insert_extra_newline, new_selection),
 3907                        )
 3908                    })
 3909                    .unzip()
 3910            };
 3911
 3912            this.edit_with_autoindent(edits, cx);
 3913            let buffer = this.buffer.read(cx).snapshot(cx);
 3914            let new_selections = selection_fixup_info
 3915                .into_iter()
 3916                .map(|(extra_newline_inserted, new_selection)| {
 3917                    let mut cursor = new_selection.end.to_point(&buffer);
 3918                    if extra_newline_inserted {
 3919                        cursor.row -= 1;
 3920                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3921                    }
 3922                    new_selection.map(|_| cursor)
 3923                })
 3924                .collect();
 3925
 3926            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3927                s.select(new_selections)
 3928            });
 3929            this.refresh_inline_completion(true, false, window, cx);
 3930        });
 3931    }
 3932
 3933    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3934        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3935
 3936        let buffer = self.buffer.read(cx);
 3937        let snapshot = buffer.snapshot(cx);
 3938
 3939        let mut edits = Vec::new();
 3940        let mut rows = Vec::new();
 3941
 3942        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3943            let cursor = selection.head();
 3944            let row = cursor.row;
 3945
 3946            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3947
 3948            let newline = "\n".to_string();
 3949            edits.push((start_of_line..start_of_line, newline));
 3950
 3951            rows.push(row + rows_inserted as u32);
 3952        }
 3953
 3954        self.transact(window, cx, |editor, window, cx| {
 3955            editor.edit(edits, cx);
 3956
 3957            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3958                let mut index = 0;
 3959                s.move_cursors_with(|map, _, _| {
 3960                    let row = rows[index];
 3961                    index += 1;
 3962
 3963                    let point = Point::new(row, 0);
 3964                    let boundary = map.next_line_boundary(point).1;
 3965                    let clipped = map.clip_point(boundary, Bias::Left);
 3966
 3967                    (clipped, SelectionGoal::None)
 3968                });
 3969            });
 3970
 3971            let mut indent_edits = Vec::new();
 3972            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3973            for row in rows {
 3974                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3975                for (row, indent) in indents {
 3976                    if indent.len == 0 {
 3977                        continue;
 3978                    }
 3979
 3980                    let text = match indent.kind {
 3981                        IndentKind::Space => " ".repeat(indent.len as usize),
 3982                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3983                    };
 3984                    let point = Point::new(row.0, 0);
 3985                    indent_edits.push((point..point, text));
 3986                }
 3987            }
 3988            editor.edit(indent_edits, cx);
 3989        });
 3990    }
 3991
 3992    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3993        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3994
 3995        let buffer = self.buffer.read(cx);
 3996        let snapshot = buffer.snapshot(cx);
 3997
 3998        let mut edits = Vec::new();
 3999        let mut rows = Vec::new();
 4000        let mut rows_inserted = 0;
 4001
 4002        for selection in self.selections.all_adjusted(cx) {
 4003            let cursor = selection.head();
 4004            let row = cursor.row;
 4005
 4006            let point = Point::new(row + 1, 0);
 4007            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4008
 4009            let newline = "\n".to_string();
 4010            edits.push((start_of_line..start_of_line, newline));
 4011
 4012            rows_inserted += 1;
 4013            rows.push(row + rows_inserted);
 4014        }
 4015
 4016        self.transact(window, cx, |editor, window, cx| {
 4017            editor.edit(edits, cx);
 4018
 4019            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4020                let mut index = 0;
 4021                s.move_cursors_with(|map, _, _| {
 4022                    let row = rows[index];
 4023                    index += 1;
 4024
 4025                    let point = Point::new(row, 0);
 4026                    let boundary = map.next_line_boundary(point).1;
 4027                    let clipped = map.clip_point(boundary, Bias::Left);
 4028
 4029                    (clipped, SelectionGoal::None)
 4030                });
 4031            });
 4032
 4033            let mut indent_edits = Vec::new();
 4034            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4035            for row in rows {
 4036                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4037                for (row, indent) in indents {
 4038                    if indent.len == 0 {
 4039                        continue;
 4040                    }
 4041
 4042                    let text = match indent.kind {
 4043                        IndentKind::Space => " ".repeat(indent.len as usize),
 4044                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4045                    };
 4046                    let point = Point::new(row.0, 0);
 4047                    indent_edits.push((point..point, text));
 4048                }
 4049            }
 4050            editor.edit(indent_edits, cx);
 4051        });
 4052    }
 4053
 4054    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4055        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4056            original_indent_columns: Vec::new(),
 4057        });
 4058        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4059    }
 4060
 4061    fn insert_with_autoindent_mode(
 4062        &mut self,
 4063        text: &str,
 4064        autoindent_mode: Option<AutoindentMode>,
 4065        window: &mut Window,
 4066        cx: &mut Context<Self>,
 4067    ) {
 4068        if self.read_only(cx) {
 4069            return;
 4070        }
 4071
 4072        let text: Arc<str> = text.into();
 4073        self.transact(window, cx, |this, window, cx| {
 4074            let old_selections = this.selections.all_adjusted(cx);
 4075            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4076                let anchors = {
 4077                    let snapshot = buffer.read(cx);
 4078                    old_selections
 4079                        .iter()
 4080                        .map(|s| {
 4081                            let anchor = snapshot.anchor_after(s.head());
 4082                            s.map(|_| anchor)
 4083                        })
 4084                        .collect::<Vec<_>>()
 4085                };
 4086                buffer.edit(
 4087                    old_selections
 4088                        .iter()
 4089                        .map(|s| (s.start..s.end, text.clone())),
 4090                    autoindent_mode,
 4091                    cx,
 4092                );
 4093                anchors
 4094            });
 4095
 4096            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4097                s.select_anchors(selection_anchors);
 4098            });
 4099
 4100            cx.notify();
 4101        });
 4102    }
 4103
 4104    fn trigger_completion_on_input(
 4105        &mut self,
 4106        text: &str,
 4107        trigger_in_words: bool,
 4108        window: &mut Window,
 4109        cx: &mut Context<Self>,
 4110    ) {
 4111        let ignore_completion_provider = self
 4112            .context_menu
 4113            .borrow()
 4114            .as_ref()
 4115            .map(|menu| match menu {
 4116                CodeContextMenu::Completions(completions_menu) => {
 4117                    completions_menu.ignore_completion_provider
 4118                }
 4119                CodeContextMenu::CodeActions(_) => false,
 4120            })
 4121            .unwrap_or(false);
 4122
 4123        if ignore_completion_provider {
 4124            self.show_word_completions(&ShowWordCompletions, window, cx);
 4125        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4126            self.show_completions(
 4127                &ShowCompletions {
 4128                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4129                },
 4130                window,
 4131                cx,
 4132            );
 4133        } else {
 4134            self.hide_context_menu(window, cx);
 4135        }
 4136    }
 4137
 4138    fn is_completion_trigger(
 4139        &self,
 4140        text: &str,
 4141        trigger_in_words: bool,
 4142        cx: &mut Context<Self>,
 4143    ) -> bool {
 4144        let position = self.selections.newest_anchor().head();
 4145        let multibuffer = self.buffer.read(cx);
 4146        let Some(buffer) = position
 4147            .buffer_id
 4148            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4149        else {
 4150            return false;
 4151        };
 4152
 4153        if let Some(completion_provider) = &self.completion_provider {
 4154            completion_provider.is_completion_trigger(
 4155                &buffer,
 4156                position.text_anchor,
 4157                text,
 4158                trigger_in_words,
 4159                cx,
 4160            )
 4161        } else {
 4162            false
 4163        }
 4164    }
 4165
 4166    /// If any empty selections is touching the start of its innermost containing autoclose
 4167    /// region, expand it to select the brackets.
 4168    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4169        let selections = self.selections.all::<usize>(cx);
 4170        let buffer = self.buffer.read(cx).read(cx);
 4171        let new_selections = self
 4172            .selections_with_autoclose_regions(selections, &buffer)
 4173            .map(|(mut selection, region)| {
 4174                if !selection.is_empty() {
 4175                    return selection;
 4176                }
 4177
 4178                if let Some(region) = region {
 4179                    let mut range = region.range.to_offset(&buffer);
 4180                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4181                        range.start -= region.pair.start.len();
 4182                        if buffer.contains_str_at(range.start, &region.pair.start)
 4183                            && buffer.contains_str_at(range.end, &region.pair.end)
 4184                        {
 4185                            range.end += region.pair.end.len();
 4186                            selection.start = range.start;
 4187                            selection.end = range.end;
 4188
 4189                            return selection;
 4190                        }
 4191                    }
 4192                }
 4193
 4194                let always_treat_brackets_as_autoclosed = buffer
 4195                    .language_settings_at(selection.start, cx)
 4196                    .always_treat_brackets_as_autoclosed;
 4197
 4198                if !always_treat_brackets_as_autoclosed {
 4199                    return selection;
 4200                }
 4201
 4202                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4203                    for (pair, enabled) in scope.brackets() {
 4204                        if !enabled || !pair.close {
 4205                            continue;
 4206                        }
 4207
 4208                        if buffer.contains_str_at(selection.start, &pair.end) {
 4209                            let pair_start_len = pair.start.len();
 4210                            if buffer.contains_str_at(
 4211                                selection.start.saturating_sub(pair_start_len),
 4212                                &pair.start,
 4213                            ) {
 4214                                selection.start -= pair_start_len;
 4215                                selection.end += pair.end.len();
 4216
 4217                                return selection;
 4218                            }
 4219                        }
 4220                    }
 4221                }
 4222
 4223                selection
 4224            })
 4225            .collect();
 4226
 4227        drop(buffer);
 4228        self.change_selections(None, window, cx, |selections| {
 4229            selections.select(new_selections)
 4230        });
 4231    }
 4232
 4233    /// Iterate the given selections, and for each one, find the smallest surrounding
 4234    /// autoclose region. This uses the ordering of the selections and the autoclose
 4235    /// regions to avoid repeated comparisons.
 4236    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4237        &'a self,
 4238        selections: impl IntoIterator<Item = Selection<D>>,
 4239        buffer: &'a MultiBufferSnapshot,
 4240    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4241        let mut i = 0;
 4242        let mut regions = self.autoclose_regions.as_slice();
 4243        selections.into_iter().map(move |selection| {
 4244            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4245
 4246            let mut enclosing = None;
 4247            while let Some(pair_state) = regions.get(i) {
 4248                if pair_state.range.end.to_offset(buffer) < range.start {
 4249                    regions = &regions[i + 1..];
 4250                    i = 0;
 4251                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4252                    break;
 4253                } else {
 4254                    if pair_state.selection_id == selection.id {
 4255                        enclosing = Some(pair_state);
 4256                    }
 4257                    i += 1;
 4258                }
 4259            }
 4260
 4261            (selection, enclosing)
 4262        })
 4263    }
 4264
 4265    /// Remove any autoclose regions that no longer contain their selection.
 4266    fn invalidate_autoclose_regions(
 4267        &mut self,
 4268        mut selections: &[Selection<Anchor>],
 4269        buffer: &MultiBufferSnapshot,
 4270    ) {
 4271        self.autoclose_regions.retain(|state| {
 4272            let mut i = 0;
 4273            while let Some(selection) = selections.get(i) {
 4274                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4275                    selections = &selections[1..];
 4276                    continue;
 4277                }
 4278                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4279                    break;
 4280                }
 4281                if selection.id == state.selection_id {
 4282                    return true;
 4283                } else {
 4284                    i += 1;
 4285                }
 4286            }
 4287            false
 4288        });
 4289    }
 4290
 4291    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4292        let offset = position.to_offset(buffer);
 4293        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4294        if offset > word_range.start && kind == Some(CharKind::Word) {
 4295            Some(
 4296                buffer
 4297                    .text_for_range(word_range.start..offset)
 4298                    .collect::<String>(),
 4299            )
 4300        } else {
 4301            None
 4302        }
 4303    }
 4304
 4305    pub fn toggle_inline_values(
 4306        &mut self,
 4307        _: &ToggleInlineValues,
 4308        _: &mut Window,
 4309        cx: &mut Context<Self>,
 4310    ) {
 4311        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4312
 4313        self.refresh_inline_values(cx);
 4314    }
 4315
 4316    pub fn toggle_inlay_hints(
 4317        &mut self,
 4318        _: &ToggleInlayHints,
 4319        _: &mut Window,
 4320        cx: &mut Context<Self>,
 4321    ) {
 4322        self.refresh_inlay_hints(
 4323            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4324            cx,
 4325        );
 4326    }
 4327
 4328    pub fn inlay_hints_enabled(&self) -> bool {
 4329        self.inlay_hint_cache.enabled
 4330    }
 4331
 4332    pub fn inline_values_enabled(&self) -> bool {
 4333        self.inline_value_cache.enabled
 4334    }
 4335
 4336    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4337        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4338            return;
 4339        }
 4340
 4341        let reason_description = reason.description();
 4342        let ignore_debounce = matches!(
 4343            reason,
 4344            InlayHintRefreshReason::SettingsChange(_)
 4345                | InlayHintRefreshReason::Toggle(_)
 4346                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4347                | InlayHintRefreshReason::ModifiersChanged(_)
 4348        );
 4349        let (invalidate_cache, required_languages) = match reason {
 4350            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4351                match self.inlay_hint_cache.modifiers_override(enabled) {
 4352                    Some(enabled) => {
 4353                        if enabled {
 4354                            (InvalidationStrategy::RefreshRequested, None)
 4355                        } else {
 4356                            self.splice_inlays(
 4357                                &self
 4358                                    .visible_inlay_hints(cx)
 4359                                    .iter()
 4360                                    .map(|inlay| inlay.id)
 4361                                    .collect::<Vec<InlayId>>(),
 4362                                Vec::new(),
 4363                                cx,
 4364                            );
 4365                            return;
 4366                        }
 4367                    }
 4368                    None => return,
 4369                }
 4370            }
 4371            InlayHintRefreshReason::Toggle(enabled) => {
 4372                if self.inlay_hint_cache.toggle(enabled) {
 4373                    if enabled {
 4374                        (InvalidationStrategy::RefreshRequested, None)
 4375                    } else {
 4376                        self.splice_inlays(
 4377                            &self
 4378                                .visible_inlay_hints(cx)
 4379                                .iter()
 4380                                .map(|inlay| inlay.id)
 4381                                .collect::<Vec<InlayId>>(),
 4382                            Vec::new(),
 4383                            cx,
 4384                        );
 4385                        return;
 4386                    }
 4387                } else {
 4388                    return;
 4389                }
 4390            }
 4391            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4392                match self.inlay_hint_cache.update_settings(
 4393                    &self.buffer,
 4394                    new_settings,
 4395                    self.visible_inlay_hints(cx),
 4396                    cx,
 4397                ) {
 4398                    ControlFlow::Break(Some(InlaySplice {
 4399                        to_remove,
 4400                        to_insert,
 4401                    })) => {
 4402                        self.splice_inlays(&to_remove, to_insert, cx);
 4403                        return;
 4404                    }
 4405                    ControlFlow::Break(None) => return,
 4406                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4407                }
 4408            }
 4409            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4410                if let Some(InlaySplice {
 4411                    to_remove,
 4412                    to_insert,
 4413                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4414                {
 4415                    self.splice_inlays(&to_remove, to_insert, cx);
 4416                }
 4417                self.display_map.update(cx, |display_map, _| {
 4418                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4419                });
 4420                return;
 4421            }
 4422            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4423            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4424                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4425            }
 4426            InlayHintRefreshReason::RefreshRequested => {
 4427                (InvalidationStrategy::RefreshRequested, None)
 4428            }
 4429        };
 4430
 4431        if let Some(InlaySplice {
 4432            to_remove,
 4433            to_insert,
 4434        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4435            reason_description,
 4436            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4437            invalidate_cache,
 4438            ignore_debounce,
 4439            cx,
 4440        ) {
 4441            self.splice_inlays(&to_remove, to_insert, cx);
 4442        }
 4443    }
 4444
 4445    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4446        self.display_map
 4447            .read(cx)
 4448            .current_inlays()
 4449            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4450            .cloned()
 4451            .collect()
 4452    }
 4453
 4454    pub fn excerpts_for_inlay_hints_query(
 4455        &self,
 4456        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4457        cx: &mut Context<Editor>,
 4458    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4459        let Some(project) = self.project.as_ref() else {
 4460            return HashMap::default();
 4461        };
 4462        let project = project.read(cx);
 4463        let multi_buffer = self.buffer().read(cx);
 4464        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4465        let multi_buffer_visible_start = self
 4466            .scroll_manager
 4467            .anchor()
 4468            .anchor
 4469            .to_point(&multi_buffer_snapshot);
 4470        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4471            multi_buffer_visible_start
 4472                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4473            Bias::Left,
 4474        );
 4475        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4476        multi_buffer_snapshot
 4477            .range_to_buffer_ranges(multi_buffer_visible_range)
 4478            .into_iter()
 4479            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4480            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4481                let buffer_file = project::File::from_dyn(buffer.file())?;
 4482                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4483                let worktree_entry = buffer_worktree
 4484                    .read(cx)
 4485                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4486                if worktree_entry.is_ignored {
 4487                    return None;
 4488                }
 4489
 4490                let language = buffer.language()?;
 4491                if let Some(restrict_to_languages) = restrict_to_languages {
 4492                    if !restrict_to_languages.contains(language) {
 4493                        return None;
 4494                    }
 4495                }
 4496                Some((
 4497                    excerpt_id,
 4498                    (
 4499                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4500                        buffer.version().clone(),
 4501                        excerpt_visible_range,
 4502                    ),
 4503                ))
 4504            })
 4505            .collect()
 4506    }
 4507
 4508    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4509        TextLayoutDetails {
 4510            text_system: window.text_system().clone(),
 4511            editor_style: self.style.clone().unwrap(),
 4512            rem_size: window.rem_size(),
 4513            scroll_anchor: self.scroll_manager.anchor(),
 4514            visible_rows: self.visible_line_count(),
 4515            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4516        }
 4517    }
 4518
 4519    pub fn splice_inlays(
 4520        &self,
 4521        to_remove: &[InlayId],
 4522        to_insert: Vec<Inlay>,
 4523        cx: &mut Context<Self>,
 4524    ) {
 4525        self.display_map.update(cx, |display_map, cx| {
 4526            display_map.splice_inlays(to_remove, to_insert, cx)
 4527        });
 4528        cx.notify();
 4529    }
 4530
 4531    fn trigger_on_type_formatting(
 4532        &self,
 4533        input: String,
 4534        window: &mut Window,
 4535        cx: &mut Context<Self>,
 4536    ) -> Option<Task<Result<()>>> {
 4537        if input.len() != 1 {
 4538            return None;
 4539        }
 4540
 4541        let project = self.project.as_ref()?;
 4542        let position = self.selections.newest_anchor().head();
 4543        let (buffer, buffer_position) = self
 4544            .buffer
 4545            .read(cx)
 4546            .text_anchor_for_position(position, cx)?;
 4547
 4548        let settings = language_settings::language_settings(
 4549            buffer
 4550                .read(cx)
 4551                .language_at(buffer_position)
 4552                .map(|l| l.name()),
 4553            buffer.read(cx).file(),
 4554            cx,
 4555        );
 4556        if !settings.use_on_type_format {
 4557            return None;
 4558        }
 4559
 4560        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4561        // hence we do LSP request & edit on host side only — add formats to host's history.
 4562        let push_to_lsp_host_history = true;
 4563        // If this is not the host, append its history with new edits.
 4564        let push_to_client_history = project.read(cx).is_via_collab();
 4565
 4566        let on_type_formatting = project.update(cx, |project, cx| {
 4567            project.on_type_format(
 4568                buffer.clone(),
 4569                buffer_position,
 4570                input,
 4571                push_to_lsp_host_history,
 4572                cx,
 4573            )
 4574        });
 4575        Some(cx.spawn_in(window, async move |editor, cx| {
 4576            if let Some(transaction) = on_type_formatting.await? {
 4577                if push_to_client_history {
 4578                    buffer
 4579                        .update(cx, |buffer, _| {
 4580                            buffer.push_transaction(transaction, Instant::now());
 4581                            buffer.finalize_last_transaction();
 4582                        })
 4583                        .ok();
 4584                }
 4585                editor.update(cx, |editor, cx| {
 4586                    editor.refresh_document_highlights(cx);
 4587                })?;
 4588            }
 4589            Ok(())
 4590        }))
 4591    }
 4592
 4593    pub fn show_word_completions(
 4594        &mut self,
 4595        _: &ShowWordCompletions,
 4596        window: &mut Window,
 4597        cx: &mut Context<Self>,
 4598    ) {
 4599        self.open_completions_menu(true, None, window, cx);
 4600    }
 4601
 4602    pub fn show_completions(
 4603        &mut self,
 4604        options: &ShowCompletions,
 4605        window: &mut Window,
 4606        cx: &mut Context<Self>,
 4607    ) {
 4608        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4609    }
 4610
 4611    fn open_completions_menu(
 4612        &mut self,
 4613        ignore_completion_provider: bool,
 4614        trigger: Option<&str>,
 4615        window: &mut Window,
 4616        cx: &mut Context<Self>,
 4617    ) {
 4618        if self.pending_rename.is_some() {
 4619            return;
 4620        }
 4621        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4622            return;
 4623        }
 4624
 4625        let position = self.selections.newest_anchor().head();
 4626        if position.diff_base_anchor.is_some() {
 4627            return;
 4628        }
 4629        let (buffer, buffer_position) =
 4630            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4631                output
 4632            } else {
 4633                return;
 4634            };
 4635        let buffer_snapshot = buffer.read(cx).snapshot();
 4636        let show_completion_documentation = buffer_snapshot
 4637            .settings_at(buffer_position, cx)
 4638            .show_completion_documentation;
 4639
 4640        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4641
 4642        let trigger_kind = match trigger {
 4643            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4644                CompletionTriggerKind::TRIGGER_CHARACTER
 4645            }
 4646            _ => CompletionTriggerKind::INVOKED,
 4647        };
 4648        let completion_context = CompletionContext {
 4649            trigger_character: trigger.and_then(|trigger| {
 4650                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4651                    Some(String::from(trigger))
 4652                } else {
 4653                    None
 4654                }
 4655            }),
 4656            trigger_kind,
 4657        };
 4658
 4659        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4660        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4661            let word_to_exclude = buffer_snapshot
 4662                .text_for_range(old_range.clone())
 4663                .collect::<String>();
 4664            (
 4665                buffer_snapshot.anchor_before(old_range.start)
 4666                    ..buffer_snapshot.anchor_after(old_range.end),
 4667                Some(word_to_exclude),
 4668            )
 4669        } else {
 4670            (buffer_position..buffer_position, None)
 4671        };
 4672
 4673        let completion_settings = language_settings(
 4674            buffer_snapshot
 4675                .language_at(buffer_position)
 4676                .map(|language| language.name()),
 4677            buffer_snapshot.file(),
 4678            cx,
 4679        )
 4680        .completions;
 4681
 4682        // The document can be large, so stay in reasonable bounds when searching for words,
 4683        // otherwise completion pop-up might be slow to appear.
 4684        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4685        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4686        let min_word_search = buffer_snapshot.clip_point(
 4687            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4688            Bias::Left,
 4689        );
 4690        let max_word_search = buffer_snapshot.clip_point(
 4691            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4692            Bias::Right,
 4693        );
 4694        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4695            ..buffer_snapshot.point_to_offset(max_word_search);
 4696
 4697        let provider = self
 4698            .completion_provider
 4699            .as_ref()
 4700            .filter(|_| !ignore_completion_provider);
 4701        let skip_digits = query
 4702            .as_ref()
 4703            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4704
 4705        let (mut words, provided_completions) = match provider {
 4706            Some(provider) => {
 4707                let completions = provider.completions(
 4708                    position.excerpt_id,
 4709                    &buffer,
 4710                    buffer_position,
 4711                    completion_context,
 4712                    window,
 4713                    cx,
 4714                );
 4715
 4716                let words = match completion_settings.words {
 4717                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4718                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4719                        .background_spawn(async move {
 4720                            buffer_snapshot.words_in_range(WordsQuery {
 4721                                fuzzy_contents: None,
 4722                                range: word_search_range,
 4723                                skip_digits,
 4724                            })
 4725                        }),
 4726                };
 4727
 4728                (words, completions)
 4729            }
 4730            None => (
 4731                cx.background_spawn(async move {
 4732                    buffer_snapshot.words_in_range(WordsQuery {
 4733                        fuzzy_contents: None,
 4734                        range: word_search_range,
 4735                        skip_digits,
 4736                    })
 4737                }),
 4738                Task::ready(Ok(None)),
 4739            ),
 4740        };
 4741
 4742        let sort_completions = provider
 4743            .as_ref()
 4744            .map_or(false, |provider| provider.sort_completions());
 4745
 4746        let filter_completions = provider
 4747            .as_ref()
 4748            .map_or(true, |provider| provider.filter_completions());
 4749
 4750        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4751
 4752        let id = post_inc(&mut self.next_completion_id);
 4753        let task = cx.spawn_in(window, async move |editor, cx| {
 4754            async move {
 4755                editor.update(cx, |this, _| {
 4756                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4757                })?;
 4758
 4759                let mut completions = Vec::new();
 4760                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4761                    completions.extend(provided_completions);
 4762                    if completion_settings.words == WordsCompletionMode::Fallback {
 4763                        words = Task::ready(BTreeMap::default());
 4764                    }
 4765                }
 4766
 4767                let mut words = words.await;
 4768                if let Some(word_to_exclude) = &word_to_exclude {
 4769                    words.remove(word_to_exclude);
 4770                }
 4771                for lsp_completion in &completions {
 4772                    words.remove(&lsp_completion.new_text);
 4773                }
 4774                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4775                    replace_range: old_range.clone(),
 4776                    new_text: word.clone(),
 4777                    label: CodeLabel::plain(word, None),
 4778                    icon_path: None,
 4779                    documentation: None,
 4780                    source: CompletionSource::BufferWord {
 4781                        word_range,
 4782                        resolved: false,
 4783                    },
 4784                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4785                    confirm: None,
 4786                }));
 4787
 4788                let menu = if completions.is_empty() {
 4789                    None
 4790                } else {
 4791                    let mut menu = CompletionsMenu::new(
 4792                        id,
 4793                        sort_completions,
 4794                        show_completion_documentation,
 4795                        ignore_completion_provider,
 4796                        position,
 4797                        buffer.clone(),
 4798                        completions.into(),
 4799                        snippet_sort_order,
 4800                    );
 4801
 4802                    menu.filter(
 4803                        if filter_completions {
 4804                            query.as_deref()
 4805                        } else {
 4806                            None
 4807                        },
 4808                        cx.background_executor().clone(),
 4809                    )
 4810                    .await;
 4811
 4812                    menu.visible().then_some(menu)
 4813                };
 4814
 4815                editor.update_in(cx, |editor, window, cx| {
 4816                    match editor.context_menu.borrow().as_ref() {
 4817                        None => {}
 4818                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4819                            if prev_menu.id > id {
 4820                                return;
 4821                            }
 4822                        }
 4823                        _ => return,
 4824                    }
 4825
 4826                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4827                        let mut menu = menu.unwrap();
 4828                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4829
 4830                        *editor.context_menu.borrow_mut() =
 4831                            Some(CodeContextMenu::Completions(menu));
 4832
 4833                        if editor.show_edit_predictions_in_menu() {
 4834                            editor.update_visible_inline_completion(window, cx);
 4835                        } else {
 4836                            editor.discard_inline_completion(false, cx);
 4837                        }
 4838
 4839                        cx.notify();
 4840                    } else if editor.completion_tasks.len() <= 1 {
 4841                        // If there are no more completion tasks and the last menu was
 4842                        // empty, we should hide it.
 4843                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4844                        // If it was already hidden and we don't show inline
 4845                        // completions in the menu, we should also show the
 4846                        // inline-completion when available.
 4847                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4848                            editor.update_visible_inline_completion(window, cx);
 4849                        }
 4850                    }
 4851                })?;
 4852
 4853                anyhow::Ok(())
 4854            }
 4855            .log_err()
 4856            .await
 4857        });
 4858
 4859        self.completion_tasks.push((id, task));
 4860    }
 4861
 4862    #[cfg(feature = "test-support")]
 4863    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4864        let menu = self.context_menu.borrow();
 4865        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4866            let completions = menu.completions.borrow();
 4867            Some(completions.to_vec())
 4868        } else {
 4869            None
 4870        }
 4871    }
 4872
 4873    pub fn confirm_completion(
 4874        &mut self,
 4875        action: &ConfirmCompletion,
 4876        window: &mut Window,
 4877        cx: &mut Context<Self>,
 4878    ) -> Option<Task<Result<()>>> {
 4879        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4880        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4881    }
 4882
 4883    pub fn confirm_completion_insert(
 4884        &mut self,
 4885        _: &ConfirmCompletionInsert,
 4886        window: &mut Window,
 4887        cx: &mut Context<Self>,
 4888    ) -> Option<Task<Result<()>>> {
 4889        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4890        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4891    }
 4892
 4893    pub fn confirm_completion_replace(
 4894        &mut self,
 4895        _: &ConfirmCompletionReplace,
 4896        window: &mut Window,
 4897        cx: &mut Context<Self>,
 4898    ) -> Option<Task<Result<()>>> {
 4899        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4900        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4901    }
 4902
 4903    pub fn compose_completion(
 4904        &mut self,
 4905        action: &ComposeCompletion,
 4906        window: &mut Window,
 4907        cx: &mut Context<Self>,
 4908    ) -> Option<Task<Result<()>>> {
 4909        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4910        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4911    }
 4912
 4913    fn do_completion(
 4914        &mut self,
 4915        item_ix: Option<usize>,
 4916        intent: CompletionIntent,
 4917        window: &mut Window,
 4918        cx: &mut Context<Editor>,
 4919    ) -> Option<Task<Result<()>>> {
 4920        use language::ToOffset as _;
 4921
 4922        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4923        else {
 4924            return None;
 4925        };
 4926
 4927        let candidate_id = {
 4928            let entries = completions_menu.entries.borrow();
 4929            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4930            if self.show_edit_predictions_in_menu() {
 4931                self.discard_inline_completion(true, cx);
 4932            }
 4933            mat.candidate_id
 4934        };
 4935
 4936        let buffer_handle = completions_menu.buffer;
 4937        let completion = completions_menu
 4938            .completions
 4939            .borrow()
 4940            .get(candidate_id)?
 4941            .clone();
 4942        cx.stop_propagation();
 4943
 4944        let snippet;
 4945        let new_text;
 4946        if completion.is_snippet() {
 4947            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4948            new_text = snippet.as_ref().unwrap().text.clone();
 4949        } else {
 4950            snippet = None;
 4951            new_text = completion.new_text.clone();
 4952        };
 4953
 4954        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4955        let buffer = buffer_handle.read(cx);
 4956        let snapshot = self.buffer.read(cx).snapshot(cx);
 4957        let replace_range_multibuffer = {
 4958            let excerpt = snapshot
 4959                .excerpt_containing(self.selections.newest_anchor().range())
 4960                .unwrap();
 4961            let multibuffer_anchor = snapshot
 4962                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4963                .unwrap()
 4964                ..snapshot
 4965                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4966                    .unwrap();
 4967            multibuffer_anchor.start.to_offset(&snapshot)
 4968                ..multibuffer_anchor.end.to_offset(&snapshot)
 4969        };
 4970        let newest_anchor = self.selections.newest_anchor();
 4971        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4972            return None;
 4973        }
 4974
 4975        let old_text = buffer
 4976            .text_for_range(replace_range.clone())
 4977            .collect::<String>();
 4978        let lookbehind = newest_anchor
 4979            .start
 4980            .text_anchor
 4981            .to_offset(buffer)
 4982            .saturating_sub(replace_range.start);
 4983        let lookahead = replace_range
 4984            .end
 4985            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4986        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4987        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4988
 4989        let selections = self.selections.all::<usize>(cx);
 4990        let mut ranges = Vec::new();
 4991        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4992
 4993        for selection in &selections {
 4994            let range = if selection.id == newest_anchor.id {
 4995                replace_range_multibuffer.clone()
 4996            } else {
 4997                let mut range = selection.range();
 4998
 4999                // if prefix is present, don't duplicate it
 5000                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5001                    range.start = range.start.saturating_sub(lookbehind);
 5002
 5003                    // if suffix is also present, mimic the newest cursor and replace it
 5004                    if selection.id != newest_anchor.id
 5005                        && snapshot.contains_str_at(range.end, suffix)
 5006                    {
 5007                        range.end += lookahead;
 5008                    }
 5009                }
 5010                range
 5011            };
 5012
 5013            ranges.push(range.clone());
 5014
 5015            if !self.linked_edit_ranges.is_empty() {
 5016                let start_anchor = snapshot.anchor_before(range.start);
 5017                let end_anchor = snapshot.anchor_after(range.end);
 5018                if let Some(ranges) = self
 5019                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5020                {
 5021                    for (buffer, edits) in ranges {
 5022                        linked_edits
 5023                            .entry(buffer.clone())
 5024                            .or_default()
 5025                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5026                    }
 5027                }
 5028            }
 5029        }
 5030
 5031        cx.emit(EditorEvent::InputHandled {
 5032            utf16_range_to_replace: None,
 5033            text: new_text.clone().into(),
 5034        });
 5035
 5036        self.transact(window, cx, |this, window, cx| {
 5037            if let Some(mut snippet) = snippet {
 5038                snippet.text = new_text.to_string();
 5039                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5040            } else {
 5041                this.buffer.update(cx, |buffer, cx| {
 5042                    let auto_indent = match completion.insert_text_mode {
 5043                        Some(InsertTextMode::AS_IS) => None,
 5044                        _ => this.autoindent_mode.clone(),
 5045                    };
 5046                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5047                    buffer.edit(edits, auto_indent, cx);
 5048                });
 5049            }
 5050            for (buffer, edits) in linked_edits {
 5051                buffer.update(cx, |buffer, cx| {
 5052                    let snapshot = buffer.snapshot();
 5053                    let edits = edits
 5054                        .into_iter()
 5055                        .map(|(range, text)| {
 5056                            use text::ToPoint as TP;
 5057                            let end_point = TP::to_point(&range.end, &snapshot);
 5058                            let start_point = TP::to_point(&range.start, &snapshot);
 5059                            (start_point..end_point, text)
 5060                        })
 5061                        .sorted_by_key(|(range, _)| range.start);
 5062                    buffer.edit(edits, None, cx);
 5063                })
 5064            }
 5065
 5066            this.refresh_inline_completion(true, false, window, cx);
 5067        });
 5068
 5069        let show_new_completions_on_confirm = completion
 5070            .confirm
 5071            .as_ref()
 5072            .map_or(false, |confirm| confirm(intent, window, cx));
 5073        if show_new_completions_on_confirm {
 5074            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5075        }
 5076
 5077        let provider = self.completion_provider.as_ref()?;
 5078        drop(completion);
 5079        let apply_edits = provider.apply_additional_edits_for_completion(
 5080            buffer_handle,
 5081            completions_menu.completions.clone(),
 5082            candidate_id,
 5083            true,
 5084            cx,
 5085        );
 5086
 5087        let editor_settings = EditorSettings::get_global(cx);
 5088        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5089            // After the code completion is finished, users often want to know what signatures are needed.
 5090            // so we should automatically call signature_help
 5091            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5092        }
 5093
 5094        Some(cx.foreground_executor().spawn(async move {
 5095            apply_edits.await?;
 5096            Ok(())
 5097        }))
 5098    }
 5099
 5100    pub fn toggle_code_actions(
 5101        &mut self,
 5102        action: &ToggleCodeActions,
 5103        window: &mut Window,
 5104        cx: &mut Context<Self>,
 5105    ) {
 5106        let quick_launch = action.quick_launch;
 5107        let mut context_menu = self.context_menu.borrow_mut();
 5108        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5109            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5110                // Toggle if we're selecting the same one
 5111                *context_menu = None;
 5112                cx.notify();
 5113                return;
 5114            } else {
 5115                // Otherwise, clear it and start a new one
 5116                *context_menu = None;
 5117                cx.notify();
 5118            }
 5119        }
 5120        drop(context_menu);
 5121        let snapshot = self.snapshot(window, cx);
 5122        let deployed_from_indicator = action.deployed_from_indicator;
 5123        let mut task = self.code_actions_task.take();
 5124        let action = action.clone();
 5125        cx.spawn_in(window, async move |editor, cx| {
 5126            while let Some(prev_task) = task {
 5127                prev_task.await.log_err();
 5128                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5129            }
 5130
 5131            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5132                if editor.focus_handle.is_focused(window) {
 5133                    let multibuffer_point = action
 5134                        .deployed_from_indicator
 5135                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5136                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5137                    let (buffer, buffer_row) = snapshot
 5138                        .buffer_snapshot
 5139                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5140                        .and_then(|(buffer_snapshot, range)| {
 5141                            editor
 5142                                .buffer
 5143                                .read(cx)
 5144                                .buffer(buffer_snapshot.remote_id())
 5145                                .map(|buffer| (buffer, range.start.row))
 5146                        })?;
 5147                    let (_, code_actions) = editor
 5148                        .available_code_actions
 5149                        .clone()
 5150                        .and_then(|(location, code_actions)| {
 5151                            let snapshot = location.buffer.read(cx).snapshot();
 5152                            let point_range = location.range.to_point(&snapshot);
 5153                            let point_range = point_range.start.row..=point_range.end.row;
 5154                            if point_range.contains(&buffer_row) {
 5155                                Some((location, code_actions))
 5156                            } else {
 5157                                None
 5158                            }
 5159                        })
 5160                        .unzip();
 5161                    let buffer_id = buffer.read(cx).remote_id();
 5162                    let tasks = editor
 5163                        .tasks
 5164                        .get(&(buffer_id, buffer_row))
 5165                        .map(|t| Arc::new(t.to_owned()));
 5166                    if tasks.is_none() && code_actions.is_none() {
 5167                        return None;
 5168                    }
 5169
 5170                    editor.completion_tasks.clear();
 5171                    editor.discard_inline_completion(false, cx);
 5172                    let task_context =
 5173                        tasks
 5174                            .as_ref()
 5175                            .zip(editor.project.clone())
 5176                            .map(|(tasks, project)| {
 5177                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5178                            });
 5179
 5180                    Some(cx.spawn_in(window, async move |editor, cx| {
 5181                        let task_context = match task_context {
 5182                            Some(task_context) => task_context.await,
 5183                            None => None,
 5184                        };
 5185                        let resolved_tasks =
 5186                            tasks
 5187                                .zip(task_context.clone())
 5188                                .map(|(tasks, task_context)| ResolvedTasks {
 5189                                    templates: tasks.resolve(&task_context).collect(),
 5190                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5191                                        multibuffer_point.row,
 5192                                        tasks.column,
 5193                                    )),
 5194                                });
 5195                        let spawn_straight_away = quick_launch
 5196                            && resolved_tasks
 5197                                .as_ref()
 5198                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5199                            && code_actions
 5200                                .as_ref()
 5201                                .map_or(true, |actions| actions.is_empty());
 5202                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5203                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5204                                maybe!({
 5205                                    let project = editor.project.as_ref()?;
 5206                                    let dap_store = project.read(cx).dap_store();
 5207                                    let mut scenarios = vec![];
 5208                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5209                                    let debug_adapter: SharedString = buffer
 5210                                        .read(cx)
 5211                                        .language()?
 5212                                        .context_provider()?
 5213                                        .debug_adapter()?
 5214                                        .into();
 5215                                    dap_store.update(cx, |this, cx| {
 5216                                        for (_, task) in &resolved_tasks.templates {
 5217                                            if let Some(scenario) = this
 5218                                                .debug_scenario_for_build_task(
 5219                                                    task.resolved.clone(),
 5220                                                    SharedString::from(
 5221                                                        task.original_task().label.clone(),
 5222                                                    ),
 5223                                                    debug_adapter.clone(),
 5224                                                    cx,
 5225                                                )
 5226                                            {
 5227                                                scenarios.push(scenario);
 5228                                            }
 5229                                        }
 5230                                    });
 5231                                    Some(scenarios)
 5232                                })
 5233                                .unwrap_or_default()
 5234                            } else {
 5235                                vec![]
 5236                            }
 5237                        })?;
 5238                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5239                            *editor.context_menu.borrow_mut() =
 5240                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5241                                    buffer,
 5242                                    actions: CodeActionContents::new(
 5243                                        resolved_tasks,
 5244                                        code_actions,
 5245                                        debug_scenarios,
 5246                                        task_context.unwrap_or_default(),
 5247                                    ),
 5248                                    selected_item: Default::default(),
 5249                                    scroll_handle: UniformListScrollHandle::default(),
 5250                                    deployed_from_indicator,
 5251                                }));
 5252                            if spawn_straight_away {
 5253                                if let Some(task) = editor.confirm_code_action(
 5254                                    &ConfirmCodeAction { item_ix: Some(0) },
 5255                                    window,
 5256                                    cx,
 5257                                ) {
 5258                                    cx.notify();
 5259                                    return task;
 5260                                }
 5261                            }
 5262                            cx.notify();
 5263                            Task::ready(Ok(()))
 5264                        }) {
 5265                            task.await
 5266                        } else {
 5267                            Ok(())
 5268                        }
 5269                    }))
 5270                } else {
 5271                    Some(Task::ready(Ok(())))
 5272                }
 5273            })?;
 5274            if let Some(task) = spawned_test_task {
 5275                task.await?;
 5276            }
 5277
 5278            Ok::<_, anyhow::Error>(())
 5279        })
 5280        .detach_and_log_err(cx);
 5281    }
 5282
 5283    pub fn confirm_code_action(
 5284        &mut self,
 5285        action: &ConfirmCodeAction,
 5286        window: &mut Window,
 5287        cx: &mut Context<Self>,
 5288    ) -> Option<Task<Result<()>>> {
 5289        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5290
 5291        let actions_menu =
 5292            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5293                menu
 5294            } else {
 5295                return None;
 5296            };
 5297
 5298        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5299        let action = actions_menu.actions.get(action_ix)?;
 5300        let title = action.label();
 5301        let buffer = actions_menu.buffer;
 5302        let workspace = self.workspace()?;
 5303
 5304        match action {
 5305            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5306                workspace.update(cx, |workspace, cx| {
 5307                    workspace.schedule_resolved_task(
 5308                        task_source_kind,
 5309                        resolved_task,
 5310                        false,
 5311                        window,
 5312                        cx,
 5313                    );
 5314
 5315                    Some(Task::ready(Ok(())))
 5316                })
 5317            }
 5318            CodeActionsItem::CodeAction {
 5319                excerpt_id,
 5320                action,
 5321                provider,
 5322            } => {
 5323                let apply_code_action =
 5324                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5325                let workspace = workspace.downgrade();
 5326                Some(cx.spawn_in(window, async move |editor, cx| {
 5327                    let project_transaction = apply_code_action.await?;
 5328                    Self::open_project_transaction(
 5329                        &editor,
 5330                        workspace,
 5331                        project_transaction,
 5332                        title,
 5333                        cx,
 5334                    )
 5335                    .await
 5336                }))
 5337            }
 5338            CodeActionsItem::DebugScenario(scenario) => {
 5339                let context = actions_menu.actions.context.clone();
 5340
 5341                workspace.update(cx, |workspace, cx| {
 5342                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5343                });
 5344                Some(Task::ready(Ok(())))
 5345            }
 5346        }
 5347    }
 5348
 5349    pub async fn open_project_transaction(
 5350        this: &WeakEntity<Editor>,
 5351        workspace: WeakEntity<Workspace>,
 5352        transaction: ProjectTransaction,
 5353        title: String,
 5354        cx: &mut AsyncWindowContext,
 5355    ) -> Result<()> {
 5356        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5357        cx.update(|_, cx| {
 5358            entries.sort_unstable_by_key(|(buffer, _)| {
 5359                buffer.read(cx).file().map(|f| f.path().clone())
 5360            });
 5361        })?;
 5362
 5363        // If the project transaction's edits are all contained within this editor, then
 5364        // avoid opening a new editor to display them.
 5365
 5366        if let Some((buffer, transaction)) = entries.first() {
 5367            if entries.len() == 1 {
 5368                let excerpt = this.update(cx, |editor, cx| {
 5369                    editor
 5370                        .buffer()
 5371                        .read(cx)
 5372                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5373                })?;
 5374                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5375                    if excerpted_buffer == *buffer {
 5376                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5377                            let excerpt_range = excerpt_range.to_offset(buffer);
 5378                            buffer
 5379                                .edited_ranges_for_transaction::<usize>(transaction)
 5380                                .all(|range| {
 5381                                    excerpt_range.start <= range.start
 5382                                        && excerpt_range.end >= range.end
 5383                                })
 5384                        })?;
 5385
 5386                        if all_edits_within_excerpt {
 5387                            return Ok(());
 5388                        }
 5389                    }
 5390                }
 5391            }
 5392        } else {
 5393            return Ok(());
 5394        }
 5395
 5396        let mut ranges_to_highlight = Vec::new();
 5397        let excerpt_buffer = cx.new(|cx| {
 5398            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5399            for (buffer_handle, transaction) in &entries {
 5400                let edited_ranges = buffer_handle
 5401                    .read(cx)
 5402                    .edited_ranges_for_transaction::<Point>(transaction)
 5403                    .collect::<Vec<_>>();
 5404                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5405                    PathKey::for_buffer(buffer_handle, cx),
 5406                    buffer_handle.clone(),
 5407                    edited_ranges,
 5408                    DEFAULT_MULTIBUFFER_CONTEXT,
 5409                    cx,
 5410                );
 5411
 5412                ranges_to_highlight.extend(ranges);
 5413            }
 5414            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5415            multibuffer
 5416        })?;
 5417
 5418        workspace.update_in(cx, |workspace, window, cx| {
 5419            let project = workspace.project().clone();
 5420            let editor =
 5421                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5422            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5423            editor.update(cx, |editor, cx| {
 5424                editor.highlight_background::<Self>(
 5425                    &ranges_to_highlight,
 5426                    |theme| theme.editor_highlighted_line_background,
 5427                    cx,
 5428                );
 5429            });
 5430        })?;
 5431
 5432        Ok(())
 5433    }
 5434
 5435    pub fn clear_code_action_providers(&mut self) {
 5436        self.code_action_providers.clear();
 5437        self.available_code_actions.take();
 5438    }
 5439
 5440    pub fn add_code_action_provider(
 5441        &mut self,
 5442        provider: Rc<dyn CodeActionProvider>,
 5443        window: &mut Window,
 5444        cx: &mut Context<Self>,
 5445    ) {
 5446        if self
 5447            .code_action_providers
 5448            .iter()
 5449            .any(|existing_provider| existing_provider.id() == provider.id())
 5450        {
 5451            return;
 5452        }
 5453
 5454        self.code_action_providers.push(provider);
 5455        self.refresh_code_actions(window, cx);
 5456    }
 5457
 5458    pub fn remove_code_action_provider(
 5459        &mut self,
 5460        id: Arc<str>,
 5461        window: &mut Window,
 5462        cx: &mut Context<Self>,
 5463    ) {
 5464        self.code_action_providers
 5465            .retain(|provider| provider.id() != id);
 5466        self.refresh_code_actions(window, cx);
 5467    }
 5468
 5469    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5470        let newest_selection = self.selections.newest_anchor().clone();
 5471        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5472        let buffer = self.buffer.read(cx);
 5473        if newest_selection.head().diff_base_anchor.is_some() {
 5474            return None;
 5475        }
 5476        let (start_buffer, start) =
 5477            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5478        let (end_buffer, end) =
 5479            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5480        if start_buffer != end_buffer {
 5481            return None;
 5482        }
 5483
 5484        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5485            cx.background_executor()
 5486                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5487                .await;
 5488
 5489            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5490                let providers = this.code_action_providers.clone();
 5491                let tasks = this
 5492                    .code_action_providers
 5493                    .iter()
 5494                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5495                    .collect::<Vec<_>>();
 5496                (providers, tasks)
 5497            })?;
 5498
 5499            let mut actions = Vec::new();
 5500            for (provider, provider_actions) in
 5501                providers.into_iter().zip(future::join_all(tasks).await)
 5502            {
 5503                if let Some(provider_actions) = provider_actions.log_err() {
 5504                    actions.extend(provider_actions.into_iter().map(|action| {
 5505                        AvailableCodeAction {
 5506                            excerpt_id: newest_selection.start.excerpt_id,
 5507                            action,
 5508                            provider: provider.clone(),
 5509                        }
 5510                    }));
 5511                }
 5512            }
 5513
 5514            this.update(cx, |this, cx| {
 5515                this.available_code_actions = if actions.is_empty() {
 5516                    None
 5517                } else {
 5518                    Some((
 5519                        Location {
 5520                            buffer: start_buffer,
 5521                            range: start..end,
 5522                        },
 5523                        actions.into(),
 5524                    ))
 5525                };
 5526                cx.notify();
 5527            })
 5528        }));
 5529        None
 5530    }
 5531
 5532    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5533        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5534            self.show_git_blame_inline = false;
 5535
 5536            self.show_git_blame_inline_delay_task =
 5537                Some(cx.spawn_in(window, async move |this, cx| {
 5538                    cx.background_executor().timer(delay).await;
 5539
 5540                    this.update(cx, |this, cx| {
 5541                        this.show_git_blame_inline = true;
 5542                        cx.notify();
 5543                    })
 5544                    .log_err();
 5545                }));
 5546        }
 5547    }
 5548
 5549    fn show_blame_popover(
 5550        &mut self,
 5551        blame_entry: &BlameEntry,
 5552        position: gpui::Point<Pixels>,
 5553        cx: &mut Context<Self>,
 5554    ) {
 5555        if let Some(state) = &mut self.inline_blame_popover {
 5556            state.hide_task.take();
 5557            cx.notify();
 5558        } else {
 5559            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5560            let show_task = cx.spawn(async move |editor, cx| {
 5561                cx.background_executor()
 5562                    .timer(std::time::Duration::from_millis(delay))
 5563                    .await;
 5564                editor
 5565                    .update(cx, |editor, cx| {
 5566                        if let Some(state) = &mut editor.inline_blame_popover {
 5567                            state.show_task = None;
 5568                            cx.notify();
 5569                        }
 5570                    })
 5571                    .ok();
 5572            });
 5573            let Some(blame) = self.blame.as_ref() else {
 5574                return;
 5575            };
 5576            let blame = blame.read(cx);
 5577            let details = blame.details_for_entry(&blame_entry);
 5578            let markdown = cx.new(|cx| {
 5579                Markdown::new(
 5580                    details
 5581                        .as_ref()
 5582                        .map(|message| message.message.clone())
 5583                        .unwrap_or_default(),
 5584                    None,
 5585                    None,
 5586                    cx,
 5587                )
 5588            });
 5589            self.inline_blame_popover = Some(InlineBlamePopover {
 5590                position,
 5591                show_task: Some(show_task),
 5592                hide_task: None,
 5593                popover_bounds: None,
 5594                popover_state: InlineBlamePopoverState {
 5595                    scroll_handle: ScrollHandle::new(),
 5596                    commit_message: details,
 5597                    markdown,
 5598                },
 5599            });
 5600        }
 5601    }
 5602
 5603    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5604        if let Some(state) = &mut self.inline_blame_popover {
 5605            if state.show_task.is_some() {
 5606                self.inline_blame_popover.take();
 5607                cx.notify();
 5608            } else {
 5609                let hide_task = cx.spawn(async move |editor, cx| {
 5610                    cx.background_executor()
 5611                        .timer(std::time::Duration::from_millis(100))
 5612                        .await;
 5613                    editor
 5614                        .update(cx, |editor, cx| {
 5615                            editor.inline_blame_popover.take();
 5616                            cx.notify();
 5617                        })
 5618                        .ok();
 5619                });
 5620                state.hide_task = Some(hide_task);
 5621            }
 5622        }
 5623    }
 5624
 5625    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5626        if self.pending_rename.is_some() {
 5627            return None;
 5628        }
 5629
 5630        let provider = self.semantics_provider.clone()?;
 5631        let buffer = self.buffer.read(cx);
 5632        let newest_selection = self.selections.newest_anchor().clone();
 5633        let cursor_position = newest_selection.head();
 5634        let (cursor_buffer, cursor_buffer_position) =
 5635            buffer.text_anchor_for_position(cursor_position, cx)?;
 5636        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5637        if cursor_buffer != tail_buffer {
 5638            return None;
 5639        }
 5640        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5641        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5642            cx.background_executor()
 5643                .timer(Duration::from_millis(debounce))
 5644                .await;
 5645
 5646            let highlights = if let Some(highlights) = cx
 5647                .update(|cx| {
 5648                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5649                })
 5650                .ok()
 5651                .flatten()
 5652            {
 5653                highlights.await.log_err()
 5654            } else {
 5655                None
 5656            };
 5657
 5658            if let Some(highlights) = highlights {
 5659                this.update(cx, |this, cx| {
 5660                    if this.pending_rename.is_some() {
 5661                        return;
 5662                    }
 5663
 5664                    let buffer_id = cursor_position.buffer_id;
 5665                    let buffer = this.buffer.read(cx);
 5666                    if !buffer
 5667                        .text_anchor_for_position(cursor_position, cx)
 5668                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5669                    {
 5670                        return;
 5671                    }
 5672
 5673                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5674                    let mut write_ranges = Vec::new();
 5675                    let mut read_ranges = Vec::new();
 5676                    for highlight in highlights {
 5677                        for (excerpt_id, excerpt_range) in
 5678                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5679                        {
 5680                            let start = highlight
 5681                                .range
 5682                                .start
 5683                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5684                            let end = highlight
 5685                                .range
 5686                                .end
 5687                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5688                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5689                                continue;
 5690                            }
 5691
 5692                            let range = Anchor {
 5693                                buffer_id,
 5694                                excerpt_id,
 5695                                text_anchor: start,
 5696                                diff_base_anchor: None,
 5697                            }..Anchor {
 5698                                buffer_id,
 5699                                excerpt_id,
 5700                                text_anchor: end,
 5701                                diff_base_anchor: None,
 5702                            };
 5703                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5704                                write_ranges.push(range);
 5705                            } else {
 5706                                read_ranges.push(range);
 5707                            }
 5708                        }
 5709                    }
 5710
 5711                    this.highlight_background::<DocumentHighlightRead>(
 5712                        &read_ranges,
 5713                        |theme| theme.editor_document_highlight_read_background,
 5714                        cx,
 5715                    );
 5716                    this.highlight_background::<DocumentHighlightWrite>(
 5717                        &write_ranges,
 5718                        |theme| theme.editor_document_highlight_write_background,
 5719                        cx,
 5720                    );
 5721                    cx.notify();
 5722                })
 5723                .log_err();
 5724            }
 5725        }));
 5726        None
 5727    }
 5728
 5729    fn prepare_highlight_query_from_selection(
 5730        &mut self,
 5731        cx: &mut Context<Editor>,
 5732    ) -> Option<(String, Range<Anchor>)> {
 5733        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5734            return None;
 5735        }
 5736        if !EditorSettings::get_global(cx).selection_highlight {
 5737            return None;
 5738        }
 5739        if self.selections.count() != 1 || self.selections.line_mode {
 5740            return None;
 5741        }
 5742        let selection = self.selections.newest::<Point>(cx);
 5743        if selection.is_empty() || selection.start.row != selection.end.row {
 5744            return None;
 5745        }
 5746        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5747        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5748        let query = multi_buffer_snapshot
 5749            .text_for_range(selection_anchor_range.clone())
 5750            .collect::<String>();
 5751        if query.trim().is_empty() {
 5752            return None;
 5753        }
 5754        Some((query, selection_anchor_range))
 5755    }
 5756
 5757    fn update_selection_occurrence_highlights(
 5758        &mut self,
 5759        query_text: String,
 5760        query_range: Range<Anchor>,
 5761        multi_buffer_range_to_query: Range<Point>,
 5762        use_debounce: bool,
 5763        window: &mut Window,
 5764        cx: &mut Context<Editor>,
 5765    ) -> Task<()> {
 5766        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5767        cx.spawn_in(window, async move |editor, cx| {
 5768            if use_debounce {
 5769                cx.background_executor()
 5770                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5771                    .await;
 5772            }
 5773            let match_task = cx.background_spawn(async move {
 5774                let buffer_ranges = multi_buffer_snapshot
 5775                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5776                    .into_iter()
 5777                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5778                let mut match_ranges = Vec::new();
 5779                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5780                    match_ranges.extend(
 5781                        project::search::SearchQuery::text(
 5782                            query_text.clone(),
 5783                            false,
 5784                            false,
 5785                            false,
 5786                            Default::default(),
 5787                            Default::default(),
 5788                            false,
 5789                            None,
 5790                        )
 5791                        .unwrap()
 5792                        .search(&buffer_snapshot, Some(search_range.clone()))
 5793                        .await
 5794                        .into_iter()
 5795                        .filter_map(|match_range| {
 5796                            let match_start = buffer_snapshot
 5797                                .anchor_after(search_range.start + match_range.start);
 5798                            let match_end =
 5799                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5800                            let match_anchor_range = Anchor::range_in_buffer(
 5801                                excerpt_id,
 5802                                buffer_snapshot.remote_id(),
 5803                                match_start..match_end,
 5804                            );
 5805                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5806                        }),
 5807                    );
 5808                }
 5809                match_ranges
 5810            });
 5811            let match_ranges = match_task.await;
 5812            editor
 5813                .update_in(cx, |editor, _, cx| {
 5814                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5815                    if !match_ranges.is_empty() {
 5816                        editor.highlight_background::<SelectedTextHighlight>(
 5817                            &match_ranges,
 5818                            |theme| theme.editor_document_highlight_bracket_background,
 5819                            cx,
 5820                        )
 5821                    }
 5822                })
 5823                .log_err();
 5824        })
 5825    }
 5826
 5827    fn refresh_selected_text_highlights(
 5828        &mut self,
 5829        on_buffer_edit: bool,
 5830        window: &mut Window,
 5831        cx: &mut Context<Editor>,
 5832    ) {
 5833        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5834        else {
 5835            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5836            self.quick_selection_highlight_task.take();
 5837            self.debounced_selection_highlight_task.take();
 5838            return;
 5839        };
 5840        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5841        if on_buffer_edit
 5842            || self
 5843                .quick_selection_highlight_task
 5844                .as_ref()
 5845                .map_or(true, |(prev_anchor_range, _)| {
 5846                    prev_anchor_range != &query_range
 5847                })
 5848        {
 5849            let multi_buffer_visible_start = self
 5850                .scroll_manager
 5851                .anchor()
 5852                .anchor
 5853                .to_point(&multi_buffer_snapshot);
 5854            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5855                multi_buffer_visible_start
 5856                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5857                Bias::Left,
 5858            );
 5859            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5860            self.quick_selection_highlight_task = Some((
 5861                query_range.clone(),
 5862                self.update_selection_occurrence_highlights(
 5863                    query_text.clone(),
 5864                    query_range.clone(),
 5865                    multi_buffer_visible_range,
 5866                    false,
 5867                    window,
 5868                    cx,
 5869                ),
 5870            ));
 5871        }
 5872        if on_buffer_edit
 5873            || self
 5874                .debounced_selection_highlight_task
 5875                .as_ref()
 5876                .map_or(true, |(prev_anchor_range, _)| {
 5877                    prev_anchor_range != &query_range
 5878                })
 5879        {
 5880            let multi_buffer_start = multi_buffer_snapshot
 5881                .anchor_before(0)
 5882                .to_point(&multi_buffer_snapshot);
 5883            let multi_buffer_end = multi_buffer_snapshot
 5884                .anchor_after(multi_buffer_snapshot.len())
 5885                .to_point(&multi_buffer_snapshot);
 5886            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5887            self.debounced_selection_highlight_task = Some((
 5888                query_range.clone(),
 5889                self.update_selection_occurrence_highlights(
 5890                    query_text,
 5891                    query_range,
 5892                    multi_buffer_full_range,
 5893                    true,
 5894                    window,
 5895                    cx,
 5896                ),
 5897            ));
 5898        }
 5899    }
 5900
 5901    pub fn refresh_inline_completion(
 5902        &mut self,
 5903        debounce: bool,
 5904        user_requested: bool,
 5905        window: &mut Window,
 5906        cx: &mut Context<Self>,
 5907    ) -> Option<()> {
 5908        let provider = self.edit_prediction_provider()?;
 5909        let cursor = self.selections.newest_anchor().head();
 5910        let (buffer, cursor_buffer_position) =
 5911            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5912
 5913        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5914            self.discard_inline_completion(false, cx);
 5915            return None;
 5916        }
 5917
 5918        if !user_requested
 5919            && (!self.should_show_edit_predictions()
 5920                || !self.is_focused(window)
 5921                || buffer.read(cx).is_empty())
 5922        {
 5923            self.discard_inline_completion(false, cx);
 5924            return None;
 5925        }
 5926
 5927        self.update_visible_inline_completion(window, cx);
 5928        provider.refresh(
 5929            self.project.clone(),
 5930            buffer,
 5931            cursor_buffer_position,
 5932            debounce,
 5933            cx,
 5934        );
 5935        Some(())
 5936    }
 5937
 5938    fn show_edit_predictions_in_menu(&self) -> bool {
 5939        match self.edit_prediction_settings {
 5940            EditPredictionSettings::Disabled => false,
 5941            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5942        }
 5943    }
 5944
 5945    pub fn edit_predictions_enabled(&self) -> bool {
 5946        match self.edit_prediction_settings {
 5947            EditPredictionSettings::Disabled => false,
 5948            EditPredictionSettings::Enabled { .. } => true,
 5949        }
 5950    }
 5951
 5952    fn edit_prediction_requires_modifier(&self) -> bool {
 5953        match self.edit_prediction_settings {
 5954            EditPredictionSettings::Disabled => false,
 5955            EditPredictionSettings::Enabled {
 5956                preview_requires_modifier,
 5957                ..
 5958            } => preview_requires_modifier,
 5959        }
 5960    }
 5961
 5962    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5963        if self.edit_prediction_provider.is_none() {
 5964            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5965        } else {
 5966            let selection = self.selections.newest_anchor();
 5967            let cursor = selection.head();
 5968
 5969            if let Some((buffer, cursor_buffer_position)) =
 5970                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5971            {
 5972                self.edit_prediction_settings =
 5973                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5974            }
 5975        }
 5976    }
 5977
 5978    fn edit_prediction_settings_at_position(
 5979        &self,
 5980        buffer: &Entity<Buffer>,
 5981        buffer_position: language::Anchor,
 5982        cx: &App,
 5983    ) -> EditPredictionSettings {
 5984        if !self.mode.is_full()
 5985            || !self.show_inline_completions_override.unwrap_or(true)
 5986            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5987        {
 5988            return EditPredictionSettings::Disabled;
 5989        }
 5990
 5991        let buffer = buffer.read(cx);
 5992
 5993        let file = buffer.file();
 5994
 5995        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5996            return EditPredictionSettings::Disabled;
 5997        };
 5998
 5999        let by_provider = matches!(
 6000            self.menu_inline_completions_policy,
 6001            MenuInlineCompletionsPolicy::ByProvider
 6002        );
 6003
 6004        let show_in_menu = by_provider
 6005            && self
 6006                .edit_prediction_provider
 6007                .as_ref()
 6008                .map_or(false, |provider| {
 6009                    provider.provider.show_completions_in_menu()
 6010                });
 6011
 6012        let preview_requires_modifier =
 6013            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6014
 6015        EditPredictionSettings::Enabled {
 6016            show_in_menu,
 6017            preview_requires_modifier,
 6018        }
 6019    }
 6020
 6021    fn should_show_edit_predictions(&self) -> bool {
 6022        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6023    }
 6024
 6025    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6026        matches!(
 6027            self.edit_prediction_preview,
 6028            EditPredictionPreview::Active { .. }
 6029        )
 6030    }
 6031
 6032    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6033        let cursor = self.selections.newest_anchor().head();
 6034        if let Some((buffer, cursor_position)) =
 6035            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6036        {
 6037            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6038        } else {
 6039            false
 6040        }
 6041    }
 6042
 6043    fn edit_predictions_enabled_in_buffer(
 6044        &self,
 6045        buffer: &Entity<Buffer>,
 6046        buffer_position: language::Anchor,
 6047        cx: &App,
 6048    ) -> bool {
 6049        maybe!({
 6050            if self.read_only(cx) {
 6051                return Some(false);
 6052            }
 6053            let provider = self.edit_prediction_provider()?;
 6054            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6055                return Some(false);
 6056            }
 6057            let buffer = buffer.read(cx);
 6058            let Some(file) = buffer.file() else {
 6059                return Some(true);
 6060            };
 6061            let settings = all_language_settings(Some(file), cx);
 6062            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6063        })
 6064        .unwrap_or(false)
 6065    }
 6066
 6067    fn cycle_inline_completion(
 6068        &mut self,
 6069        direction: Direction,
 6070        window: &mut Window,
 6071        cx: &mut Context<Self>,
 6072    ) -> Option<()> {
 6073        let provider = self.edit_prediction_provider()?;
 6074        let cursor = self.selections.newest_anchor().head();
 6075        let (buffer, cursor_buffer_position) =
 6076            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6077        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6078            return None;
 6079        }
 6080
 6081        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6082        self.update_visible_inline_completion(window, cx);
 6083
 6084        Some(())
 6085    }
 6086
 6087    pub fn show_inline_completion(
 6088        &mut self,
 6089        _: &ShowEditPrediction,
 6090        window: &mut Window,
 6091        cx: &mut Context<Self>,
 6092    ) {
 6093        if !self.has_active_inline_completion() {
 6094            self.refresh_inline_completion(false, true, window, cx);
 6095            return;
 6096        }
 6097
 6098        self.update_visible_inline_completion(window, cx);
 6099    }
 6100
 6101    pub fn display_cursor_names(
 6102        &mut self,
 6103        _: &DisplayCursorNames,
 6104        window: &mut Window,
 6105        cx: &mut Context<Self>,
 6106    ) {
 6107        self.show_cursor_names(window, cx);
 6108    }
 6109
 6110    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6111        self.show_cursor_names = true;
 6112        cx.notify();
 6113        cx.spawn_in(window, async move |this, cx| {
 6114            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6115            this.update(cx, |this, cx| {
 6116                this.show_cursor_names = false;
 6117                cx.notify()
 6118            })
 6119            .ok()
 6120        })
 6121        .detach();
 6122    }
 6123
 6124    pub fn next_edit_prediction(
 6125        &mut self,
 6126        _: &NextEditPrediction,
 6127        window: &mut Window,
 6128        cx: &mut Context<Self>,
 6129    ) {
 6130        if self.has_active_inline_completion() {
 6131            self.cycle_inline_completion(Direction::Next, window, cx);
 6132        } else {
 6133            let is_copilot_disabled = self
 6134                .refresh_inline_completion(false, true, window, cx)
 6135                .is_none();
 6136            if is_copilot_disabled {
 6137                cx.propagate();
 6138            }
 6139        }
 6140    }
 6141
 6142    pub fn previous_edit_prediction(
 6143        &mut self,
 6144        _: &PreviousEditPrediction,
 6145        window: &mut Window,
 6146        cx: &mut Context<Self>,
 6147    ) {
 6148        if self.has_active_inline_completion() {
 6149            self.cycle_inline_completion(Direction::Prev, window, cx);
 6150        } else {
 6151            let is_copilot_disabled = self
 6152                .refresh_inline_completion(false, true, window, cx)
 6153                .is_none();
 6154            if is_copilot_disabled {
 6155                cx.propagate();
 6156            }
 6157        }
 6158    }
 6159
 6160    pub fn accept_edit_prediction(
 6161        &mut self,
 6162        _: &AcceptEditPrediction,
 6163        window: &mut Window,
 6164        cx: &mut Context<Self>,
 6165    ) {
 6166        if self.show_edit_predictions_in_menu() {
 6167            self.hide_context_menu(window, cx);
 6168        }
 6169
 6170        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6171            return;
 6172        };
 6173
 6174        self.report_inline_completion_event(
 6175            active_inline_completion.completion_id.clone(),
 6176            true,
 6177            cx,
 6178        );
 6179
 6180        match &active_inline_completion.completion {
 6181            InlineCompletion::Move { target, .. } => {
 6182                let target = *target;
 6183
 6184                if let Some(position_map) = &self.last_position_map {
 6185                    if position_map
 6186                        .visible_row_range
 6187                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6188                        || !self.edit_prediction_requires_modifier()
 6189                    {
 6190                        self.unfold_ranges(&[target..target], true, false, cx);
 6191                        // Note that this is also done in vim's handler of the Tab action.
 6192                        self.change_selections(
 6193                            Some(Autoscroll::newest()),
 6194                            window,
 6195                            cx,
 6196                            |selections| {
 6197                                selections.select_anchor_ranges([target..target]);
 6198                            },
 6199                        );
 6200                        self.clear_row_highlights::<EditPredictionPreview>();
 6201
 6202                        self.edit_prediction_preview
 6203                            .set_previous_scroll_position(None);
 6204                    } else {
 6205                        self.edit_prediction_preview
 6206                            .set_previous_scroll_position(Some(
 6207                                position_map.snapshot.scroll_anchor,
 6208                            ));
 6209
 6210                        self.highlight_rows::<EditPredictionPreview>(
 6211                            target..target,
 6212                            cx.theme().colors().editor_highlighted_line_background,
 6213                            RowHighlightOptions {
 6214                                autoscroll: true,
 6215                                ..Default::default()
 6216                            },
 6217                            cx,
 6218                        );
 6219                        self.request_autoscroll(Autoscroll::fit(), cx);
 6220                    }
 6221                }
 6222            }
 6223            InlineCompletion::Edit { edits, .. } => {
 6224                if let Some(provider) = self.edit_prediction_provider() {
 6225                    provider.accept(cx);
 6226                }
 6227
 6228                let snapshot = self.buffer.read(cx).snapshot(cx);
 6229                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6230
 6231                self.buffer.update(cx, |buffer, cx| {
 6232                    buffer.edit(edits.iter().cloned(), None, cx)
 6233                });
 6234
 6235                self.change_selections(None, window, cx, |s| {
 6236                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6237                });
 6238
 6239                self.update_visible_inline_completion(window, cx);
 6240                if self.active_inline_completion.is_none() {
 6241                    self.refresh_inline_completion(true, true, window, cx);
 6242                }
 6243
 6244                cx.notify();
 6245            }
 6246        }
 6247
 6248        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6249    }
 6250
 6251    pub fn accept_partial_inline_completion(
 6252        &mut self,
 6253        _: &AcceptPartialEditPrediction,
 6254        window: &mut Window,
 6255        cx: &mut Context<Self>,
 6256    ) {
 6257        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6258            return;
 6259        };
 6260        if self.selections.count() != 1 {
 6261            return;
 6262        }
 6263
 6264        self.report_inline_completion_event(
 6265            active_inline_completion.completion_id.clone(),
 6266            true,
 6267            cx,
 6268        );
 6269
 6270        match &active_inline_completion.completion {
 6271            InlineCompletion::Move { target, .. } => {
 6272                let target = *target;
 6273                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6274                    selections.select_anchor_ranges([target..target]);
 6275                });
 6276            }
 6277            InlineCompletion::Edit { edits, .. } => {
 6278                // Find an insertion that starts at the cursor position.
 6279                let snapshot = self.buffer.read(cx).snapshot(cx);
 6280                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6281                let insertion = edits.iter().find_map(|(range, text)| {
 6282                    let range = range.to_offset(&snapshot);
 6283                    if range.is_empty() && range.start == cursor_offset {
 6284                        Some(text)
 6285                    } else {
 6286                        None
 6287                    }
 6288                });
 6289
 6290                if let Some(text) = insertion {
 6291                    let mut partial_completion = text
 6292                        .chars()
 6293                        .by_ref()
 6294                        .take_while(|c| c.is_alphabetic())
 6295                        .collect::<String>();
 6296                    if partial_completion.is_empty() {
 6297                        partial_completion = text
 6298                            .chars()
 6299                            .by_ref()
 6300                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6301                            .collect::<String>();
 6302                    }
 6303
 6304                    cx.emit(EditorEvent::InputHandled {
 6305                        utf16_range_to_replace: None,
 6306                        text: partial_completion.clone().into(),
 6307                    });
 6308
 6309                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6310
 6311                    self.refresh_inline_completion(true, true, window, cx);
 6312                    cx.notify();
 6313                } else {
 6314                    self.accept_edit_prediction(&Default::default(), window, cx);
 6315                }
 6316            }
 6317        }
 6318    }
 6319
 6320    fn discard_inline_completion(
 6321        &mut self,
 6322        should_report_inline_completion_event: bool,
 6323        cx: &mut Context<Self>,
 6324    ) -> bool {
 6325        if should_report_inline_completion_event {
 6326            let completion_id = self
 6327                .active_inline_completion
 6328                .as_ref()
 6329                .and_then(|active_completion| active_completion.completion_id.clone());
 6330
 6331            self.report_inline_completion_event(completion_id, false, cx);
 6332        }
 6333
 6334        if let Some(provider) = self.edit_prediction_provider() {
 6335            provider.discard(cx);
 6336        }
 6337
 6338        self.take_active_inline_completion(cx)
 6339    }
 6340
 6341    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6342        let Some(provider) = self.edit_prediction_provider() else {
 6343            return;
 6344        };
 6345
 6346        let Some((_, buffer, _)) = self
 6347            .buffer
 6348            .read(cx)
 6349            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6350        else {
 6351            return;
 6352        };
 6353
 6354        let extension = buffer
 6355            .read(cx)
 6356            .file()
 6357            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6358
 6359        let event_type = match accepted {
 6360            true => "Edit Prediction Accepted",
 6361            false => "Edit Prediction Discarded",
 6362        };
 6363        telemetry::event!(
 6364            event_type,
 6365            provider = provider.name(),
 6366            prediction_id = id,
 6367            suggestion_accepted = accepted,
 6368            file_extension = extension,
 6369        );
 6370    }
 6371
 6372    pub fn has_active_inline_completion(&self) -> bool {
 6373        self.active_inline_completion.is_some()
 6374    }
 6375
 6376    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6377        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6378            return false;
 6379        };
 6380
 6381        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6382        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6383        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6384        true
 6385    }
 6386
 6387    /// Returns true when we're displaying the edit prediction popover below the cursor
 6388    /// like we are not previewing and the LSP autocomplete menu is visible
 6389    /// or we are in `when_holding_modifier` mode.
 6390    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6391        if self.edit_prediction_preview_is_active()
 6392            || !self.show_edit_predictions_in_menu()
 6393            || !self.edit_predictions_enabled()
 6394        {
 6395            return false;
 6396        }
 6397
 6398        if self.has_visible_completions_menu() {
 6399            return true;
 6400        }
 6401
 6402        has_completion && self.edit_prediction_requires_modifier()
 6403    }
 6404
 6405    fn handle_modifiers_changed(
 6406        &mut self,
 6407        modifiers: Modifiers,
 6408        position_map: &PositionMap,
 6409        window: &mut Window,
 6410        cx: &mut Context<Self>,
 6411    ) {
 6412        if self.show_edit_predictions_in_menu() {
 6413            self.update_edit_prediction_preview(&modifiers, window, cx);
 6414        }
 6415
 6416        self.update_selection_mode(&modifiers, position_map, window, cx);
 6417
 6418        let mouse_position = window.mouse_position();
 6419        if !position_map.text_hitbox.is_hovered(window) {
 6420            return;
 6421        }
 6422
 6423        self.update_hovered_link(
 6424            position_map.point_for_position(mouse_position),
 6425            &position_map.snapshot,
 6426            modifiers,
 6427            window,
 6428            cx,
 6429        )
 6430    }
 6431
 6432    fn update_selection_mode(
 6433        &mut self,
 6434        modifiers: &Modifiers,
 6435        position_map: &PositionMap,
 6436        window: &mut Window,
 6437        cx: &mut Context<Self>,
 6438    ) {
 6439        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6440            return;
 6441        }
 6442
 6443        let mouse_position = window.mouse_position();
 6444        let point_for_position = position_map.point_for_position(mouse_position);
 6445        let position = point_for_position.previous_valid;
 6446
 6447        self.select(
 6448            SelectPhase::BeginColumnar {
 6449                position,
 6450                reset: false,
 6451                goal_column: point_for_position.exact_unclipped.column(),
 6452            },
 6453            window,
 6454            cx,
 6455        );
 6456    }
 6457
 6458    fn update_edit_prediction_preview(
 6459        &mut self,
 6460        modifiers: &Modifiers,
 6461        window: &mut Window,
 6462        cx: &mut Context<Self>,
 6463    ) {
 6464        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6465        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6466            return;
 6467        };
 6468
 6469        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6470            if matches!(
 6471                self.edit_prediction_preview,
 6472                EditPredictionPreview::Inactive { .. }
 6473            ) {
 6474                self.edit_prediction_preview = EditPredictionPreview::Active {
 6475                    previous_scroll_position: None,
 6476                    since: Instant::now(),
 6477                };
 6478
 6479                self.update_visible_inline_completion(window, cx);
 6480                cx.notify();
 6481            }
 6482        } else if let EditPredictionPreview::Active {
 6483            previous_scroll_position,
 6484            since,
 6485        } = self.edit_prediction_preview
 6486        {
 6487            if let (Some(previous_scroll_position), Some(position_map)) =
 6488                (previous_scroll_position, self.last_position_map.as_ref())
 6489            {
 6490                self.set_scroll_position(
 6491                    previous_scroll_position
 6492                        .scroll_position(&position_map.snapshot.display_snapshot),
 6493                    window,
 6494                    cx,
 6495                );
 6496            }
 6497
 6498            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6499                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6500            };
 6501            self.clear_row_highlights::<EditPredictionPreview>();
 6502            self.update_visible_inline_completion(window, cx);
 6503            cx.notify();
 6504        }
 6505    }
 6506
 6507    fn update_visible_inline_completion(
 6508        &mut self,
 6509        _window: &mut Window,
 6510        cx: &mut Context<Self>,
 6511    ) -> Option<()> {
 6512        let selection = self.selections.newest_anchor();
 6513        let cursor = selection.head();
 6514        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6515        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6516        let excerpt_id = cursor.excerpt_id;
 6517
 6518        let show_in_menu = self.show_edit_predictions_in_menu();
 6519        let completions_menu_has_precedence = !show_in_menu
 6520            && (self.context_menu.borrow().is_some()
 6521                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6522
 6523        if completions_menu_has_precedence
 6524            || !offset_selection.is_empty()
 6525            || self
 6526                .active_inline_completion
 6527                .as_ref()
 6528                .map_or(false, |completion| {
 6529                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6530                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6531                    !invalidation_range.contains(&offset_selection.head())
 6532                })
 6533        {
 6534            self.discard_inline_completion(false, cx);
 6535            return None;
 6536        }
 6537
 6538        self.take_active_inline_completion(cx);
 6539        let Some(provider) = self.edit_prediction_provider() else {
 6540            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6541            return None;
 6542        };
 6543
 6544        let (buffer, cursor_buffer_position) =
 6545            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6546
 6547        self.edit_prediction_settings =
 6548            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6549
 6550        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6551
 6552        if self.edit_prediction_indent_conflict {
 6553            let cursor_point = cursor.to_point(&multibuffer);
 6554
 6555            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6556
 6557            if let Some((_, indent)) = indents.iter().next() {
 6558                if indent.len == cursor_point.column {
 6559                    self.edit_prediction_indent_conflict = false;
 6560                }
 6561            }
 6562        }
 6563
 6564        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6565        let edits = inline_completion
 6566            .edits
 6567            .into_iter()
 6568            .flat_map(|(range, new_text)| {
 6569                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6570                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6571                Some((start..end, new_text))
 6572            })
 6573            .collect::<Vec<_>>();
 6574        if edits.is_empty() {
 6575            return None;
 6576        }
 6577
 6578        let first_edit_start = edits.first().unwrap().0.start;
 6579        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6580        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6581
 6582        let last_edit_end = edits.last().unwrap().0.end;
 6583        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6584        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6585
 6586        let cursor_row = cursor.to_point(&multibuffer).row;
 6587
 6588        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6589
 6590        let mut inlay_ids = Vec::new();
 6591        let invalidation_row_range;
 6592        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6593            Some(cursor_row..edit_end_row)
 6594        } else if cursor_row > edit_end_row {
 6595            Some(edit_start_row..cursor_row)
 6596        } else {
 6597            None
 6598        };
 6599        let is_move =
 6600            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6601        let completion = if is_move {
 6602            invalidation_row_range =
 6603                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6604            let target = first_edit_start;
 6605            InlineCompletion::Move { target, snapshot }
 6606        } else {
 6607            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6608                && !self.inline_completions_hidden_for_vim_mode;
 6609
 6610            if show_completions_in_buffer {
 6611                if edits
 6612                    .iter()
 6613                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6614                {
 6615                    let mut inlays = Vec::new();
 6616                    for (range, new_text) in &edits {
 6617                        let inlay = Inlay::inline_completion(
 6618                            post_inc(&mut self.next_inlay_id),
 6619                            range.start,
 6620                            new_text.as_str(),
 6621                        );
 6622                        inlay_ids.push(inlay.id);
 6623                        inlays.push(inlay);
 6624                    }
 6625
 6626                    self.splice_inlays(&[], inlays, cx);
 6627                } else {
 6628                    let background_color = cx.theme().status().deleted_background;
 6629                    self.highlight_text::<InlineCompletionHighlight>(
 6630                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6631                        HighlightStyle {
 6632                            background_color: Some(background_color),
 6633                            ..Default::default()
 6634                        },
 6635                        cx,
 6636                    );
 6637                }
 6638            }
 6639
 6640            invalidation_row_range = edit_start_row..edit_end_row;
 6641
 6642            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6643                if provider.show_tab_accept_marker() {
 6644                    EditDisplayMode::TabAccept
 6645                } else {
 6646                    EditDisplayMode::Inline
 6647                }
 6648            } else {
 6649                EditDisplayMode::DiffPopover
 6650            };
 6651
 6652            InlineCompletion::Edit {
 6653                edits,
 6654                edit_preview: inline_completion.edit_preview,
 6655                display_mode,
 6656                snapshot,
 6657            }
 6658        };
 6659
 6660        let invalidation_range = multibuffer
 6661            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6662            ..multibuffer.anchor_after(Point::new(
 6663                invalidation_row_range.end,
 6664                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6665            ));
 6666
 6667        self.stale_inline_completion_in_menu = None;
 6668        self.active_inline_completion = Some(InlineCompletionState {
 6669            inlay_ids,
 6670            completion,
 6671            completion_id: inline_completion.id,
 6672            invalidation_range,
 6673        });
 6674
 6675        cx.notify();
 6676
 6677        Some(())
 6678    }
 6679
 6680    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6681        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6682    }
 6683
 6684    fn render_code_actions_indicator(
 6685        &self,
 6686        _style: &EditorStyle,
 6687        row: DisplayRow,
 6688        is_active: bool,
 6689        breakpoint: Option<&(Anchor, Breakpoint)>,
 6690        cx: &mut Context<Self>,
 6691    ) -> Option<IconButton> {
 6692        let color = Color::Muted;
 6693        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6694        let show_tooltip = !self.context_menu_visible();
 6695
 6696        if self.available_code_actions.is_some() {
 6697            Some(
 6698                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6699                    .shape(ui::IconButtonShape::Square)
 6700                    .icon_size(IconSize::XSmall)
 6701                    .icon_color(color)
 6702                    .toggle_state(is_active)
 6703                    .when(show_tooltip, |this| {
 6704                        this.tooltip({
 6705                            let focus_handle = self.focus_handle.clone();
 6706                            move |window, cx| {
 6707                                Tooltip::for_action_in(
 6708                                    "Toggle Code Actions",
 6709                                    &ToggleCodeActions {
 6710                                        deployed_from_indicator: None,
 6711                                        quick_launch: false,
 6712                                    },
 6713                                    &focus_handle,
 6714                                    window,
 6715                                    cx,
 6716                                )
 6717                            }
 6718                        })
 6719                    })
 6720                    .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 6721                        let quick_launch = e.down.button == MouseButton::Left;
 6722                        window.focus(&editor.focus_handle(cx));
 6723                        editor.toggle_code_actions(
 6724                            &ToggleCodeActions {
 6725                                deployed_from_indicator: Some(row),
 6726                                quick_launch,
 6727                            },
 6728                            window,
 6729                            cx,
 6730                        );
 6731                    }))
 6732                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6733                        editor.set_breakpoint_context_menu(
 6734                            row,
 6735                            position,
 6736                            event.down.position,
 6737                            window,
 6738                            cx,
 6739                        );
 6740                    })),
 6741            )
 6742        } else {
 6743            None
 6744        }
 6745    }
 6746
 6747    fn clear_tasks(&mut self) {
 6748        self.tasks.clear()
 6749    }
 6750
 6751    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6752        if self.tasks.insert(key, value).is_some() {
 6753            // This case should hopefully be rare, but just in case...
 6754            log::error!(
 6755                "multiple different run targets found on a single line, only the last target will be rendered"
 6756            )
 6757        }
 6758    }
 6759
 6760    /// Get all display points of breakpoints that will be rendered within editor
 6761    ///
 6762    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6763    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6764    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6765    fn active_breakpoints(
 6766        &self,
 6767        range: Range<DisplayRow>,
 6768        window: &mut Window,
 6769        cx: &mut Context<Self>,
 6770    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6771        let mut breakpoint_display_points = HashMap::default();
 6772
 6773        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6774            return breakpoint_display_points;
 6775        };
 6776
 6777        let snapshot = self.snapshot(window, cx);
 6778
 6779        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6780        let Some(project) = self.project.as_ref() else {
 6781            return breakpoint_display_points;
 6782        };
 6783
 6784        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6785            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6786
 6787        for (buffer_snapshot, range, excerpt_id) in
 6788            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6789        {
 6790            let Some(buffer) = project.read_with(cx, |this, cx| {
 6791                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6792            }) else {
 6793                continue;
 6794            };
 6795            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6796                &buffer,
 6797                Some(
 6798                    buffer_snapshot.anchor_before(range.start)
 6799                        ..buffer_snapshot.anchor_after(range.end),
 6800                ),
 6801                buffer_snapshot,
 6802                cx,
 6803            );
 6804            for (anchor, breakpoint) in breakpoints {
 6805                let multi_buffer_anchor =
 6806                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6807                let position = multi_buffer_anchor
 6808                    .to_point(&multi_buffer_snapshot)
 6809                    .to_display_point(&snapshot);
 6810
 6811                breakpoint_display_points
 6812                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6813            }
 6814        }
 6815
 6816        breakpoint_display_points
 6817    }
 6818
 6819    fn breakpoint_context_menu(
 6820        &self,
 6821        anchor: Anchor,
 6822        window: &mut Window,
 6823        cx: &mut Context<Self>,
 6824    ) -> Entity<ui::ContextMenu> {
 6825        let weak_editor = cx.weak_entity();
 6826        let focus_handle = self.focus_handle(cx);
 6827
 6828        let row = self
 6829            .buffer
 6830            .read(cx)
 6831            .snapshot(cx)
 6832            .summary_for_anchor::<Point>(&anchor)
 6833            .row;
 6834
 6835        let breakpoint = self
 6836            .breakpoint_at_row(row, window, cx)
 6837            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6838
 6839        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6840            "Edit Log Breakpoint"
 6841        } else {
 6842            "Set Log Breakpoint"
 6843        };
 6844
 6845        let condition_breakpoint_msg = if breakpoint
 6846            .as_ref()
 6847            .is_some_and(|bp| bp.1.condition.is_some())
 6848        {
 6849            "Edit Condition Breakpoint"
 6850        } else {
 6851            "Set Condition Breakpoint"
 6852        };
 6853
 6854        let hit_condition_breakpoint_msg = if breakpoint
 6855            .as_ref()
 6856            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6857        {
 6858            "Edit Hit Condition Breakpoint"
 6859        } else {
 6860            "Set Hit Condition Breakpoint"
 6861        };
 6862
 6863        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6864            "Unset Breakpoint"
 6865        } else {
 6866            "Set Breakpoint"
 6867        };
 6868
 6869        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6870            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6871
 6872        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6873            BreakpointState::Enabled => Some("Disable"),
 6874            BreakpointState::Disabled => Some("Enable"),
 6875        });
 6876
 6877        let (anchor, breakpoint) =
 6878            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6879
 6880        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6881            menu.on_blur_subscription(Subscription::new(|| {}))
 6882                .context(focus_handle)
 6883                .when(run_to_cursor, |this| {
 6884                    let weak_editor = weak_editor.clone();
 6885                    this.entry("Run to cursor", None, move |window, cx| {
 6886                        weak_editor
 6887                            .update(cx, |editor, cx| {
 6888                                editor.change_selections(None, window, cx, |s| {
 6889                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6890                                });
 6891                            })
 6892                            .ok();
 6893
 6894                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6895                    })
 6896                    .separator()
 6897                })
 6898                .when_some(toggle_state_msg, |this, msg| {
 6899                    this.entry(msg, None, {
 6900                        let weak_editor = weak_editor.clone();
 6901                        let breakpoint = breakpoint.clone();
 6902                        move |_window, cx| {
 6903                            weak_editor
 6904                                .update(cx, |this, cx| {
 6905                                    this.edit_breakpoint_at_anchor(
 6906                                        anchor,
 6907                                        breakpoint.as_ref().clone(),
 6908                                        BreakpointEditAction::InvertState,
 6909                                        cx,
 6910                                    );
 6911                                })
 6912                                .log_err();
 6913                        }
 6914                    })
 6915                })
 6916                .entry(set_breakpoint_msg, None, {
 6917                    let weak_editor = weak_editor.clone();
 6918                    let breakpoint = breakpoint.clone();
 6919                    move |_window, cx| {
 6920                        weak_editor
 6921                            .update(cx, |this, cx| {
 6922                                this.edit_breakpoint_at_anchor(
 6923                                    anchor,
 6924                                    breakpoint.as_ref().clone(),
 6925                                    BreakpointEditAction::Toggle,
 6926                                    cx,
 6927                                );
 6928                            })
 6929                            .log_err();
 6930                    }
 6931                })
 6932                .entry(log_breakpoint_msg, None, {
 6933                    let breakpoint = breakpoint.clone();
 6934                    let weak_editor = weak_editor.clone();
 6935                    move |window, cx| {
 6936                        weak_editor
 6937                            .update(cx, |this, cx| {
 6938                                this.add_edit_breakpoint_block(
 6939                                    anchor,
 6940                                    breakpoint.as_ref(),
 6941                                    BreakpointPromptEditAction::Log,
 6942                                    window,
 6943                                    cx,
 6944                                );
 6945                            })
 6946                            .log_err();
 6947                    }
 6948                })
 6949                .entry(condition_breakpoint_msg, None, {
 6950                    let breakpoint = breakpoint.clone();
 6951                    let weak_editor = weak_editor.clone();
 6952                    move |window, cx| {
 6953                        weak_editor
 6954                            .update(cx, |this, cx| {
 6955                                this.add_edit_breakpoint_block(
 6956                                    anchor,
 6957                                    breakpoint.as_ref(),
 6958                                    BreakpointPromptEditAction::Condition,
 6959                                    window,
 6960                                    cx,
 6961                                );
 6962                            })
 6963                            .log_err();
 6964                    }
 6965                })
 6966                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6967                    weak_editor
 6968                        .update(cx, |this, cx| {
 6969                            this.add_edit_breakpoint_block(
 6970                                anchor,
 6971                                breakpoint.as_ref(),
 6972                                BreakpointPromptEditAction::HitCondition,
 6973                                window,
 6974                                cx,
 6975                            );
 6976                        })
 6977                        .log_err();
 6978                })
 6979        })
 6980    }
 6981
 6982    fn render_breakpoint(
 6983        &self,
 6984        position: Anchor,
 6985        row: DisplayRow,
 6986        breakpoint: &Breakpoint,
 6987        cx: &mut Context<Self>,
 6988    ) -> IconButton {
 6989        // Is it a breakpoint that shows up when hovering over gutter?
 6990        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 6991            (false, false),
 6992            |PhantomBreakpointIndicator {
 6993                 is_active,
 6994                 display_row,
 6995                 collides_with_existing_breakpoint,
 6996             }| {
 6997                (
 6998                    is_active && display_row == row,
 6999                    collides_with_existing_breakpoint,
 7000                )
 7001            },
 7002        );
 7003
 7004        let (color, icon) = {
 7005            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 7006                (false, false) => ui::IconName::DebugBreakpoint,
 7007                (true, false) => ui::IconName::DebugLogBreakpoint,
 7008                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 7009                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 7010            };
 7011
 7012            let color = if is_phantom {
 7013                Color::Hint
 7014            } else {
 7015                Color::Debugger
 7016            };
 7017
 7018            (color, icon)
 7019        };
 7020
 7021        let breakpoint = Arc::from(breakpoint.clone());
 7022
 7023        let alt_as_text = gpui::Keystroke {
 7024            modifiers: Modifiers::secondary_key(),
 7025            ..Default::default()
 7026        };
 7027        let primary_action_text = if breakpoint.is_disabled() {
 7028            "enable"
 7029        } else if is_phantom && !collides_with_existing {
 7030            "set"
 7031        } else {
 7032            "unset"
 7033        };
 7034        let mut primary_text = format!("Click to {primary_action_text}");
 7035        if collides_with_existing && !breakpoint.is_disabled() {
 7036            use std::fmt::Write;
 7037            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7038        }
 7039        let primary_text = SharedString::from(primary_text);
 7040        let focus_handle = self.focus_handle.clone();
 7041        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7042            .icon_size(IconSize::XSmall)
 7043            .size(ui::ButtonSize::None)
 7044            .icon_color(color)
 7045            .style(ButtonStyle::Transparent)
 7046            .on_click(cx.listener({
 7047                let breakpoint = breakpoint.clone();
 7048
 7049                move |editor, event: &ClickEvent, window, cx| {
 7050                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7051                        BreakpointEditAction::InvertState
 7052                    } else {
 7053                        BreakpointEditAction::Toggle
 7054                    };
 7055
 7056                    window.focus(&editor.focus_handle(cx));
 7057                    editor.edit_breakpoint_at_anchor(
 7058                        position,
 7059                        breakpoint.as_ref().clone(),
 7060                        edit_action,
 7061                        cx,
 7062                    );
 7063                }
 7064            }))
 7065            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7066                editor.set_breakpoint_context_menu(
 7067                    row,
 7068                    Some(position),
 7069                    event.down.position,
 7070                    window,
 7071                    cx,
 7072                );
 7073            }))
 7074            .tooltip(move |window, cx| {
 7075                Tooltip::with_meta_in(
 7076                    primary_text.clone(),
 7077                    None,
 7078                    "Right-click for more options",
 7079                    &focus_handle,
 7080                    window,
 7081                    cx,
 7082                )
 7083            })
 7084    }
 7085
 7086    fn build_tasks_context(
 7087        project: &Entity<Project>,
 7088        buffer: &Entity<Buffer>,
 7089        buffer_row: u32,
 7090        tasks: &Arc<RunnableTasks>,
 7091        cx: &mut Context<Self>,
 7092    ) -> Task<Option<task::TaskContext>> {
 7093        let position = Point::new(buffer_row, tasks.column);
 7094        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7095        let location = Location {
 7096            buffer: buffer.clone(),
 7097            range: range_start..range_start,
 7098        };
 7099        // Fill in the environmental variables from the tree-sitter captures
 7100        let mut captured_task_variables = TaskVariables::default();
 7101        for (capture_name, value) in tasks.extra_variables.clone() {
 7102            captured_task_variables.insert(
 7103                task::VariableName::Custom(capture_name.into()),
 7104                value.clone(),
 7105            );
 7106        }
 7107        project.update(cx, |project, cx| {
 7108            project.task_store().update(cx, |task_store, cx| {
 7109                task_store.task_context_for_location(captured_task_variables, location, cx)
 7110            })
 7111        })
 7112    }
 7113
 7114    pub fn spawn_nearest_task(
 7115        &mut self,
 7116        action: &SpawnNearestTask,
 7117        window: &mut Window,
 7118        cx: &mut Context<Self>,
 7119    ) {
 7120        let Some((workspace, _)) = self.workspace.clone() else {
 7121            return;
 7122        };
 7123        let Some(project) = self.project.clone() else {
 7124            return;
 7125        };
 7126
 7127        // Try to find a closest, enclosing node using tree-sitter that has a
 7128        // task
 7129        let Some((buffer, buffer_row, tasks)) = self
 7130            .find_enclosing_node_task(cx)
 7131            // Or find the task that's closest in row-distance.
 7132            .or_else(|| self.find_closest_task(cx))
 7133        else {
 7134            return;
 7135        };
 7136
 7137        let reveal_strategy = action.reveal;
 7138        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7139        cx.spawn_in(window, async move |_, cx| {
 7140            let context = task_context.await?;
 7141            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7142
 7143            let resolved = &mut resolved_task.resolved;
 7144            resolved.reveal = reveal_strategy;
 7145
 7146            workspace
 7147                .update_in(cx, |workspace, window, cx| {
 7148                    workspace.schedule_resolved_task(
 7149                        task_source_kind,
 7150                        resolved_task,
 7151                        false,
 7152                        window,
 7153                        cx,
 7154                    );
 7155                })
 7156                .ok()
 7157        })
 7158        .detach();
 7159    }
 7160
 7161    fn find_closest_task(
 7162        &mut self,
 7163        cx: &mut Context<Self>,
 7164    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7165        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7166
 7167        let ((buffer_id, row), tasks) = self
 7168            .tasks
 7169            .iter()
 7170            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7171
 7172        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7173        let tasks = Arc::new(tasks.to_owned());
 7174        Some((buffer, *row, tasks))
 7175    }
 7176
 7177    fn find_enclosing_node_task(
 7178        &mut self,
 7179        cx: &mut Context<Self>,
 7180    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7181        let snapshot = self.buffer.read(cx).snapshot(cx);
 7182        let offset = self.selections.newest::<usize>(cx).head();
 7183        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7184        let buffer_id = excerpt.buffer().remote_id();
 7185
 7186        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7187        let mut cursor = layer.node().walk();
 7188
 7189        while cursor.goto_first_child_for_byte(offset).is_some() {
 7190            if cursor.node().end_byte() == offset {
 7191                cursor.goto_next_sibling();
 7192            }
 7193        }
 7194
 7195        // Ascend to the smallest ancestor that contains the range and has a task.
 7196        loop {
 7197            let node = cursor.node();
 7198            let node_range = node.byte_range();
 7199            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7200
 7201            // Check if this node contains our offset
 7202            if node_range.start <= offset && node_range.end >= offset {
 7203                // If it contains offset, check for task
 7204                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7205                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7206                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7207                }
 7208            }
 7209
 7210            if !cursor.goto_parent() {
 7211                break;
 7212            }
 7213        }
 7214        None
 7215    }
 7216
 7217    fn render_run_indicator(
 7218        &self,
 7219        _style: &EditorStyle,
 7220        is_active: bool,
 7221        row: DisplayRow,
 7222        breakpoint: Option<(Anchor, Breakpoint)>,
 7223        cx: &mut Context<Self>,
 7224    ) -> IconButton {
 7225        let color = Color::Muted;
 7226        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7227
 7228        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7229            .shape(ui::IconButtonShape::Square)
 7230            .icon_size(IconSize::XSmall)
 7231            .icon_color(color)
 7232            .toggle_state(is_active)
 7233            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7234                let quick_launch = e.down.button == MouseButton::Left;
 7235                window.focus(&editor.focus_handle(cx));
 7236                editor.toggle_code_actions(
 7237                    &ToggleCodeActions {
 7238                        deployed_from_indicator: Some(row),
 7239                        quick_launch,
 7240                    },
 7241                    window,
 7242                    cx,
 7243                );
 7244            }))
 7245            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7246                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7247            }))
 7248    }
 7249
 7250    pub fn context_menu_visible(&self) -> bool {
 7251        !self.edit_prediction_preview_is_active()
 7252            && self
 7253                .context_menu
 7254                .borrow()
 7255                .as_ref()
 7256                .map_or(false, |menu| menu.visible())
 7257    }
 7258
 7259    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7260        self.context_menu
 7261            .borrow()
 7262            .as_ref()
 7263            .map(|menu| menu.origin())
 7264    }
 7265
 7266    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7267        self.context_menu_options = Some(options);
 7268    }
 7269
 7270    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7271    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7272
 7273    fn render_edit_prediction_popover(
 7274        &mut self,
 7275        text_bounds: &Bounds<Pixels>,
 7276        content_origin: gpui::Point<Pixels>,
 7277        editor_snapshot: &EditorSnapshot,
 7278        visible_row_range: Range<DisplayRow>,
 7279        scroll_top: f32,
 7280        scroll_bottom: f32,
 7281        line_layouts: &[LineWithInvisibles],
 7282        line_height: Pixels,
 7283        scroll_pixel_position: gpui::Point<Pixels>,
 7284        newest_selection_head: Option<DisplayPoint>,
 7285        editor_width: Pixels,
 7286        style: &EditorStyle,
 7287        window: &mut Window,
 7288        cx: &mut App,
 7289    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7290        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7291
 7292        if self.edit_prediction_visible_in_cursor_popover(true) {
 7293            return None;
 7294        }
 7295
 7296        match &active_inline_completion.completion {
 7297            InlineCompletion::Move { target, .. } => {
 7298                let target_display_point = target.to_display_point(editor_snapshot);
 7299
 7300                if self.edit_prediction_requires_modifier() {
 7301                    if !self.edit_prediction_preview_is_active() {
 7302                        return None;
 7303                    }
 7304
 7305                    self.render_edit_prediction_modifier_jump_popover(
 7306                        text_bounds,
 7307                        content_origin,
 7308                        visible_row_range,
 7309                        line_layouts,
 7310                        line_height,
 7311                        scroll_pixel_position,
 7312                        newest_selection_head,
 7313                        target_display_point,
 7314                        window,
 7315                        cx,
 7316                    )
 7317                } else {
 7318                    self.render_edit_prediction_eager_jump_popover(
 7319                        text_bounds,
 7320                        content_origin,
 7321                        editor_snapshot,
 7322                        visible_row_range,
 7323                        scroll_top,
 7324                        scroll_bottom,
 7325                        line_height,
 7326                        scroll_pixel_position,
 7327                        target_display_point,
 7328                        editor_width,
 7329                        window,
 7330                        cx,
 7331                    )
 7332                }
 7333            }
 7334            InlineCompletion::Edit {
 7335                display_mode: EditDisplayMode::Inline,
 7336                ..
 7337            } => None,
 7338            InlineCompletion::Edit {
 7339                display_mode: EditDisplayMode::TabAccept,
 7340                edits,
 7341                ..
 7342            } => {
 7343                let range = &edits.first()?.0;
 7344                let target_display_point = range.end.to_display_point(editor_snapshot);
 7345
 7346                self.render_edit_prediction_end_of_line_popover(
 7347                    "Accept",
 7348                    editor_snapshot,
 7349                    visible_row_range,
 7350                    target_display_point,
 7351                    line_height,
 7352                    scroll_pixel_position,
 7353                    content_origin,
 7354                    editor_width,
 7355                    window,
 7356                    cx,
 7357                )
 7358            }
 7359            InlineCompletion::Edit {
 7360                edits,
 7361                edit_preview,
 7362                display_mode: EditDisplayMode::DiffPopover,
 7363                snapshot,
 7364            } => self.render_edit_prediction_diff_popover(
 7365                text_bounds,
 7366                content_origin,
 7367                editor_snapshot,
 7368                visible_row_range,
 7369                line_layouts,
 7370                line_height,
 7371                scroll_pixel_position,
 7372                newest_selection_head,
 7373                editor_width,
 7374                style,
 7375                edits,
 7376                edit_preview,
 7377                snapshot,
 7378                window,
 7379                cx,
 7380            ),
 7381        }
 7382    }
 7383
 7384    fn render_edit_prediction_modifier_jump_popover(
 7385        &mut self,
 7386        text_bounds: &Bounds<Pixels>,
 7387        content_origin: gpui::Point<Pixels>,
 7388        visible_row_range: Range<DisplayRow>,
 7389        line_layouts: &[LineWithInvisibles],
 7390        line_height: Pixels,
 7391        scroll_pixel_position: gpui::Point<Pixels>,
 7392        newest_selection_head: Option<DisplayPoint>,
 7393        target_display_point: DisplayPoint,
 7394        window: &mut Window,
 7395        cx: &mut App,
 7396    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7397        let scrolled_content_origin =
 7398            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7399
 7400        const SCROLL_PADDING_Y: Pixels = px(12.);
 7401
 7402        if target_display_point.row() < visible_row_range.start {
 7403            return self.render_edit_prediction_scroll_popover(
 7404                |_| SCROLL_PADDING_Y,
 7405                IconName::ArrowUp,
 7406                visible_row_range,
 7407                line_layouts,
 7408                newest_selection_head,
 7409                scrolled_content_origin,
 7410                window,
 7411                cx,
 7412            );
 7413        } else if target_display_point.row() >= visible_row_range.end {
 7414            return self.render_edit_prediction_scroll_popover(
 7415                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7416                IconName::ArrowDown,
 7417                visible_row_range,
 7418                line_layouts,
 7419                newest_selection_head,
 7420                scrolled_content_origin,
 7421                window,
 7422                cx,
 7423            );
 7424        }
 7425
 7426        const POLE_WIDTH: Pixels = px(2.);
 7427
 7428        let line_layout =
 7429            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7430        let target_column = target_display_point.column() as usize;
 7431
 7432        let target_x = line_layout.x_for_index(target_column);
 7433        let target_y =
 7434            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7435
 7436        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7437
 7438        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7439        border_color.l += 0.001;
 7440
 7441        let mut element = v_flex()
 7442            .items_end()
 7443            .when(flag_on_right, |el| el.items_start())
 7444            .child(if flag_on_right {
 7445                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7446                    .rounded_bl(px(0.))
 7447                    .rounded_tl(px(0.))
 7448                    .border_l_2()
 7449                    .border_color(border_color)
 7450            } else {
 7451                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7452                    .rounded_br(px(0.))
 7453                    .rounded_tr(px(0.))
 7454                    .border_r_2()
 7455                    .border_color(border_color)
 7456            })
 7457            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7458            .into_any();
 7459
 7460        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7461
 7462        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7463            - point(
 7464                if flag_on_right {
 7465                    POLE_WIDTH
 7466                } else {
 7467                    size.width - POLE_WIDTH
 7468                },
 7469                size.height - line_height,
 7470            );
 7471
 7472        origin.x = origin.x.max(content_origin.x);
 7473
 7474        element.prepaint_at(origin, window, cx);
 7475
 7476        Some((element, origin))
 7477    }
 7478
 7479    fn render_edit_prediction_scroll_popover(
 7480        &mut self,
 7481        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7482        scroll_icon: IconName,
 7483        visible_row_range: Range<DisplayRow>,
 7484        line_layouts: &[LineWithInvisibles],
 7485        newest_selection_head: Option<DisplayPoint>,
 7486        scrolled_content_origin: gpui::Point<Pixels>,
 7487        window: &mut Window,
 7488        cx: &mut App,
 7489    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7490        let mut element = self
 7491            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7492            .into_any();
 7493
 7494        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7495
 7496        let cursor = newest_selection_head?;
 7497        let cursor_row_layout =
 7498            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7499        let cursor_column = cursor.column() as usize;
 7500
 7501        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7502
 7503        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7504
 7505        element.prepaint_at(origin, window, cx);
 7506        Some((element, origin))
 7507    }
 7508
 7509    fn render_edit_prediction_eager_jump_popover(
 7510        &mut self,
 7511        text_bounds: &Bounds<Pixels>,
 7512        content_origin: gpui::Point<Pixels>,
 7513        editor_snapshot: &EditorSnapshot,
 7514        visible_row_range: Range<DisplayRow>,
 7515        scroll_top: f32,
 7516        scroll_bottom: f32,
 7517        line_height: Pixels,
 7518        scroll_pixel_position: gpui::Point<Pixels>,
 7519        target_display_point: DisplayPoint,
 7520        editor_width: Pixels,
 7521        window: &mut Window,
 7522        cx: &mut App,
 7523    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7524        if target_display_point.row().as_f32() < scroll_top {
 7525            let mut element = self
 7526                .render_edit_prediction_line_popover(
 7527                    "Jump to Edit",
 7528                    Some(IconName::ArrowUp),
 7529                    window,
 7530                    cx,
 7531                )?
 7532                .into_any();
 7533
 7534            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7535            let offset = point(
 7536                (text_bounds.size.width - size.width) / 2.,
 7537                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7538            );
 7539
 7540            let origin = text_bounds.origin + offset;
 7541            element.prepaint_at(origin, window, cx);
 7542            Some((element, origin))
 7543        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7544            let mut element = self
 7545                .render_edit_prediction_line_popover(
 7546                    "Jump to Edit",
 7547                    Some(IconName::ArrowDown),
 7548                    window,
 7549                    cx,
 7550                )?
 7551                .into_any();
 7552
 7553            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7554            let offset = point(
 7555                (text_bounds.size.width - size.width) / 2.,
 7556                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7557            );
 7558
 7559            let origin = text_bounds.origin + offset;
 7560            element.prepaint_at(origin, window, cx);
 7561            Some((element, origin))
 7562        } else {
 7563            self.render_edit_prediction_end_of_line_popover(
 7564                "Jump to Edit",
 7565                editor_snapshot,
 7566                visible_row_range,
 7567                target_display_point,
 7568                line_height,
 7569                scroll_pixel_position,
 7570                content_origin,
 7571                editor_width,
 7572                window,
 7573                cx,
 7574            )
 7575        }
 7576    }
 7577
 7578    fn render_edit_prediction_end_of_line_popover(
 7579        self: &mut Editor,
 7580        label: &'static str,
 7581        editor_snapshot: &EditorSnapshot,
 7582        visible_row_range: Range<DisplayRow>,
 7583        target_display_point: DisplayPoint,
 7584        line_height: Pixels,
 7585        scroll_pixel_position: gpui::Point<Pixels>,
 7586        content_origin: gpui::Point<Pixels>,
 7587        editor_width: Pixels,
 7588        window: &mut Window,
 7589        cx: &mut App,
 7590    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7591        let target_line_end = DisplayPoint::new(
 7592            target_display_point.row(),
 7593            editor_snapshot.line_len(target_display_point.row()),
 7594        );
 7595
 7596        let mut element = self
 7597            .render_edit_prediction_line_popover(label, None, window, cx)?
 7598            .into_any();
 7599
 7600        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7601
 7602        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7603
 7604        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7605        let mut origin = start_point
 7606            + line_origin
 7607            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7608        origin.x = origin.x.max(content_origin.x);
 7609
 7610        let max_x = content_origin.x + editor_width - size.width;
 7611
 7612        if origin.x > max_x {
 7613            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7614
 7615            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7616                origin.y += offset;
 7617                IconName::ArrowUp
 7618            } else {
 7619                origin.y -= offset;
 7620                IconName::ArrowDown
 7621            };
 7622
 7623            element = self
 7624                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7625                .into_any();
 7626
 7627            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7628
 7629            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7630        }
 7631
 7632        element.prepaint_at(origin, window, cx);
 7633        Some((element, origin))
 7634    }
 7635
 7636    fn render_edit_prediction_diff_popover(
 7637        self: &Editor,
 7638        text_bounds: &Bounds<Pixels>,
 7639        content_origin: gpui::Point<Pixels>,
 7640        editor_snapshot: &EditorSnapshot,
 7641        visible_row_range: Range<DisplayRow>,
 7642        line_layouts: &[LineWithInvisibles],
 7643        line_height: Pixels,
 7644        scroll_pixel_position: gpui::Point<Pixels>,
 7645        newest_selection_head: Option<DisplayPoint>,
 7646        editor_width: Pixels,
 7647        style: &EditorStyle,
 7648        edits: &Vec<(Range<Anchor>, String)>,
 7649        edit_preview: &Option<language::EditPreview>,
 7650        snapshot: &language::BufferSnapshot,
 7651        window: &mut Window,
 7652        cx: &mut App,
 7653    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7654        let edit_start = edits
 7655            .first()
 7656            .unwrap()
 7657            .0
 7658            .start
 7659            .to_display_point(editor_snapshot);
 7660        let edit_end = edits
 7661            .last()
 7662            .unwrap()
 7663            .0
 7664            .end
 7665            .to_display_point(editor_snapshot);
 7666
 7667        let is_visible = visible_row_range.contains(&edit_start.row())
 7668            || visible_row_range.contains(&edit_end.row());
 7669        if !is_visible {
 7670            return None;
 7671        }
 7672
 7673        let highlighted_edits =
 7674            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7675
 7676        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7677        let line_count = highlighted_edits.text.lines().count();
 7678
 7679        const BORDER_WIDTH: Pixels = px(1.);
 7680
 7681        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7682        let has_keybind = keybind.is_some();
 7683
 7684        let mut element = h_flex()
 7685            .items_start()
 7686            .child(
 7687                h_flex()
 7688                    .bg(cx.theme().colors().editor_background)
 7689                    .border(BORDER_WIDTH)
 7690                    .shadow_sm()
 7691                    .border_color(cx.theme().colors().border)
 7692                    .rounded_l_lg()
 7693                    .when(line_count > 1, |el| el.rounded_br_lg())
 7694                    .pr_1()
 7695                    .child(styled_text),
 7696            )
 7697            .child(
 7698                h_flex()
 7699                    .h(line_height + BORDER_WIDTH * 2.)
 7700                    .px_1p5()
 7701                    .gap_1()
 7702                    // Workaround: For some reason, there's a gap if we don't do this
 7703                    .ml(-BORDER_WIDTH)
 7704                    .shadow(smallvec![gpui::BoxShadow {
 7705                        color: gpui::black().opacity(0.05),
 7706                        offset: point(px(1.), px(1.)),
 7707                        blur_radius: px(2.),
 7708                        spread_radius: px(0.),
 7709                    }])
 7710                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7711                    .border(BORDER_WIDTH)
 7712                    .border_color(cx.theme().colors().border)
 7713                    .rounded_r_lg()
 7714                    .id("edit_prediction_diff_popover_keybind")
 7715                    .when(!has_keybind, |el| {
 7716                        let status_colors = cx.theme().status();
 7717
 7718                        el.bg(status_colors.error_background)
 7719                            .border_color(status_colors.error.opacity(0.6))
 7720                            .child(Icon::new(IconName::Info).color(Color::Error))
 7721                            .cursor_default()
 7722                            .hoverable_tooltip(move |_window, cx| {
 7723                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7724                            })
 7725                    })
 7726                    .children(keybind),
 7727            )
 7728            .into_any();
 7729
 7730        let longest_row =
 7731            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7732        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7733            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7734        } else {
 7735            layout_line(
 7736                longest_row,
 7737                editor_snapshot,
 7738                style,
 7739                editor_width,
 7740                |_| false,
 7741                window,
 7742                cx,
 7743            )
 7744            .width
 7745        };
 7746
 7747        let viewport_bounds =
 7748            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7749                right: -EditorElement::SCROLLBAR_WIDTH,
 7750                ..Default::default()
 7751            });
 7752
 7753        let x_after_longest =
 7754            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7755                - scroll_pixel_position.x;
 7756
 7757        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7758
 7759        // Fully visible if it can be displayed within the window (allow overlapping other
 7760        // panes). However, this is only allowed if the popover starts within text_bounds.
 7761        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7762            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7763
 7764        let mut origin = if can_position_to_the_right {
 7765            point(
 7766                x_after_longest,
 7767                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7768                    - scroll_pixel_position.y,
 7769            )
 7770        } else {
 7771            let cursor_row = newest_selection_head.map(|head| head.row());
 7772            let above_edit = edit_start
 7773                .row()
 7774                .0
 7775                .checked_sub(line_count as u32)
 7776                .map(DisplayRow);
 7777            let below_edit = Some(edit_end.row() + 1);
 7778            let above_cursor =
 7779                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7780            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7781
 7782            // Place the edit popover adjacent to the edit if there is a location
 7783            // available that is onscreen and does not obscure the cursor. Otherwise,
 7784            // place it adjacent to the cursor.
 7785            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7786                .into_iter()
 7787                .flatten()
 7788                .find(|&start_row| {
 7789                    let end_row = start_row + line_count as u32;
 7790                    visible_row_range.contains(&start_row)
 7791                        && visible_row_range.contains(&end_row)
 7792                        && cursor_row.map_or(true, |cursor_row| {
 7793                            !((start_row..end_row).contains(&cursor_row))
 7794                        })
 7795                })?;
 7796
 7797            content_origin
 7798                + point(
 7799                    -scroll_pixel_position.x,
 7800                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7801                )
 7802        };
 7803
 7804        origin.x -= BORDER_WIDTH;
 7805
 7806        window.defer_draw(element, origin, 1);
 7807
 7808        // Do not return an element, since it will already be drawn due to defer_draw.
 7809        None
 7810    }
 7811
 7812    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7813        px(30.)
 7814    }
 7815
 7816    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7817        if self.read_only(cx) {
 7818            cx.theme().players().read_only()
 7819        } else {
 7820            self.style.as_ref().unwrap().local_player
 7821        }
 7822    }
 7823
 7824    fn render_edit_prediction_accept_keybind(
 7825        &self,
 7826        window: &mut Window,
 7827        cx: &App,
 7828    ) -> Option<AnyElement> {
 7829        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7830        let accept_keystroke = accept_binding.keystroke()?;
 7831
 7832        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7833
 7834        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7835            Color::Accent
 7836        } else {
 7837            Color::Muted
 7838        };
 7839
 7840        h_flex()
 7841            .px_0p5()
 7842            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7843            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7844            .text_size(TextSize::XSmall.rems(cx))
 7845            .child(h_flex().children(ui::render_modifiers(
 7846                &accept_keystroke.modifiers,
 7847                PlatformStyle::platform(),
 7848                Some(modifiers_color),
 7849                Some(IconSize::XSmall.rems().into()),
 7850                true,
 7851            )))
 7852            .when(is_platform_style_mac, |parent| {
 7853                parent.child(accept_keystroke.key.clone())
 7854            })
 7855            .when(!is_platform_style_mac, |parent| {
 7856                parent.child(
 7857                    Key::new(
 7858                        util::capitalize(&accept_keystroke.key),
 7859                        Some(Color::Default),
 7860                    )
 7861                    .size(Some(IconSize::XSmall.rems().into())),
 7862                )
 7863            })
 7864            .into_any()
 7865            .into()
 7866    }
 7867
 7868    fn render_edit_prediction_line_popover(
 7869        &self,
 7870        label: impl Into<SharedString>,
 7871        icon: Option<IconName>,
 7872        window: &mut Window,
 7873        cx: &App,
 7874    ) -> Option<Stateful<Div>> {
 7875        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7876
 7877        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7878        let has_keybind = keybind.is_some();
 7879
 7880        let result = h_flex()
 7881            .id("ep-line-popover")
 7882            .py_0p5()
 7883            .pl_1()
 7884            .pr(padding_right)
 7885            .gap_1()
 7886            .rounded_md()
 7887            .border_1()
 7888            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7889            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7890            .shadow_sm()
 7891            .when(!has_keybind, |el| {
 7892                let status_colors = cx.theme().status();
 7893
 7894                el.bg(status_colors.error_background)
 7895                    .border_color(status_colors.error.opacity(0.6))
 7896                    .pl_2()
 7897                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7898                    .cursor_default()
 7899                    .hoverable_tooltip(move |_window, cx| {
 7900                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7901                    })
 7902            })
 7903            .children(keybind)
 7904            .child(
 7905                Label::new(label)
 7906                    .size(LabelSize::Small)
 7907                    .when(!has_keybind, |el| {
 7908                        el.color(cx.theme().status().error.into()).strikethrough()
 7909                    }),
 7910            )
 7911            .when(!has_keybind, |el| {
 7912                el.child(
 7913                    h_flex().ml_1().child(
 7914                        Icon::new(IconName::Info)
 7915                            .size(IconSize::Small)
 7916                            .color(cx.theme().status().error.into()),
 7917                    ),
 7918                )
 7919            })
 7920            .when_some(icon, |element, icon| {
 7921                element.child(
 7922                    div()
 7923                        .mt(px(1.5))
 7924                        .child(Icon::new(icon).size(IconSize::Small)),
 7925                )
 7926            });
 7927
 7928        Some(result)
 7929    }
 7930
 7931    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7932        let accent_color = cx.theme().colors().text_accent;
 7933        let editor_bg_color = cx.theme().colors().editor_background;
 7934        editor_bg_color.blend(accent_color.opacity(0.1))
 7935    }
 7936
 7937    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7938        let accent_color = cx.theme().colors().text_accent;
 7939        let editor_bg_color = cx.theme().colors().editor_background;
 7940        editor_bg_color.blend(accent_color.opacity(0.6))
 7941    }
 7942
 7943    fn render_edit_prediction_cursor_popover(
 7944        &self,
 7945        min_width: Pixels,
 7946        max_width: Pixels,
 7947        cursor_point: Point,
 7948        style: &EditorStyle,
 7949        accept_keystroke: Option<&gpui::Keystroke>,
 7950        _window: &Window,
 7951        cx: &mut Context<Editor>,
 7952    ) -> Option<AnyElement> {
 7953        let provider = self.edit_prediction_provider.as_ref()?;
 7954
 7955        if provider.provider.needs_terms_acceptance(cx) {
 7956            return Some(
 7957                h_flex()
 7958                    .min_w(min_width)
 7959                    .flex_1()
 7960                    .px_2()
 7961                    .py_1()
 7962                    .gap_3()
 7963                    .elevation_2(cx)
 7964                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7965                    .id("accept-terms")
 7966                    .cursor_pointer()
 7967                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7968                    .on_click(cx.listener(|this, _event, window, cx| {
 7969                        cx.stop_propagation();
 7970                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7971                        window.dispatch_action(
 7972                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7973                            cx,
 7974                        );
 7975                    }))
 7976                    .child(
 7977                        h_flex()
 7978                            .flex_1()
 7979                            .gap_2()
 7980                            .child(Icon::new(IconName::ZedPredict))
 7981                            .child(Label::new("Accept Terms of Service"))
 7982                            .child(div().w_full())
 7983                            .child(
 7984                                Icon::new(IconName::ArrowUpRight)
 7985                                    .color(Color::Muted)
 7986                                    .size(IconSize::Small),
 7987                            )
 7988                            .into_any_element(),
 7989                    )
 7990                    .into_any(),
 7991            );
 7992        }
 7993
 7994        let is_refreshing = provider.provider.is_refreshing(cx);
 7995
 7996        fn pending_completion_container() -> Div {
 7997            h_flex()
 7998                .h_full()
 7999                .flex_1()
 8000                .gap_2()
 8001                .child(Icon::new(IconName::ZedPredict))
 8002        }
 8003
 8004        let completion = match &self.active_inline_completion {
 8005            Some(prediction) => {
 8006                if !self.has_visible_completions_menu() {
 8007                    const RADIUS: Pixels = px(6.);
 8008                    const BORDER_WIDTH: Pixels = px(1.);
 8009
 8010                    return Some(
 8011                        h_flex()
 8012                            .elevation_2(cx)
 8013                            .border(BORDER_WIDTH)
 8014                            .border_color(cx.theme().colors().border)
 8015                            .when(accept_keystroke.is_none(), |el| {
 8016                                el.border_color(cx.theme().status().error)
 8017                            })
 8018                            .rounded(RADIUS)
 8019                            .rounded_tl(px(0.))
 8020                            .overflow_hidden()
 8021                            .child(div().px_1p5().child(match &prediction.completion {
 8022                                InlineCompletion::Move { target, snapshot } => {
 8023                                    use text::ToPoint as _;
 8024                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 8025                                    {
 8026                                        Icon::new(IconName::ZedPredictDown)
 8027                                    } else {
 8028                                        Icon::new(IconName::ZedPredictUp)
 8029                                    }
 8030                                }
 8031                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 8032                            }))
 8033                            .child(
 8034                                h_flex()
 8035                                    .gap_1()
 8036                                    .py_1()
 8037                                    .px_2()
 8038                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8039                                    .border_l_1()
 8040                                    .border_color(cx.theme().colors().border)
 8041                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8042                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8043                                        el.child(
 8044                                            Label::new("Hold")
 8045                                                .size(LabelSize::Small)
 8046                                                .when(accept_keystroke.is_none(), |el| {
 8047                                                    el.strikethrough()
 8048                                                })
 8049                                                .line_height_style(LineHeightStyle::UiLabel),
 8050                                        )
 8051                                    })
 8052                                    .id("edit_prediction_cursor_popover_keybind")
 8053                                    .when(accept_keystroke.is_none(), |el| {
 8054                                        let status_colors = cx.theme().status();
 8055
 8056                                        el.bg(status_colors.error_background)
 8057                                            .border_color(status_colors.error.opacity(0.6))
 8058                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8059                                            .cursor_default()
 8060                                            .hoverable_tooltip(move |_window, cx| {
 8061                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8062                                                    .into()
 8063                                            })
 8064                                    })
 8065                                    .when_some(
 8066                                        accept_keystroke.as_ref(),
 8067                                        |el, accept_keystroke| {
 8068                                            el.child(h_flex().children(ui::render_modifiers(
 8069                                                &accept_keystroke.modifiers,
 8070                                                PlatformStyle::platform(),
 8071                                                Some(Color::Default),
 8072                                                Some(IconSize::XSmall.rems().into()),
 8073                                                false,
 8074                                            )))
 8075                                        },
 8076                                    ),
 8077                            )
 8078                            .into_any(),
 8079                    );
 8080                }
 8081
 8082                self.render_edit_prediction_cursor_popover_preview(
 8083                    prediction,
 8084                    cursor_point,
 8085                    style,
 8086                    cx,
 8087                )?
 8088            }
 8089
 8090            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8091                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8092                    stale_completion,
 8093                    cursor_point,
 8094                    style,
 8095                    cx,
 8096                )?,
 8097
 8098                None => {
 8099                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8100                }
 8101            },
 8102
 8103            None => pending_completion_container().child(Label::new("No Prediction")),
 8104        };
 8105
 8106        let completion = if is_refreshing {
 8107            completion
 8108                .with_animation(
 8109                    "loading-completion",
 8110                    Animation::new(Duration::from_secs(2))
 8111                        .repeat()
 8112                        .with_easing(pulsating_between(0.4, 0.8)),
 8113                    |label, delta| label.opacity(delta),
 8114                )
 8115                .into_any_element()
 8116        } else {
 8117            completion.into_any_element()
 8118        };
 8119
 8120        let has_completion = self.active_inline_completion.is_some();
 8121
 8122        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8123        Some(
 8124            h_flex()
 8125                .min_w(min_width)
 8126                .max_w(max_width)
 8127                .flex_1()
 8128                .elevation_2(cx)
 8129                .border_color(cx.theme().colors().border)
 8130                .child(
 8131                    div()
 8132                        .flex_1()
 8133                        .py_1()
 8134                        .px_2()
 8135                        .overflow_hidden()
 8136                        .child(completion),
 8137                )
 8138                .when_some(accept_keystroke, |el, accept_keystroke| {
 8139                    if !accept_keystroke.modifiers.modified() {
 8140                        return el;
 8141                    }
 8142
 8143                    el.child(
 8144                        h_flex()
 8145                            .h_full()
 8146                            .border_l_1()
 8147                            .rounded_r_lg()
 8148                            .border_color(cx.theme().colors().border)
 8149                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8150                            .gap_1()
 8151                            .py_1()
 8152                            .px_2()
 8153                            .child(
 8154                                h_flex()
 8155                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8156                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8157                                    .child(h_flex().children(ui::render_modifiers(
 8158                                        &accept_keystroke.modifiers,
 8159                                        PlatformStyle::platform(),
 8160                                        Some(if !has_completion {
 8161                                            Color::Muted
 8162                                        } else {
 8163                                            Color::Default
 8164                                        }),
 8165                                        None,
 8166                                        false,
 8167                                    ))),
 8168                            )
 8169                            .child(Label::new("Preview").into_any_element())
 8170                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8171                    )
 8172                })
 8173                .into_any(),
 8174        )
 8175    }
 8176
 8177    fn render_edit_prediction_cursor_popover_preview(
 8178        &self,
 8179        completion: &InlineCompletionState,
 8180        cursor_point: Point,
 8181        style: &EditorStyle,
 8182        cx: &mut Context<Editor>,
 8183    ) -> Option<Div> {
 8184        use text::ToPoint as _;
 8185
 8186        fn render_relative_row_jump(
 8187            prefix: impl Into<String>,
 8188            current_row: u32,
 8189            target_row: u32,
 8190        ) -> Div {
 8191            let (row_diff, arrow) = if target_row < current_row {
 8192                (current_row - target_row, IconName::ArrowUp)
 8193            } else {
 8194                (target_row - current_row, IconName::ArrowDown)
 8195            };
 8196
 8197            h_flex()
 8198                .child(
 8199                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8200                        .color(Color::Muted)
 8201                        .size(LabelSize::Small),
 8202                )
 8203                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8204        }
 8205
 8206        match &completion.completion {
 8207            InlineCompletion::Move {
 8208                target, snapshot, ..
 8209            } => Some(
 8210                h_flex()
 8211                    .px_2()
 8212                    .gap_2()
 8213                    .flex_1()
 8214                    .child(
 8215                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8216                            Icon::new(IconName::ZedPredictDown)
 8217                        } else {
 8218                            Icon::new(IconName::ZedPredictUp)
 8219                        },
 8220                    )
 8221                    .child(Label::new("Jump to Edit")),
 8222            ),
 8223
 8224            InlineCompletion::Edit {
 8225                edits,
 8226                edit_preview,
 8227                snapshot,
 8228                display_mode: _,
 8229            } => {
 8230                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8231
 8232                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8233                    &snapshot,
 8234                    &edits,
 8235                    edit_preview.as_ref()?,
 8236                    true,
 8237                    cx,
 8238                )
 8239                .first_line_preview();
 8240
 8241                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8242                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8243
 8244                let preview = h_flex()
 8245                    .gap_1()
 8246                    .min_w_16()
 8247                    .child(styled_text)
 8248                    .when(has_more_lines, |parent| parent.child(""));
 8249
 8250                let left = if first_edit_row != cursor_point.row {
 8251                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8252                        .into_any_element()
 8253                } else {
 8254                    Icon::new(IconName::ZedPredict).into_any_element()
 8255                };
 8256
 8257                Some(
 8258                    h_flex()
 8259                        .h_full()
 8260                        .flex_1()
 8261                        .gap_2()
 8262                        .pr_1()
 8263                        .overflow_x_hidden()
 8264                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8265                        .child(left)
 8266                        .child(preview),
 8267                )
 8268            }
 8269        }
 8270    }
 8271
 8272    fn render_context_menu(
 8273        &self,
 8274        style: &EditorStyle,
 8275        max_height_in_lines: u32,
 8276        window: &mut Window,
 8277        cx: &mut Context<Editor>,
 8278    ) -> Option<AnyElement> {
 8279        let menu = self.context_menu.borrow();
 8280        let menu = menu.as_ref()?;
 8281        if !menu.visible() {
 8282            return None;
 8283        };
 8284        Some(menu.render(style, max_height_in_lines, window, cx))
 8285    }
 8286
 8287    fn render_context_menu_aside(
 8288        &mut self,
 8289        max_size: Size<Pixels>,
 8290        window: &mut Window,
 8291        cx: &mut Context<Editor>,
 8292    ) -> Option<AnyElement> {
 8293        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8294            if menu.visible() {
 8295                menu.render_aside(self, max_size, window, cx)
 8296            } else {
 8297                None
 8298            }
 8299        })
 8300    }
 8301
 8302    fn hide_context_menu(
 8303        &mut self,
 8304        window: &mut Window,
 8305        cx: &mut Context<Self>,
 8306    ) -> Option<CodeContextMenu> {
 8307        cx.notify();
 8308        self.completion_tasks.clear();
 8309        let context_menu = self.context_menu.borrow_mut().take();
 8310        self.stale_inline_completion_in_menu.take();
 8311        self.update_visible_inline_completion(window, cx);
 8312        context_menu
 8313    }
 8314
 8315    fn show_snippet_choices(
 8316        &mut self,
 8317        choices: &Vec<String>,
 8318        selection: Range<Anchor>,
 8319        cx: &mut Context<Self>,
 8320    ) {
 8321        if selection.start.buffer_id.is_none() {
 8322            return;
 8323        }
 8324        let buffer_id = selection.start.buffer_id.unwrap();
 8325        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8326        let id = post_inc(&mut self.next_completion_id);
 8327        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8328
 8329        if let Some(buffer) = buffer {
 8330            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8331                CompletionsMenu::new_snippet_choices(
 8332                    id,
 8333                    true,
 8334                    choices,
 8335                    selection,
 8336                    buffer,
 8337                    snippet_sort_order,
 8338                ),
 8339            ));
 8340        }
 8341    }
 8342
 8343    pub fn insert_snippet(
 8344        &mut self,
 8345        insertion_ranges: &[Range<usize>],
 8346        snippet: Snippet,
 8347        window: &mut Window,
 8348        cx: &mut Context<Self>,
 8349    ) -> Result<()> {
 8350        struct Tabstop<T> {
 8351            is_end_tabstop: bool,
 8352            ranges: Vec<Range<T>>,
 8353            choices: Option<Vec<String>>,
 8354        }
 8355
 8356        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8357            let snippet_text: Arc<str> = snippet.text.clone().into();
 8358            let edits = insertion_ranges
 8359                .iter()
 8360                .cloned()
 8361                .map(|range| (range, snippet_text.clone()));
 8362            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8363
 8364            let snapshot = &*buffer.read(cx);
 8365            let snippet = &snippet;
 8366            snippet
 8367                .tabstops
 8368                .iter()
 8369                .map(|tabstop| {
 8370                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8371                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8372                    });
 8373                    let mut tabstop_ranges = tabstop
 8374                        .ranges
 8375                        .iter()
 8376                        .flat_map(|tabstop_range| {
 8377                            let mut delta = 0_isize;
 8378                            insertion_ranges.iter().map(move |insertion_range| {
 8379                                let insertion_start = insertion_range.start as isize + delta;
 8380                                delta +=
 8381                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8382
 8383                                let start = ((insertion_start + tabstop_range.start) as usize)
 8384                                    .min(snapshot.len());
 8385                                let end = ((insertion_start + tabstop_range.end) as usize)
 8386                                    .min(snapshot.len());
 8387                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8388                            })
 8389                        })
 8390                        .collect::<Vec<_>>();
 8391                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8392
 8393                    Tabstop {
 8394                        is_end_tabstop,
 8395                        ranges: tabstop_ranges,
 8396                        choices: tabstop.choices.clone(),
 8397                    }
 8398                })
 8399                .collect::<Vec<_>>()
 8400        });
 8401        if let Some(tabstop) = tabstops.first() {
 8402            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8403                s.select_ranges(tabstop.ranges.iter().cloned());
 8404            });
 8405
 8406            if let Some(choices) = &tabstop.choices {
 8407                if let Some(selection) = tabstop.ranges.first() {
 8408                    self.show_snippet_choices(choices, selection.clone(), cx)
 8409                }
 8410            }
 8411
 8412            // If we're already at the last tabstop and it's at the end of the snippet,
 8413            // we're done, we don't need to keep the state around.
 8414            if !tabstop.is_end_tabstop {
 8415                let choices = tabstops
 8416                    .iter()
 8417                    .map(|tabstop| tabstop.choices.clone())
 8418                    .collect();
 8419
 8420                let ranges = tabstops
 8421                    .into_iter()
 8422                    .map(|tabstop| tabstop.ranges)
 8423                    .collect::<Vec<_>>();
 8424
 8425                self.snippet_stack.push(SnippetState {
 8426                    active_index: 0,
 8427                    ranges,
 8428                    choices,
 8429                });
 8430            }
 8431
 8432            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8433            if self.autoclose_regions.is_empty() {
 8434                let snapshot = self.buffer.read(cx).snapshot(cx);
 8435                for selection in &mut self.selections.all::<Point>(cx) {
 8436                    let selection_head = selection.head();
 8437                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8438                        continue;
 8439                    };
 8440
 8441                    let mut bracket_pair = None;
 8442                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8443                    let prev_chars = snapshot
 8444                        .reversed_chars_at(selection_head)
 8445                        .collect::<String>();
 8446                    for (pair, enabled) in scope.brackets() {
 8447                        if enabled
 8448                            && pair.close
 8449                            && prev_chars.starts_with(pair.start.as_str())
 8450                            && next_chars.starts_with(pair.end.as_str())
 8451                        {
 8452                            bracket_pair = Some(pair.clone());
 8453                            break;
 8454                        }
 8455                    }
 8456                    if let Some(pair) = bracket_pair {
 8457                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8458                        let autoclose_enabled =
 8459                            self.use_autoclose && snapshot_settings.use_autoclose;
 8460                        if autoclose_enabled {
 8461                            let start = snapshot.anchor_after(selection_head);
 8462                            let end = snapshot.anchor_after(selection_head);
 8463                            self.autoclose_regions.push(AutocloseRegion {
 8464                                selection_id: selection.id,
 8465                                range: start..end,
 8466                                pair,
 8467                            });
 8468                        }
 8469                    }
 8470                }
 8471            }
 8472        }
 8473        Ok(())
 8474    }
 8475
 8476    pub fn move_to_next_snippet_tabstop(
 8477        &mut self,
 8478        window: &mut Window,
 8479        cx: &mut Context<Self>,
 8480    ) -> bool {
 8481        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8482    }
 8483
 8484    pub fn move_to_prev_snippet_tabstop(
 8485        &mut self,
 8486        window: &mut Window,
 8487        cx: &mut Context<Self>,
 8488    ) -> bool {
 8489        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8490    }
 8491
 8492    pub fn move_to_snippet_tabstop(
 8493        &mut self,
 8494        bias: Bias,
 8495        window: &mut Window,
 8496        cx: &mut Context<Self>,
 8497    ) -> bool {
 8498        if let Some(mut snippet) = self.snippet_stack.pop() {
 8499            match bias {
 8500                Bias::Left => {
 8501                    if snippet.active_index > 0 {
 8502                        snippet.active_index -= 1;
 8503                    } else {
 8504                        self.snippet_stack.push(snippet);
 8505                        return false;
 8506                    }
 8507                }
 8508                Bias::Right => {
 8509                    if snippet.active_index + 1 < snippet.ranges.len() {
 8510                        snippet.active_index += 1;
 8511                    } else {
 8512                        self.snippet_stack.push(snippet);
 8513                        return false;
 8514                    }
 8515                }
 8516            }
 8517            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8518                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8519                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8520                });
 8521
 8522                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8523                    if let Some(selection) = current_ranges.first() {
 8524                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8525                    }
 8526                }
 8527
 8528                // If snippet state is not at the last tabstop, push it back on the stack
 8529                if snippet.active_index + 1 < snippet.ranges.len() {
 8530                    self.snippet_stack.push(snippet);
 8531                }
 8532                return true;
 8533            }
 8534        }
 8535
 8536        false
 8537    }
 8538
 8539    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8540        self.transact(window, cx, |this, window, cx| {
 8541            this.select_all(&SelectAll, window, cx);
 8542            this.insert("", window, cx);
 8543        });
 8544    }
 8545
 8546    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8547        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8548        self.transact(window, cx, |this, window, cx| {
 8549            this.select_autoclose_pair(window, cx);
 8550            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8551            if !this.linked_edit_ranges.is_empty() {
 8552                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8553                let snapshot = this.buffer.read(cx).snapshot(cx);
 8554
 8555                for selection in selections.iter() {
 8556                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8557                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8558                    if selection_start.buffer_id != selection_end.buffer_id {
 8559                        continue;
 8560                    }
 8561                    if let Some(ranges) =
 8562                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8563                    {
 8564                        for (buffer, entries) in ranges {
 8565                            linked_ranges.entry(buffer).or_default().extend(entries);
 8566                        }
 8567                    }
 8568                }
 8569            }
 8570
 8571            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8572            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8573            for selection in &mut selections {
 8574                if selection.is_empty() {
 8575                    let old_head = selection.head();
 8576                    let mut new_head =
 8577                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8578                            .to_point(&display_map);
 8579                    if let Some((buffer, line_buffer_range)) = display_map
 8580                        .buffer_snapshot
 8581                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8582                    {
 8583                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8584                        let indent_len = match indent_size.kind {
 8585                            IndentKind::Space => {
 8586                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8587                            }
 8588                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8589                        };
 8590                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8591                            let indent_len = indent_len.get();
 8592                            new_head = cmp::min(
 8593                                new_head,
 8594                                MultiBufferPoint::new(
 8595                                    old_head.row,
 8596                                    ((old_head.column - 1) / indent_len) * indent_len,
 8597                                ),
 8598                            );
 8599                        }
 8600                    }
 8601
 8602                    selection.set_head(new_head, SelectionGoal::None);
 8603                }
 8604            }
 8605
 8606            this.signature_help_state.set_backspace_pressed(true);
 8607            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608                s.select(selections)
 8609            });
 8610            this.insert("", window, cx);
 8611            let empty_str: Arc<str> = Arc::from("");
 8612            for (buffer, edits) in linked_ranges {
 8613                let snapshot = buffer.read(cx).snapshot();
 8614                use text::ToPoint as TP;
 8615
 8616                let edits = edits
 8617                    .into_iter()
 8618                    .map(|range| {
 8619                        let end_point = TP::to_point(&range.end, &snapshot);
 8620                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8621
 8622                        if end_point == start_point {
 8623                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8624                                .saturating_sub(1);
 8625                            start_point =
 8626                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8627                        };
 8628
 8629                        (start_point..end_point, empty_str.clone())
 8630                    })
 8631                    .sorted_by_key(|(range, _)| range.start)
 8632                    .collect::<Vec<_>>();
 8633                buffer.update(cx, |this, cx| {
 8634                    this.edit(edits, None, cx);
 8635                })
 8636            }
 8637            this.refresh_inline_completion(true, false, window, cx);
 8638            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8639        });
 8640    }
 8641
 8642    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8643        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8644        self.transact(window, cx, |this, window, cx| {
 8645            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8646                s.move_with(|map, selection| {
 8647                    if selection.is_empty() {
 8648                        let cursor = movement::right(map, selection.head());
 8649                        selection.end = cursor;
 8650                        selection.reversed = true;
 8651                        selection.goal = SelectionGoal::None;
 8652                    }
 8653                })
 8654            });
 8655            this.insert("", window, cx);
 8656            this.refresh_inline_completion(true, false, window, cx);
 8657        });
 8658    }
 8659
 8660    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8661        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8662        if self.move_to_prev_snippet_tabstop(window, cx) {
 8663            return;
 8664        }
 8665        self.outdent(&Outdent, window, cx);
 8666    }
 8667
 8668    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8669        if self.move_to_next_snippet_tabstop(window, cx) {
 8670            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8671            return;
 8672        }
 8673        if self.read_only(cx) {
 8674            return;
 8675        }
 8676        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8677        let mut selections = self.selections.all_adjusted(cx);
 8678        let buffer = self.buffer.read(cx);
 8679        let snapshot = buffer.snapshot(cx);
 8680        let rows_iter = selections.iter().map(|s| s.head().row);
 8681        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8682
 8683        let has_some_cursor_in_whitespace = selections
 8684            .iter()
 8685            .filter(|selection| selection.is_empty())
 8686            .any(|selection| {
 8687                let cursor = selection.head();
 8688                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8689                cursor.column < current_indent.len
 8690            });
 8691
 8692        let mut edits = Vec::new();
 8693        let mut prev_edited_row = 0;
 8694        let mut row_delta = 0;
 8695        for selection in &mut selections {
 8696            if selection.start.row != prev_edited_row {
 8697                row_delta = 0;
 8698            }
 8699            prev_edited_row = selection.end.row;
 8700
 8701            // If the selection is non-empty, then increase the indentation of the selected lines.
 8702            if !selection.is_empty() {
 8703                row_delta =
 8704                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8705                continue;
 8706            }
 8707
 8708            // If the selection is empty and the cursor is in the leading whitespace before the
 8709            // suggested indentation, then auto-indent the line.
 8710            let cursor = selection.head();
 8711            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8712            if let Some(suggested_indent) =
 8713                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8714            {
 8715                // If there exist any empty selection in the leading whitespace, then skip
 8716                // indent for selections at the boundary.
 8717                if has_some_cursor_in_whitespace
 8718                    && cursor.column == current_indent.len
 8719                    && current_indent.len == suggested_indent.len
 8720                {
 8721                    continue;
 8722                }
 8723
 8724                if cursor.column < suggested_indent.len
 8725                    && cursor.column <= current_indent.len
 8726                    && current_indent.len <= suggested_indent.len
 8727                {
 8728                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8729                    selection.end = selection.start;
 8730                    if row_delta == 0 {
 8731                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8732                            cursor.row,
 8733                            current_indent,
 8734                            suggested_indent,
 8735                        ));
 8736                        row_delta = suggested_indent.len - current_indent.len;
 8737                    }
 8738                    continue;
 8739                }
 8740            }
 8741
 8742            // Otherwise, insert a hard or soft tab.
 8743            let settings = buffer.language_settings_at(cursor, cx);
 8744            let tab_size = if settings.hard_tabs {
 8745                IndentSize::tab()
 8746            } else {
 8747                let tab_size = settings.tab_size.get();
 8748                let indent_remainder = snapshot
 8749                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8750                    .flat_map(str::chars)
 8751                    .fold(row_delta % tab_size, |counter: u32, c| {
 8752                        if c == '\t' {
 8753                            0
 8754                        } else {
 8755                            (counter + 1) % tab_size
 8756                        }
 8757                    });
 8758
 8759                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8760                IndentSize::spaces(chars_to_next_tab_stop)
 8761            };
 8762            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8763            selection.end = selection.start;
 8764            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8765            row_delta += tab_size.len;
 8766        }
 8767
 8768        self.transact(window, cx, |this, window, cx| {
 8769            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8770            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8771                s.select(selections)
 8772            });
 8773            this.refresh_inline_completion(true, false, window, cx);
 8774        });
 8775    }
 8776
 8777    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8778        if self.read_only(cx) {
 8779            return;
 8780        }
 8781        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8782        let mut selections = self.selections.all::<Point>(cx);
 8783        let mut prev_edited_row = 0;
 8784        let mut row_delta = 0;
 8785        let mut edits = Vec::new();
 8786        let buffer = self.buffer.read(cx);
 8787        let snapshot = buffer.snapshot(cx);
 8788        for selection in &mut selections {
 8789            if selection.start.row != prev_edited_row {
 8790                row_delta = 0;
 8791            }
 8792            prev_edited_row = selection.end.row;
 8793
 8794            row_delta =
 8795                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8796        }
 8797
 8798        self.transact(window, cx, |this, window, cx| {
 8799            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8800            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8801                s.select(selections)
 8802            });
 8803        });
 8804    }
 8805
 8806    fn indent_selection(
 8807        buffer: &MultiBuffer,
 8808        snapshot: &MultiBufferSnapshot,
 8809        selection: &mut Selection<Point>,
 8810        edits: &mut Vec<(Range<Point>, String)>,
 8811        delta_for_start_row: u32,
 8812        cx: &App,
 8813    ) -> u32 {
 8814        let settings = buffer.language_settings_at(selection.start, cx);
 8815        let tab_size = settings.tab_size.get();
 8816        let indent_kind = if settings.hard_tabs {
 8817            IndentKind::Tab
 8818        } else {
 8819            IndentKind::Space
 8820        };
 8821        let mut start_row = selection.start.row;
 8822        let mut end_row = selection.end.row + 1;
 8823
 8824        // If a selection ends at the beginning of a line, don't indent
 8825        // that last line.
 8826        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8827            end_row -= 1;
 8828        }
 8829
 8830        // Avoid re-indenting a row that has already been indented by a
 8831        // previous selection, but still update this selection's column
 8832        // to reflect that indentation.
 8833        if delta_for_start_row > 0 {
 8834            start_row += 1;
 8835            selection.start.column += delta_for_start_row;
 8836            if selection.end.row == selection.start.row {
 8837                selection.end.column += delta_for_start_row;
 8838            }
 8839        }
 8840
 8841        let mut delta_for_end_row = 0;
 8842        let has_multiple_rows = start_row + 1 != end_row;
 8843        for row in start_row..end_row {
 8844            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8845            let indent_delta = match (current_indent.kind, indent_kind) {
 8846                (IndentKind::Space, IndentKind::Space) => {
 8847                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8848                    IndentSize::spaces(columns_to_next_tab_stop)
 8849                }
 8850                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8851                (_, IndentKind::Tab) => IndentSize::tab(),
 8852            };
 8853
 8854            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8855                0
 8856            } else {
 8857                selection.start.column
 8858            };
 8859            let row_start = Point::new(row, start);
 8860            edits.push((
 8861                row_start..row_start,
 8862                indent_delta.chars().collect::<String>(),
 8863            ));
 8864
 8865            // Update this selection's endpoints to reflect the indentation.
 8866            if row == selection.start.row {
 8867                selection.start.column += indent_delta.len;
 8868            }
 8869            if row == selection.end.row {
 8870                selection.end.column += indent_delta.len;
 8871                delta_for_end_row = indent_delta.len;
 8872            }
 8873        }
 8874
 8875        if selection.start.row == selection.end.row {
 8876            delta_for_start_row + delta_for_end_row
 8877        } else {
 8878            delta_for_end_row
 8879        }
 8880    }
 8881
 8882    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8883        if self.read_only(cx) {
 8884            return;
 8885        }
 8886        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8888        let selections = self.selections.all::<Point>(cx);
 8889        let mut deletion_ranges = Vec::new();
 8890        let mut last_outdent = None;
 8891        {
 8892            let buffer = self.buffer.read(cx);
 8893            let snapshot = buffer.snapshot(cx);
 8894            for selection in &selections {
 8895                let settings = buffer.language_settings_at(selection.start, cx);
 8896                let tab_size = settings.tab_size.get();
 8897                let mut rows = selection.spanned_rows(false, &display_map);
 8898
 8899                // Avoid re-outdenting a row that has already been outdented by a
 8900                // previous selection.
 8901                if let Some(last_row) = last_outdent {
 8902                    if last_row == rows.start {
 8903                        rows.start = rows.start.next_row();
 8904                    }
 8905                }
 8906                let has_multiple_rows = rows.len() > 1;
 8907                for row in rows.iter_rows() {
 8908                    let indent_size = snapshot.indent_size_for_line(row);
 8909                    if indent_size.len > 0 {
 8910                        let deletion_len = match indent_size.kind {
 8911                            IndentKind::Space => {
 8912                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8913                                if columns_to_prev_tab_stop == 0 {
 8914                                    tab_size
 8915                                } else {
 8916                                    columns_to_prev_tab_stop
 8917                                }
 8918                            }
 8919                            IndentKind::Tab => 1,
 8920                        };
 8921                        let start = if has_multiple_rows
 8922                            || deletion_len > selection.start.column
 8923                            || indent_size.len < selection.start.column
 8924                        {
 8925                            0
 8926                        } else {
 8927                            selection.start.column - deletion_len
 8928                        };
 8929                        deletion_ranges.push(
 8930                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8931                        );
 8932                        last_outdent = Some(row);
 8933                    }
 8934                }
 8935            }
 8936        }
 8937
 8938        self.transact(window, cx, |this, window, cx| {
 8939            this.buffer.update(cx, |buffer, cx| {
 8940                let empty_str: Arc<str> = Arc::default();
 8941                buffer.edit(
 8942                    deletion_ranges
 8943                        .into_iter()
 8944                        .map(|range| (range, empty_str.clone())),
 8945                    None,
 8946                    cx,
 8947                );
 8948            });
 8949            let selections = this.selections.all::<usize>(cx);
 8950            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8951                s.select(selections)
 8952            });
 8953        });
 8954    }
 8955
 8956    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8957        if self.read_only(cx) {
 8958            return;
 8959        }
 8960        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8961        let selections = self
 8962            .selections
 8963            .all::<usize>(cx)
 8964            .into_iter()
 8965            .map(|s| s.range());
 8966
 8967        self.transact(window, cx, |this, window, cx| {
 8968            this.buffer.update(cx, |buffer, cx| {
 8969                buffer.autoindent_ranges(selections, cx);
 8970            });
 8971            let selections = this.selections.all::<usize>(cx);
 8972            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8973                s.select(selections)
 8974            });
 8975        });
 8976    }
 8977
 8978    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8979        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8981        let selections = self.selections.all::<Point>(cx);
 8982
 8983        let mut new_cursors = Vec::new();
 8984        let mut edit_ranges = Vec::new();
 8985        let mut selections = selections.iter().peekable();
 8986        while let Some(selection) = selections.next() {
 8987            let mut rows = selection.spanned_rows(false, &display_map);
 8988            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8989
 8990            // Accumulate contiguous regions of rows that we want to delete.
 8991            while let Some(next_selection) = selections.peek() {
 8992                let next_rows = next_selection.spanned_rows(false, &display_map);
 8993                if next_rows.start <= rows.end {
 8994                    rows.end = next_rows.end;
 8995                    selections.next().unwrap();
 8996                } else {
 8997                    break;
 8998                }
 8999            }
 9000
 9001            let buffer = &display_map.buffer_snapshot;
 9002            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 9003            let edit_end;
 9004            let cursor_buffer_row;
 9005            if buffer.max_point().row >= rows.end.0 {
 9006                // If there's a line after the range, delete the \n from the end of the row range
 9007                // and position the cursor on the next line.
 9008                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 9009                cursor_buffer_row = rows.end;
 9010            } else {
 9011                // If there isn't a line after the range, delete the \n from the line before the
 9012                // start of the row range and position the cursor there.
 9013                edit_start = edit_start.saturating_sub(1);
 9014                edit_end = buffer.len();
 9015                cursor_buffer_row = rows.start.previous_row();
 9016            }
 9017
 9018            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 9019            *cursor.column_mut() =
 9020                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 9021
 9022            new_cursors.push((
 9023                selection.id,
 9024                buffer.anchor_after(cursor.to_point(&display_map)),
 9025            ));
 9026            edit_ranges.push(edit_start..edit_end);
 9027        }
 9028
 9029        self.transact(window, cx, |this, window, cx| {
 9030            let buffer = this.buffer.update(cx, |buffer, cx| {
 9031                let empty_str: Arc<str> = Arc::default();
 9032                buffer.edit(
 9033                    edit_ranges
 9034                        .into_iter()
 9035                        .map(|range| (range, empty_str.clone())),
 9036                    None,
 9037                    cx,
 9038                );
 9039                buffer.snapshot(cx)
 9040            });
 9041            let new_selections = new_cursors
 9042                .into_iter()
 9043                .map(|(id, cursor)| {
 9044                    let cursor = cursor.to_point(&buffer);
 9045                    Selection {
 9046                        id,
 9047                        start: cursor,
 9048                        end: cursor,
 9049                        reversed: false,
 9050                        goal: SelectionGoal::None,
 9051                    }
 9052                })
 9053                .collect();
 9054
 9055            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9056                s.select(new_selections);
 9057            });
 9058        });
 9059    }
 9060
 9061    pub fn join_lines_impl(
 9062        &mut self,
 9063        insert_whitespace: bool,
 9064        window: &mut Window,
 9065        cx: &mut Context<Self>,
 9066    ) {
 9067        if self.read_only(cx) {
 9068            return;
 9069        }
 9070        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9071        for selection in self.selections.all::<Point>(cx) {
 9072            let start = MultiBufferRow(selection.start.row);
 9073            // Treat single line selections as if they include the next line. Otherwise this action
 9074            // would do nothing for single line selections individual cursors.
 9075            let end = if selection.start.row == selection.end.row {
 9076                MultiBufferRow(selection.start.row + 1)
 9077            } else {
 9078                MultiBufferRow(selection.end.row)
 9079            };
 9080
 9081            if let Some(last_row_range) = row_ranges.last_mut() {
 9082                if start <= last_row_range.end {
 9083                    last_row_range.end = end;
 9084                    continue;
 9085                }
 9086            }
 9087            row_ranges.push(start..end);
 9088        }
 9089
 9090        let snapshot = self.buffer.read(cx).snapshot(cx);
 9091        let mut cursor_positions = Vec::new();
 9092        for row_range in &row_ranges {
 9093            let anchor = snapshot.anchor_before(Point::new(
 9094                row_range.end.previous_row().0,
 9095                snapshot.line_len(row_range.end.previous_row()),
 9096            ));
 9097            cursor_positions.push(anchor..anchor);
 9098        }
 9099
 9100        self.transact(window, cx, |this, window, cx| {
 9101            for row_range in row_ranges.into_iter().rev() {
 9102                for row in row_range.iter_rows().rev() {
 9103                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9104                    let next_line_row = row.next_row();
 9105                    let indent = snapshot.indent_size_for_line(next_line_row);
 9106                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9107
 9108                    let replace =
 9109                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9110                            " "
 9111                        } else {
 9112                            ""
 9113                        };
 9114
 9115                    this.buffer.update(cx, |buffer, cx| {
 9116                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9117                    });
 9118                }
 9119            }
 9120
 9121            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9122                s.select_anchor_ranges(cursor_positions)
 9123            });
 9124        });
 9125    }
 9126
 9127    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9128        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9129        self.join_lines_impl(true, window, cx);
 9130    }
 9131
 9132    pub fn sort_lines_case_sensitive(
 9133        &mut self,
 9134        _: &SortLinesCaseSensitive,
 9135        window: &mut Window,
 9136        cx: &mut Context<Self>,
 9137    ) {
 9138        self.manipulate_lines(window, cx, |lines| lines.sort())
 9139    }
 9140
 9141    pub fn sort_lines_case_insensitive(
 9142        &mut self,
 9143        _: &SortLinesCaseInsensitive,
 9144        window: &mut Window,
 9145        cx: &mut Context<Self>,
 9146    ) {
 9147        self.manipulate_lines(window, cx, |lines| {
 9148            lines.sort_by_key(|line| line.to_lowercase())
 9149        })
 9150    }
 9151
 9152    pub fn unique_lines_case_insensitive(
 9153        &mut self,
 9154        _: &UniqueLinesCaseInsensitive,
 9155        window: &mut Window,
 9156        cx: &mut Context<Self>,
 9157    ) {
 9158        self.manipulate_lines(window, cx, |lines| {
 9159            let mut seen = HashSet::default();
 9160            lines.retain(|line| seen.insert(line.to_lowercase()));
 9161        })
 9162    }
 9163
 9164    pub fn unique_lines_case_sensitive(
 9165        &mut self,
 9166        _: &UniqueLinesCaseSensitive,
 9167        window: &mut Window,
 9168        cx: &mut Context<Self>,
 9169    ) {
 9170        self.manipulate_lines(window, cx, |lines| {
 9171            let mut seen = HashSet::default();
 9172            lines.retain(|line| seen.insert(*line));
 9173        })
 9174    }
 9175
 9176    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9177        let Some(project) = self.project.clone() else {
 9178            return;
 9179        };
 9180        self.reload(project, window, cx)
 9181            .detach_and_notify_err(window, cx);
 9182    }
 9183
 9184    pub fn restore_file(
 9185        &mut self,
 9186        _: &::git::RestoreFile,
 9187        window: &mut Window,
 9188        cx: &mut Context<Self>,
 9189    ) {
 9190        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9191        let mut buffer_ids = HashSet::default();
 9192        let snapshot = self.buffer().read(cx).snapshot(cx);
 9193        for selection in self.selections.all::<usize>(cx) {
 9194            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9195        }
 9196
 9197        let buffer = self.buffer().read(cx);
 9198        let ranges = buffer_ids
 9199            .into_iter()
 9200            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9201            .collect::<Vec<_>>();
 9202
 9203        self.restore_hunks_in_ranges(ranges, window, cx);
 9204    }
 9205
 9206    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9207        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9208        let selections = self
 9209            .selections
 9210            .all(cx)
 9211            .into_iter()
 9212            .map(|s| s.range())
 9213            .collect();
 9214        self.restore_hunks_in_ranges(selections, window, cx);
 9215    }
 9216
 9217    pub fn restore_hunks_in_ranges(
 9218        &mut self,
 9219        ranges: Vec<Range<Point>>,
 9220        window: &mut Window,
 9221        cx: &mut Context<Editor>,
 9222    ) {
 9223        let mut revert_changes = HashMap::default();
 9224        let chunk_by = self
 9225            .snapshot(window, cx)
 9226            .hunks_for_ranges(ranges)
 9227            .into_iter()
 9228            .chunk_by(|hunk| hunk.buffer_id);
 9229        for (buffer_id, hunks) in &chunk_by {
 9230            let hunks = hunks.collect::<Vec<_>>();
 9231            for hunk in &hunks {
 9232                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9233            }
 9234            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9235        }
 9236        drop(chunk_by);
 9237        if !revert_changes.is_empty() {
 9238            self.transact(window, cx, |editor, window, cx| {
 9239                editor.restore(revert_changes, window, cx);
 9240            });
 9241        }
 9242    }
 9243
 9244    pub fn open_active_item_in_terminal(
 9245        &mut self,
 9246        _: &OpenInTerminal,
 9247        window: &mut Window,
 9248        cx: &mut Context<Self>,
 9249    ) {
 9250        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9251            let project_path = buffer.read(cx).project_path(cx)?;
 9252            let project = self.project.as_ref()?.read(cx);
 9253            let entry = project.entry_for_path(&project_path, cx)?;
 9254            let parent = match &entry.canonical_path {
 9255                Some(canonical_path) => canonical_path.to_path_buf(),
 9256                None => project.absolute_path(&project_path, cx)?,
 9257            }
 9258            .parent()?
 9259            .to_path_buf();
 9260            Some(parent)
 9261        }) {
 9262            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9263        }
 9264    }
 9265
 9266    fn set_breakpoint_context_menu(
 9267        &mut self,
 9268        display_row: DisplayRow,
 9269        position: Option<Anchor>,
 9270        clicked_point: gpui::Point<Pixels>,
 9271        window: &mut Window,
 9272        cx: &mut Context<Self>,
 9273    ) {
 9274        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9275            return;
 9276        }
 9277        let source = self
 9278            .buffer
 9279            .read(cx)
 9280            .snapshot(cx)
 9281            .anchor_before(Point::new(display_row.0, 0u32));
 9282
 9283        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9284
 9285        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9286            self,
 9287            source,
 9288            clicked_point,
 9289            context_menu,
 9290            window,
 9291            cx,
 9292        );
 9293    }
 9294
 9295    fn add_edit_breakpoint_block(
 9296        &mut self,
 9297        anchor: Anchor,
 9298        breakpoint: &Breakpoint,
 9299        edit_action: BreakpointPromptEditAction,
 9300        window: &mut Window,
 9301        cx: &mut Context<Self>,
 9302    ) {
 9303        let weak_editor = cx.weak_entity();
 9304        let bp_prompt = cx.new(|cx| {
 9305            BreakpointPromptEditor::new(
 9306                weak_editor,
 9307                anchor,
 9308                breakpoint.clone(),
 9309                edit_action,
 9310                window,
 9311                cx,
 9312            )
 9313        });
 9314
 9315        let height = bp_prompt.update(cx, |this, cx| {
 9316            this.prompt
 9317                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9318        });
 9319        let cloned_prompt = bp_prompt.clone();
 9320        let blocks = vec![BlockProperties {
 9321            style: BlockStyle::Sticky,
 9322            placement: BlockPlacement::Above(anchor),
 9323            height: Some(height),
 9324            render: Arc::new(move |cx| {
 9325                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9326                cloned_prompt.clone().into_any_element()
 9327            }),
 9328            priority: 0,
 9329        }];
 9330
 9331        let focus_handle = bp_prompt.focus_handle(cx);
 9332        window.focus(&focus_handle);
 9333
 9334        let block_ids = self.insert_blocks(blocks, None, cx);
 9335        bp_prompt.update(cx, |prompt, _| {
 9336            prompt.add_block_ids(block_ids);
 9337        });
 9338    }
 9339
 9340    pub(crate) fn breakpoint_at_row(
 9341        &self,
 9342        row: u32,
 9343        window: &mut Window,
 9344        cx: &mut Context<Self>,
 9345    ) -> Option<(Anchor, Breakpoint)> {
 9346        let snapshot = self.snapshot(window, cx);
 9347        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9348
 9349        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9350    }
 9351
 9352    pub(crate) fn breakpoint_at_anchor(
 9353        &self,
 9354        breakpoint_position: Anchor,
 9355        snapshot: &EditorSnapshot,
 9356        cx: &mut Context<Self>,
 9357    ) -> Option<(Anchor, Breakpoint)> {
 9358        let project = self.project.clone()?;
 9359
 9360        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9361            snapshot
 9362                .buffer_snapshot
 9363                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9364        })?;
 9365
 9366        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9367        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9368        let buffer_snapshot = buffer.read(cx).snapshot();
 9369
 9370        let row = buffer_snapshot
 9371            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9372            .row;
 9373
 9374        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9375        let anchor_end = snapshot
 9376            .buffer_snapshot
 9377            .anchor_after(Point::new(row, line_len));
 9378
 9379        let bp = self
 9380            .breakpoint_store
 9381            .as_ref()?
 9382            .read_with(cx, |breakpoint_store, cx| {
 9383                breakpoint_store
 9384                    .breakpoints(
 9385                        &buffer,
 9386                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9387                        &buffer_snapshot,
 9388                        cx,
 9389                    )
 9390                    .next()
 9391                    .and_then(|(anchor, bp)| {
 9392                        let breakpoint_row = buffer_snapshot
 9393                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9394                            .row;
 9395
 9396                        if breakpoint_row == row {
 9397                            snapshot
 9398                                .buffer_snapshot
 9399                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9400                                .map(|anchor| (anchor, bp.clone()))
 9401                        } else {
 9402                            None
 9403                        }
 9404                    })
 9405            });
 9406        bp
 9407    }
 9408
 9409    pub fn edit_log_breakpoint(
 9410        &mut self,
 9411        _: &EditLogBreakpoint,
 9412        window: &mut Window,
 9413        cx: &mut Context<Self>,
 9414    ) {
 9415        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9416            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9417                message: None,
 9418                state: BreakpointState::Enabled,
 9419                condition: None,
 9420                hit_condition: None,
 9421            });
 9422
 9423            self.add_edit_breakpoint_block(
 9424                anchor,
 9425                &breakpoint,
 9426                BreakpointPromptEditAction::Log,
 9427                window,
 9428                cx,
 9429            );
 9430        }
 9431    }
 9432
 9433    fn breakpoints_at_cursors(
 9434        &self,
 9435        window: &mut Window,
 9436        cx: &mut Context<Self>,
 9437    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9438        let snapshot = self.snapshot(window, cx);
 9439        let cursors = self
 9440            .selections
 9441            .disjoint_anchors()
 9442            .into_iter()
 9443            .map(|selection| {
 9444                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9445
 9446                let breakpoint_position = self
 9447                    .breakpoint_at_row(cursor_position.row, window, cx)
 9448                    .map(|bp| bp.0)
 9449                    .unwrap_or_else(|| {
 9450                        snapshot
 9451                            .display_snapshot
 9452                            .buffer_snapshot
 9453                            .anchor_after(Point::new(cursor_position.row, 0))
 9454                    });
 9455
 9456                let breakpoint = self
 9457                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9458                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9459
 9460                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9461            })
 9462            // 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.
 9463            .collect::<HashMap<Anchor, _>>();
 9464
 9465        cursors.into_iter().collect()
 9466    }
 9467
 9468    pub fn enable_breakpoint(
 9469        &mut self,
 9470        _: &crate::actions::EnableBreakpoint,
 9471        window: &mut Window,
 9472        cx: &mut Context<Self>,
 9473    ) {
 9474        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9475            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9476                continue;
 9477            };
 9478            self.edit_breakpoint_at_anchor(
 9479                anchor,
 9480                breakpoint,
 9481                BreakpointEditAction::InvertState,
 9482                cx,
 9483            );
 9484        }
 9485    }
 9486
 9487    pub fn disable_breakpoint(
 9488        &mut self,
 9489        _: &crate::actions::DisableBreakpoint,
 9490        window: &mut Window,
 9491        cx: &mut Context<Self>,
 9492    ) {
 9493        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9494            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9495                continue;
 9496            };
 9497            self.edit_breakpoint_at_anchor(
 9498                anchor,
 9499                breakpoint,
 9500                BreakpointEditAction::InvertState,
 9501                cx,
 9502            );
 9503        }
 9504    }
 9505
 9506    pub fn toggle_breakpoint(
 9507        &mut self,
 9508        _: &crate::actions::ToggleBreakpoint,
 9509        window: &mut Window,
 9510        cx: &mut Context<Self>,
 9511    ) {
 9512        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9513            if let Some(breakpoint) = breakpoint {
 9514                self.edit_breakpoint_at_anchor(
 9515                    anchor,
 9516                    breakpoint,
 9517                    BreakpointEditAction::Toggle,
 9518                    cx,
 9519                );
 9520            } else {
 9521                self.edit_breakpoint_at_anchor(
 9522                    anchor,
 9523                    Breakpoint::new_standard(),
 9524                    BreakpointEditAction::Toggle,
 9525                    cx,
 9526                );
 9527            }
 9528        }
 9529    }
 9530
 9531    pub fn edit_breakpoint_at_anchor(
 9532        &mut self,
 9533        breakpoint_position: Anchor,
 9534        breakpoint: Breakpoint,
 9535        edit_action: BreakpointEditAction,
 9536        cx: &mut Context<Self>,
 9537    ) {
 9538        let Some(breakpoint_store) = &self.breakpoint_store else {
 9539            return;
 9540        };
 9541
 9542        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9543            if breakpoint_position == Anchor::min() {
 9544                self.buffer()
 9545                    .read(cx)
 9546                    .excerpt_buffer_ids()
 9547                    .into_iter()
 9548                    .next()
 9549            } else {
 9550                None
 9551            }
 9552        }) else {
 9553            return;
 9554        };
 9555
 9556        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9557            return;
 9558        };
 9559
 9560        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9561            breakpoint_store.toggle_breakpoint(
 9562                buffer,
 9563                (breakpoint_position.text_anchor, breakpoint),
 9564                edit_action,
 9565                cx,
 9566            );
 9567        });
 9568
 9569        cx.notify();
 9570    }
 9571
 9572    #[cfg(any(test, feature = "test-support"))]
 9573    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9574        self.breakpoint_store.clone()
 9575    }
 9576
 9577    pub fn prepare_restore_change(
 9578        &self,
 9579        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9580        hunk: &MultiBufferDiffHunk,
 9581        cx: &mut App,
 9582    ) -> Option<()> {
 9583        if hunk.is_created_file() {
 9584            return None;
 9585        }
 9586        let buffer = self.buffer.read(cx);
 9587        let diff = buffer.diff_for(hunk.buffer_id)?;
 9588        let buffer = buffer.buffer(hunk.buffer_id)?;
 9589        let buffer = buffer.read(cx);
 9590        let original_text = diff
 9591            .read(cx)
 9592            .base_text()
 9593            .as_rope()
 9594            .slice(hunk.diff_base_byte_range.clone());
 9595        let buffer_snapshot = buffer.snapshot();
 9596        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9597        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9598            probe
 9599                .0
 9600                .start
 9601                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9602                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9603        }) {
 9604            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9605            Some(())
 9606        } else {
 9607            None
 9608        }
 9609    }
 9610
 9611    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9612        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9613    }
 9614
 9615    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9616        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9617    }
 9618
 9619    fn manipulate_lines<Fn>(
 9620        &mut self,
 9621        window: &mut Window,
 9622        cx: &mut Context<Self>,
 9623        mut callback: Fn,
 9624    ) where
 9625        Fn: FnMut(&mut Vec<&str>),
 9626    {
 9627        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9628
 9629        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9630        let buffer = self.buffer.read(cx).snapshot(cx);
 9631
 9632        let mut edits = Vec::new();
 9633
 9634        let selections = self.selections.all::<Point>(cx);
 9635        let mut selections = selections.iter().peekable();
 9636        let mut contiguous_row_selections = Vec::new();
 9637        let mut new_selections = Vec::new();
 9638        let mut added_lines = 0;
 9639        let mut removed_lines = 0;
 9640
 9641        while let Some(selection) = selections.next() {
 9642            let (start_row, end_row) = consume_contiguous_rows(
 9643                &mut contiguous_row_selections,
 9644                selection,
 9645                &display_map,
 9646                &mut selections,
 9647            );
 9648
 9649            let start_point = Point::new(start_row.0, 0);
 9650            let end_point = Point::new(
 9651                end_row.previous_row().0,
 9652                buffer.line_len(end_row.previous_row()),
 9653            );
 9654            let text = buffer
 9655                .text_for_range(start_point..end_point)
 9656                .collect::<String>();
 9657
 9658            let mut lines = text.split('\n').collect_vec();
 9659
 9660            let lines_before = lines.len();
 9661            callback(&mut lines);
 9662            let lines_after = lines.len();
 9663
 9664            edits.push((start_point..end_point, lines.join("\n")));
 9665
 9666            // Selections must change based on added and removed line count
 9667            let start_row =
 9668                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9669            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9670            new_selections.push(Selection {
 9671                id: selection.id,
 9672                start: start_row,
 9673                end: end_row,
 9674                goal: SelectionGoal::None,
 9675                reversed: selection.reversed,
 9676            });
 9677
 9678            if lines_after > lines_before {
 9679                added_lines += lines_after - lines_before;
 9680            } else if lines_before > lines_after {
 9681                removed_lines += lines_before - lines_after;
 9682            }
 9683        }
 9684
 9685        self.transact(window, cx, |this, window, cx| {
 9686            let buffer = this.buffer.update(cx, |buffer, cx| {
 9687                buffer.edit(edits, None, cx);
 9688                buffer.snapshot(cx)
 9689            });
 9690
 9691            // Recalculate offsets on newly edited buffer
 9692            let new_selections = new_selections
 9693                .iter()
 9694                .map(|s| {
 9695                    let start_point = Point::new(s.start.0, 0);
 9696                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9697                    Selection {
 9698                        id: s.id,
 9699                        start: buffer.point_to_offset(start_point),
 9700                        end: buffer.point_to_offset(end_point),
 9701                        goal: s.goal,
 9702                        reversed: s.reversed,
 9703                    }
 9704                })
 9705                .collect();
 9706
 9707            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9708                s.select(new_selections);
 9709            });
 9710
 9711            this.request_autoscroll(Autoscroll::fit(), cx);
 9712        });
 9713    }
 9714
 9715    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9716        self.manipulate_text(window, cx, |text| {
 9717            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9718            if has_upper_case_characters {
 9719                text.to_lowercase()
 9720            } else {
 9721                text.to_uppercase()
 9722            }
 9723        })
 9724    }
 9725
 9726    pub fn convert_to_upper_case(
 9727        &mut self,
 9728        _: &ConvertToUpperCase,
 9729        window: &mut Window,
 9730        cx: &mut Context<Self>,
 9731    ) {
 9732        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9733    }
 9734
 9735    pub fn convert_to_lower_case(
 9736        &mut self,
 9737        _: &ConvertToLowerCase,
 9738        window: &mut Window,
 9739        cx: &mut Context<Self>,
 9740    ) {
 9741        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9742    }
 9743
 9744    pub fn convert_to_title_case(
 9745        &mut self,
 9746        _: &ConvertToTitleCase,
 9747        window: &mut Window,
 9748        cx: &mut Context<Self>,
 9749    ) {
 9750        self.manipulate_text(window, cx, |text| {
 9751            text.split('\n')
 9752                .map(|line| line.to_case(Case::Title))
 9753                .join("\n")
 9754        })
 9755    }
 9756
 9757    pub fn convert_to_snake_case(
 9758        &mut self,
 9759        _: &ConvertToSnakeCase,
 9760        window: &mut Window,
 9761        cx: &mut Context<Self>,
 9762    ) {
 9763        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9764    }
 9765
 9766    pub fn convert_to_kebab_case(
 9767        &mut self,
 9768        _: &ConvertToKebabCase,
 9769        window: &mut Window,
 9770        cx: &mut Context<Self>,
 9771    ) {
 9772        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9773    }
 9774
 9775    pub fn convert_to_upper_camel_case(
 9776        &mut self,
 9777        _: &ConvertToUpperCamelCase,
 9778        window: &mut Window,
 9779        cx: &mut Context<Self>,
 9780    ) {
 9781        self.manipulate_text(window, cx, |text| {
 9782            text.split('\n')
 9783                .map(|line| line.to_case(Case::UpperCamel))
 9784                .join("\n")
 9785        })
 9786    }
 9787
 9788    pub fn convert_to_lower_camel_case(
 9789        &mut self,
 9790        _: &ConvertToLowerCamelCase,
 9791        window: &mut Window,
 9792        cx: &mut Context<Self>,
 9793    ) {
 9794        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9795    }
 9796
 9797    pub fn convert_to_opposite_case(
 9798        &mut self,
 9799        _: &ConvertToOppositeCase,
 9800        window: &mut Window,
 9801        cx: &mut Context<Self>,
 9802    ) {
 9803        self.manipulate_text(window, cx, |text| {
 9804            text.chars()
 9805                .fold(String::with_capacity(text.len()), |mut t, c| {
 9806                    if c.is_uppercase() {
 9807                        t.extend(c.to_lowercase());
 9808                    } else {
 9809                        t.extend(c.to_uppercase());
 9810                    }
 9811                    t
 9812                })
 9813        })
 9814    }
 9815
 9816    pub fn convert_to_rot13(
 9817        &mut self,
 9818        _: &ConvertToRot13,
 9819        window: &mut Window,
 9820        cx: &mut Context<Self>,
 9821    ) {
 9822        self.manipulate_text(window, cx, |text| {
 9823            text.chars()
 9824                .map(|c| match c {
 9825                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9826                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9827                    _ => c,
 9828                })
 9829                .collect()
 9830        })
 9831    }
 9832
 9833    pub fn convert_to_rot47(
 9834        &mut self,
 9835        _: &ConvertToRot47,
 9836        window: &mut Window,
 9837        cx: &mut Context<Self>,
 9838    ) {
 9839        self.manipulate_text(window, cx, |text| {
 9840            text.chars()
 9841                .map(|c| {
 9842                    let code_point = c as u32;
 9843                    if code_point >= 33 && code_point <= 126 {
 9844                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9845                    }
 9846                    c
 9847                })
 9848                .collect()
 9849        })
 9850    }
 9851
 9852    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9853    where
 9854        Fn: FnMut(&str) -> String,
 9855    {
 9856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9857        let buffer = self.buffer.read(cx).snapshot(cx);
 9858
 9859        let mut new_selections = Vec::new();
 9860        let mut edits = Vec::new();
 9861        let mut selection_adjustment = 0i32;
 9862
 9863        for selection in self.selections.all::<usize>(cx) {
 9864            let selection_is_empty = selection.is_empty();
 9865
 9866            let (start, end) = if selection_is_empty {
 9867                let word_range = movement::surrounding_word(
 9868                    &display_map,
 9869                    selection.start.to_display_point(&display_map),
 9870                );
 9871                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9872                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9873                (start, end)
 9874            } else {
 9875                (selection.start, selection.end)
 9876            };
 9877
 9878            let text = buffer.text_for_range(start..end).collect::<String>();
 9879            let old_length = text.len() as i32;
 9880            let text = callback(&text);
 9881
 9882            new_selections.push(Selection {
 9883                start: (start as i32 - selection_adjustment) as usize,
 9884                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9885                goal: SelectionGoal::None,
 9886                ..selection
 9887            });
 9888
 9889            selection_adjustment += old_length - text.len() as i32;
 9890
 9891            edits.push((start..end, text));
 9892        }
 9893
 9894        self.transact(window, cx, |this, window, cx| {
 9895            this.buffer.update(cx, |buffer, cx| {
 9896                buffer.edit(edits, None, cx);
 9897            });
 9898
 9899            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9900                s.select(new_selections);
 9901            });
 9902
 9903            this.request_autoscroll(Autoscroll::fit(), cx);
 9904        });
 9905    }
 9906
 9907    pub fn duplicate(
 9908        &mut self,
 9909        upwards: bool,
 9910        whole_lines: bool,
 9911        window: &mut Window,
 9912        cx: &mut Context<Self>,
 9913    ) {
 9914        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9915
 9916        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9917        let buffer = &display_map.buffer_snapshot;
 9918        let selections = self.selections.all::<Point>(cx);
 9919
 9920        let mut edits = Vec::new();
 9921        let mut selections_iter = selections.iter().peekable();
 9922        while let Some(selection) = selections_iter.next() {
 9923            let mut rows = selection.spanned_rows(false, &display_map);
 9924            // duplicate line-wise
 9925            if whole_lines || selection.start == selection.end {
 9926                // Avoid duplicating the same lines twice.
 9927                while let Some(next_selection) = selections_iter.peek() {
 9928                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9929                    if next_rows.start < rows.end {
 9930                        rows.end = next_rows.end;
 9931                        selections_iter.next().unwrap();
 9932                    } else {
 9933                        break;
 9934                    }
 9935                }
 9936
 9937                // Copy the text from the selected row region and splice it either at the start
 9938                // or end of the region.
 9939                let start = Point::new(rows.start.0, 0);
 9940                let end = Point::new(
 9941                    rows.end.previous_row().0,
 9942                    buffer.line_len(rows.end.previous_row()),
 9943                );
 9944                let text = buffer
 9945                    .text_for_range(start..end)
 9946                    .chain(Some("\n"))
 9947                    .collect::<String>();
 9948                let insert_location = if upwards {
 9949                    Point::new(rows.end.0, 0)
 9950                } else {
 9951                    start
 9952                };
 9953                edits.push((insert_location..insert_location, text));
 9954            } else {
 9955                // duplicate character-wise
 9956                let start = selection.start;
 9957                let end = selection.end;
 9958                let text = buffer.text_for_range(start..end).collect::<String>();
 9959                edits.push((selection.end..selection.end, text));
 9960            }
 9961        }
 9962
 9963        self.transact(window, cx, |this, _, cx| {
 9964            this.buffer.update(cx, |buffer, cx| {
 9965                buffer.edit(edits, None, cx);
 9966            });
 9967
 9968            this.request_autoscroll(Autoscroll::fit(), cx);
 9969        });
 9970    }
 9971
 9972    pub fn duplicate_line_up(
 9973        &mut self,
 9974        _: &DuplicateLineUp,
 9975        window: &mut Window,
 9976        cx: &mut Context<Self>,
 9977    ) {
 9978        self.duplicate(true, true, window, cx);
 9979    }
 9980
 9981    pub fn duplicate_line_down(
 9982        &mut self,
 9983        _: &DuplicateLineDown,
 9984        window: &mut Window,
 9985        cx: &mut Context<Self>,
 9986    ) {
 9987        self.duplicate(false, true, window, cx);
 9988    }
 9989
 9990    pub fn duplicate_selection(
 9991        &mut self,
 9992        _: &DuplicateSelection,
 9993        window: &mut Window,
 9994        cx: &mut Context<Self>,
 9995    ) {
 9996        self.duplicate(false, false, window, cx);
 9997    }
 9998
 9999    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10000        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10001
10002        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10003        let buffer = self.buffer.read(cx).snapshot(cx);
10004
10005        let mut edits = Vec::new();
10006        let mut unfold_ranges = Vec::new();
10007        let mut refold_creases = Vec::new();
10008
10009        let selections = self.selections.all::<Point>(cx);
10010        let mut selections = selections.iter().peekable();
10011        let mut contiguous_row_selections = Vec::new();
10012        let mut new_selections = Vec::new();
10013
10014        while let Some(selection) = selections.next() {
10015            // Find all the selections that span a contiguous row range
10016            let (start_row, end_row) = consume_contiguous_rows(
10017                &mut contiguous_row_selections,
10018                selection,
10019                &display_map,
10020                &mut selections,
10021            );
10022
10023            // Move the text spanned by the row range to be before the line preceding the row range
10024            if start_row.0 > 0 {
10025                let range_to_move = Point::new(
10026                    start_row.previous_row().0,
10027                    buffer.line_len(start_row.previous_row()),
10028                )
10029                    ..Point::new(
10030                        end_row.previous_row().0,
10031                        buffer.line_len(end_row.previous_row()),
10032                    );
10033                let insertion_point = display_map
10034                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10035                    .0;
10036
10037                // Don't move lines across excerpts
10038                if buffer
10039                    .excerpt_containing(insertion_point..range_to_move.end)
10040                    .is_some()
10041                {
10042                    let text = buffer
10043                        .text_for_range(range_to_move.clone())
10044                        .flat_map(|s| s.chars())
10045                        .skip(1)
10046                        .chain(['\n'])
10047                        .collect::<String>();
10048
10049                    edits.push((
10050                        buffer.anchor_after(range_to_move.start)
10051                            ..buffer.anchor_before(range_to_move.end),
10052                        String::new(),
10053                    ));
10054                    let insertion_anchor = buffer.anchor_after(insertion_point);
10055                    edits.push((insertion_anchor..insertion_anchor, text));
10056
10057                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10058
10059                    // Move selections up
10060                    new_selections.extend(contiguous_row_selections.drain(..).map(
10061                        |mut selection| {
10062                            selection.start.row -= row_delta;
10063                            selection.end.row -= row_delta;
10064                            selection
10065                        },
10066                    ));
10067
10068                    // Move folds up
10069                    unfold_ranges.push(range_to_move.clone());
10070                    for fold in display_map.folds_in_range(
10071                        buffer.anchor_before(range_to_move.start)
10072                            ..buffer.anchor_after(range_to_move.end),
10073                    ) {
10074                        let mut start = fold.range.start.to_point(&buffer);
10075                        let mut end = fold.range.end.to_point(&buffer);
10076                        start.row -= row_delta;
10077                        end.row -= row_delta;
10078                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10079                    }
10080                }
10081            }
10082
10083            // If we didn't move line(s), preserve the existing selections
10084            new_selections.append(&mut contiguous_row_selections);
10085        }
10086
10087        self.transact(window, cx, |this, window, cx| {
10088            this.unfold_ranges(&unfold_ranges, true, true, cx);
10089            this.buffer.update(cx, |buffer, cx| {
10090                for (range, text) in edits {
10091                    buffer.edit([(range, text)], None, cx);
10092                }
10093            });
10094            this.fold_creases(refold_creases, true, window, cx);
10095            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10096                s.select(new_selections);
10097            })
10098        });
10099    }
10100
10101    pub fn move_line_down(
10102        &mut self,
10103        _: &MoveLineDown,
10104        window: &mut Window,
10105        cx: &mut Context<Self>,
10106    ) {
10107        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10108
10109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10110        let buffer = self.buffer.read(cx).snapshot(cx);
10111
10112        let mut edits = Vec::new();
10113        let mut unfold_ranges = Vec::new();
10114        let mut refold_creases = Vec::new();
10115
10116        let selections = self.selections.all::<Point>(cx);
10117        let mut selections = selections.iter().peekable();
10118        let mut contiguous_row_selections = Vec::new();
10119        let mut new_selections = Vec::new();
10120
10121        while let Some(selection) = selections.next() {
10122            // Find all the selections that span a contiguous row range
10123            let (start_row, end_row) = consume_contiguous_rows(
10124                &mut contiguous_row_selections,
10125                selection,
10126                &display_map,
10127                &mut selections,
10128            );
10129
10130            // Move the text spanned by the row range to be after the last line of the row range
10131            if end_row.0 <= buffer.max_point().row {
10132                let range_to_move =
10133                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10134                let insertion_point = display_map
10135                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10136                    .0;
10137
10138                // Don't move lines across excerpt boundaries
10139                if buffer
10140                    .excerpt_containing(range_to_move.start..insertion_point)
10141                    .is_some()
10142                {
10143                    let mut text = String::from("\n");
10144                    text.extend(buffer.text_for_range(range_to_move.clone()));
10145                    text.pop(); // Drop trailing newline
10146                    edits.push((
10147                        buffer.anchor_after(range_to_move.start)
10148                            ..buffer.anchor_before(range_to_move.end),
10149                        String::new(),
10150                    ));
10151                    let insertion_anchor = buffer.anchor_after(insertion_point);
10152                    edits.push((insertion_anchor..insertion_anchor, text));
10153
10154                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10155
10156                    // Move selections down
10157                    new_selections.extend(contiguous_row_selections.drain(..).map(
10158                        |mut selection| {
10159                            selection.start.row += row_delta;
10160                            selection.end.row += row_delta;
10161                            selection
10162                        },
10163                    ));
10164
10165                    // Move folds down
10166                    unfold_ranges.push(range_to_move.clone());
10167                    for fold in display_map.folds_in_range(
10168                        buffer.anchor_before(range_to_move.start)
10169                            ..buffer.anchor_after(range_to_move.end),
10170                    ) {
10171                        let mut start = fold.range.start.to_point(&buffer);
10172                        let mut end = fold.range.end.to_point(&buffer);
10173                        start.row += row_delta;
10174                        end.row += row_delta;
10175                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10176                    }
10177                }
10178            }
10179
10180            // If we didn't move line(s), preserve the existing selections
10181            new_selections.append(&mut contiguous_row_selections);
10182        }
10183
10184        self.transact(window, cx, |this, window, cx| {
10185            this.unfold_ranges(&unfold_ranges, true, true, cx);
10186            this.buffer.update(cx, |buffer, cx| {
10187                for (range, text) in edits {
10188                    buffer.edit([(range, text)], None, cx);
10189                }
10190            });
10191            this.fold_creases(refold_creases, true, window, cx);
10192            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10193                s.select(new_selections)
10194            });
10195        });
10196    }
10197
10198    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10199        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10200        let text_layout_details = &self.text_layout_details(window);
10201        self.transact(window, cx, |this, window, cx| {
10202            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10203                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10204                s.move_with(|display_map, selection| {
10205                    if !selection.is_empty() {
10206                        return;
10207                    }
10208
10209                    let mut head = selection.head();
10210                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10211                    if head.column() == display_map.line_len(head.row()) {
10212                        transpose_offset = display_map
10213                            .buffer_snapshot
10214                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10215                    }
10216
10217                    if transpose_offset == 0 {
10218                        return;
10219                    }
10220
10221                    *head.column_mut() += 1;
10222                    head = display_map.clip_point(head, Bias::Right);
10223                    let goal = SelectionGoal::HorizontalPosition(
10224                        display_map
10225                            .x_for_display_point(head, text_layout_details)
10226                            .into(),
10227                    );
10228                    selection.collapse_to(head, goal);
10229
10230                    let transpose_start = display_map
10231                        .buffer_snapshot
10232                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10233                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10234                        let transpose_end = display_map
10235                            .buffer_snapshot
10236                            .clip_offset(transpose_offset + 1, Bias::Right);
10237                        if let Some(ch) =
10238                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10239                        {
10240                            edits.push((transpose_start..transpose_offset, String::new()));
10241                            edits.push((transpose_end..transpose_end, ch.to_string()));
10242                        }
10243                    }
10244                });
10245                edits
10246            });
10247            this.buffer
10248                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10249            let selections = this.selections.all::<usize>(cx);
10250            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10251                s.select(selections);
10252            });
10253        });
10254    }
10255
10256    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10257        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10258        self.rewrap_impl(RewrapOptions::default(), cx)
10259    }
10260
10261    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10262        let buffer = self.buffer.read(cx).snapshot(cx);
10263        let selections = self.selections.all::<Point>(cx);
10264        let mut selections = selections.iter().peekable();
10265
10266        let mut edits = Vec::new();
10267        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10268
10269        while let Some(selection) = selections.next() {
10270            let mut start_row = selection.start.row;
10271            let mut end_row = selection.end.row;
10272
10273            // Skip selections that overlap with a range that has already been rewrapped.
10274            let selection_range = start_row..end_row;
10275            if rewrapped_row_ranges
10276                .iter()
10277                .any(|range| range.overlaps(&selection_range))
10278            {
10279                continue;
10280            }
10281
10282            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10283
10284            // Since not all lines in the selection may be at the same indent
10285            // level, choose the indent size that is the most common between all
10286            // of the lines.
10287            //
10288            // If there is a tie, we use the deepest indent.
10289            let (indent_size, indent_end) = {
10290                let mut indent_size_occurrences = HashMap::default();
10291                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10292
10293                for row in start_row..=end_row {
10294                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10295                    rows_by_indent_size.entry(indent).or_default().push(row);
10296                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10297                }
10298
10299                let indent_size = indent_size_occurrences
10300                    .into_iter()
10301                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10302                    .map(|(indent, _)| indent)
10303                    .unwrap_or_default();
10304                let row = rows_by_indent_size[&indent_size][0];
10305                let indent_end = Point::new(row, indent_size.len);
10306
10307                (indent_size, indent_end)
10308            };
10309
10310            let mut line_prefix = indent_size.chars().collect::<String>();
10311
10312            let mut inside_comment = false;
10313            if let Some(comment_prefix) =
10314                buffer
10315                    .language_scope_at(selection.head())
10316                    .and_then(|language| {
10317                        language
10318                            .line_comment_prefixes()
10319                            .iter()
10320                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10321                            .cloned()
10322                    })
10323            {
10324                line_prefix.push_str(&comment_prefix);
10325                inside_comment = true;
10326            }
10327
10328            let language_settings = buffer.language_settings_at(selection.head(), cx);
10329            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10330                RewrapBehavior::InComments => inside_comment,
10331                RewrapBehavior::InSelections => !selection.is_empty(),
10332                RewrapBehavior::Anywhere => true,
10333            };
10334
10335            let should_rewrap = options.override_language_settings
10336                || allow_rewrap_based_on_language
10337                || self.hard_wrap.is_some();
10338            if !should_rewrap {
10339                continue;
10340            }
10341
10342            if selection.is_empty() {
10343                'expand_upwards: while start_row > 0 {
10344                    let prev_row = start_row - 1;
10345                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10346                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10347                    {
10348                        start_row = prev_row;
10349                    } else {
10350                        break 'expand_upwards;
10351                    }
10352                }
10353
10354                'expand_downwards: while end_row < buffer.max_point().row {
10355                    let next_row = end_row + 1;
10356                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10357                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10358                    {
10359                        end_row = next_row;
10360                    } else {
10361                        break 'expand_downwards;
10362                    }
10363                }
10364            }
10365
10366            let start = Point::new(start_row, 0);
10367            let start_offset = start.to_offset(&buffer);
10368            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10369            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10370            let Some(lines_without_prefixes) = selection_text
10371                .lines()
10372                .map(|line| {
10373                    line.strip_prefix(&line_prefix)
10374                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10375                        .ok_or_else(|| {
10376                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10377                        })
10378                })
10379                .collect::<Result<Vec<_>, _>>()
10380                .log_err()
10381            else {
10382                continue;
10383            };
10384
10385            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10386                buffer
10387                    .language_settings_at(Point::new(start_row, 0), cx)
10388                    .preferred_line_length as usize
10389            });
10390            let wrapped_text = wrap_with_prefix(
10391                line_prefix,
10392                lines_without_prefixes.join("\n"),
10393                wrap_column,
10394                tab_size,
10395                options.preserve_existing_whitespace,
10396            );
10397
10398            // TODO: should always use char-based diff while still supporting cursor behavior that
10399            // matches vim.
10400            let mut diff_options = DiffOptions::default();
10401            if options.override_language_settings {
10402                diff_options.max_word_diff_len = 0;
10403                diff_options.max_word_diff_line_count = 0;
10404            } else {
10405                diff_options.max_word_diff_len = usize::MAX;
10406                diff_options.max_word_diff_line_count = usize::MAX;
10407            }
10408
10409            for (old_range, new_text) in
10410                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10411            {
10412                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10413                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10414                edits.push((edit_start..edit_end, new_text));
10415            }
10416
10417            rewrapped_row_ranges.push(start_row..=end_row);
10418        }
10419
10420        self.buffer
10421            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10422    }
10423
10424    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10425        let mut text = String::new();
10426        let buffer = self.buffer.read(cx).snapshot(cx);
10427        let mut selections = self.selections.all::<Point>(cx);
10428        let mut clipboard_selections = Vec::with_capacity(selections.len());
10429        {
10430            let max_point = buffer.max_point();
10431            let mut is_first = true;
10432            for selection in &mut selections {
10433                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10434                if is_entire_line {
10435                    selection.start = Point::new(selection.start.row, 0);
10436                    if !selection.is_empty() && selection.end.column == 0 {
10437                        selection.end = cmp::min(max_point, selection.end);
10438                    } else {
10439                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10440                    }
10441                    selection.goal = SelectionGoal::None;
10442                }
10443                if is_first {
10444                    is_first = false;
10445                } else {
10446                    text += "\n";
10447                }
10448                let mut len = 0;
10449                for chunk in buffer.text_for_range(selection.start..selection.end) {
10450                    text.push_str(chunk);
10451                    len += chunk.len();
10452                }
10453                clipboard_selections.push(ClipboardSelection {
10454                    len,
10455                    is_entire_line,
10456                    first_line_indent: buffer
10457                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10458                        .len,
10459                });
10460            }
10461        }
10462
10463        self.transact(window, cx, |this, window, cx| {
10464            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10465                s.select(selections);
10466            });
10467            this.insert("", window, cx);
10468        });
10469        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10470    }
10471
10472    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10473        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10474        let item = self.cut_common(window, cx);
10475        cx.write_to_clipboard(item);
10476    }
10477
10478    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10479        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10480        self.change_selections(None, window, cx, |s| {
10481            s.move_with(|snapshot, sel| {
10482                if sel.is_empty() {
10483                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10484                }
10485            });
10486        });
10487        let item = self.cut_common(window, cx);
10488        cx.set_global(KillRing(item))
10489    }
10490
10491    pub fn kill_ring_yank(
10492        &mut self,
10493        _: &KillRingYank,
10494        window: &mut Window,
10495        cx: &mut Context<Self>,
10496    ) {
10497        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10498        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10499            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10500                (kill_ring.text().to_string(), kill_ring.metadata_json())
10501            } else {
10502                return;
10503            }
10504        } else {
10505            return;
10506        };
10507        self.do_paste(&text, metadata, false, window, cx);
10508    }
10509
10510    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10511        self.do_copy(true, cx);
10512    }
10513
10514    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10515        self.do_copy(false, cx);
10516    }
10517
10518    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10519        let selections = self.selections.all::<Point>(cx);
10520        let buffer = self.buffer.read(cx).read(cx);
10521        let mut text = String::new();
10522
10523        let mut clipboard_selections = Vec::with_capacity(selections.len());
10524        {
10525            let max_point = buffer.max_point();
10526            let mut is_first = true;
10527            for selection in &selections {
10528                let mut start = selection.start;
10529                let mut end = selection.end;
10530                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10531                if is_entire_line {
10532                    start = Point::new(start.row, 0);
10533                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10534                }
10535
10536                let mut trimmed_selections = Vec::new();
10537                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10538                    let row = MultiBufferRow(start.row);
10539                    let first_indent = buffer.indent_size_for_line(row);
10540                    if first_indent.len == 0 || start.column > first_indent.len {
10541                        trimmed_selections.push(start..end);
10542                    } else {
10543                        trimmed_selections.push(
10544                            Point::new(row.0, first_indent.len)
10545                                ..Point::new(row.0, buffer.line_len(row)),
10546                        );
10547                        for row in start.row + 1..=end.row {
10548                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10549                            if row == end.row {
10550                                line_len = end.column;
10551                            }
10552                            if line_len == 0 {
10553                                trimmed_selections
10554                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10555                                continue;
10556                            }
10557                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10558                            if row_indent_size.len >= first_indent.len {
10559                                trimmed_selections.push(
10560                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10561                                );
10562                            } else {
10563                                trimmed_selections.clear();
10564                                trimmed_selections.push(start..end);
10565                                break;
10566                            }
10567                        }
10568                    }
10569                } else {
10570                    trimmed_selections.push(start..end);
10571                }
10572
10573                for trimmed_range in trimmed_selections {
10574                    if is_first {
10575                        is_first = false;
10576                    } else {
10577                        text += "\n";
10578                    }
10579                    let mut len = 0;
10580                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10581                        text.push_str(chunk);
10582                        len += chunk.len();
10583                    }
10584                    clipboard_selections.push(ClipboardSelection {
10585                        len,
10586                        is_entire_line,
10587                        first_line_indent: buffer
10588                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10589                            .len,
10590                    });
10591                }
10592            }
10593        }
10594
10595        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10596            text,
10597            clipboard_selections,
10598        ));
10599    }
10600
10601    pub fn do_paste(
10602        &mut self,
10603        text: &String,
10604        clipboard_selections: Option<Vec<ClipboardSelection>>,
10605        handle_entire_lines: bool,
10606        window: &mut Window,
10607        cx: &mut Context<Self>,
10608    ) {
10609        if self.read_only(cx) {
10610            return;
10611        }
10612
10613        let clipboard_text = Cow::Borrowed(text);
10614
10615        self.transact(window, cx, |this, window, cx| {
10616            if let Some(mut clipboard_selections) = clipboard_selections {
10617                let old_selections = this.selections.all::<usize>(cx);
10618                let all_selections_were_entire_line =
10619                    clipboard_selections.iter().all(|s| s.is_entire_line);
10620                let first_selection_indent_column =
10621                    clipboard_selections.first().map(|s| s.first_line_indent);
10622                if clipboard_selections.len() != old_selections.len() {
10623                    clipboard_selections.drain(..);
10624                }
10625                let cursor_offset = this.selections.last::<usize>(cx).head();
10626                let mut auto_indent_on_paste = true;
10627
10628                this.buffer.update(cx, |buffer, cx| {
10629                    let snapshot = buffer.read(cx);
10630                    auto_indent_on_paste = snapshot
10631                        .language_settings_at(cursor_offset, cx)
10632                        .auto_indent_on_paste;
10633
10634                    let mut start_offset = 0;
10635                    let mut edits = Vec::new();
10636                    let mut original_indent_columns = Vec::new();
10637                    for (ix, selection) in old_selections.iter().enumerate() {
10638                        let to_insert;
10639                        let entire_line;
10640                        let original_indent_column;
10641                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10642                            let end_offset = start_offset + clipboard_selection.len;
10643                            to_insert = &clipboard_text[start_offset..end_offset];
10644                            entire_line = clipboard_selection.is_entire_line;
10645                            start_offset = end_offset + 1;
10646                            original_indent_column = Some(clipboard_selection.first_line_indent);
10647                        } else {
10648                            to_insert = clipboard_text.as_str();
10649                            entire_line = all_selections_were_entire_line;
10650                            original_indent_column = first_selection_indent_column
10651                        }
10652
10653                        // If the corresponding selection was empty when this slice of the
10654                        // clipboard text was written, then the entire line containing the
10655                        // selection was copied. If this selection is also currently empty,
10656                        // then paste the line before the current line of the buffer.
10657                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10658                            let column = selection.start.to_point(&snapshot).column as usize;
10659                            let line_start = selection.start - column;
10660                            line_start..line_start
10661                        } else {
10662                            selection.range()
10663                        };
10664
10665                        edits.push((range, to_insert));
10666                        original_indent_columns.push(original_indent_column);
10667                    }
10668                    drop(snapshot);
10669
10670                    buffer.edit(
10671                        edits,
10672                        if auto_indent_on_paste {
10673                            Some(AutoindentMode::Block {
10674                                original_indent_columns,
10675                            })
10676                        } else {
10677                            None
10678                        },
10679                        cx,
10680                    );
10681                });
10682
10683                let selections = this.selections.all::<usize>(cx);
10684                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10685                    s.select(selections)
10686                });
10687            } else {
10688                this.insert(&clipboard_text, window, cx);
10689            }
10690        });
10691    }
10692
10693    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10694        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10695        if let Some(item) = cx.read_from_clipboard() {
10696            let entries = item.entries();
10697
10698            match entries.first() {
10699                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10700                // of all the pasted entries.
10701                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10702                    .do_paste(
10703                        clipboard_string.text(),
10704                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10705                        true,
10706                        window,
10707                        cx,
10708                    ),
10709                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10710            }
10711        }
10712    }
10713
10714    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10715        if self.read_only(cx) {
10716            return;
10717        }
10718
10719        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10720
10721        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10722            if let Some((selections, _)) =
10723                self.selection_history.transaction(transaction_id).cloned()
10724            {
10725                self.change_selections(None, window, cx, |s| {
10726                    s.select_anchors(selections.to_vec());
10727                });
10728            } else {
10729                log::error!(
10730                    "No entry in selection_history found for undo. \
10731                     This may correspond to a bug where undo does not update the selection. \
10732                     If this is occurring, please add details to \
10733                     https://github.com/zed-industries/zed/issues/22692"
10734                );
10735            }
10736            self.request_autoscroll(Autoscroll::fit(), cx);
10737            self.unmark_text(window, cx);
10738            self.refresh_inline_completion(true, false, window, cx);
10739            cx.emit(EditorEvent::Edited { transaction_id });
10740            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10741        }
10742    }
10743
10744    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10745        if self.read_only(cx) {
10746            return;
10747        }
10748
10749        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10750
10751        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10752            if let Some((_, Some(selections))) =
10753                self.selection_history.transaction(transaction_id).cloned()
10754            {
10755                self.change_selections(None, window, cx, |s| {
10756                    s.select_anchors(selections.to_vec());
10757                });
10758            } else {
10759                log::error!(
10760                    "No entry in selection_history found for redo. \
10761                     This may correspond to a bug where undo does not update the selection. \
10762                     If this is occurring, please add details to \
10763                     https://github.com/zed-industries/zed/issues/22692"
10764                );
10765            }
10766            self.request_autoscroll(Autoscroll::fit(), cx);
10767            self.unmark_text(window, cx);
10768            self.refresh_inline_completion(true, false, window, cx);
10769            cx.emit(EditorEvent::Edited { transaction_id });
10770        }
10771    }
10772
10773    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10774        self.buffer
10775            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10776    }
10777
10778    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10779        self.buffer
10780            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10781    }
10782
10783    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10784        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10785        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10786            s.move_with(|map, selection| {
10787                let cursor = if selection.is_empty() {
10788                    movement::left(map, selection.start)
10789                } else {
10790                    selection.start
10791                };
10792                selection.collapse_to(cursor, SelectionGoal::None);
10793            });
10794        })
10795    }
10796
10797    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10798        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10799        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10800            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10801        })
10802    }
10803
10804    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10805        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10807            s.move_with(|map, selection| {
10808                let cursor = if selection.is_empty() {
10809                    movement::right(map, selection.end)
10810                } else {
10811                    selection.end
10812                };
10813                selection.collapse_to(cursor, SelectionGoal::None)
10814            });
10815        })
10816    }
10817
10818    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10819        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10820        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10821            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10822        })
10823    }
10824
10825    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10826        if self.take_rename(true, window, cx).is_some() {
10827            return;
10828        }
10829
10830        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10831            cx.propagate();
10832            return;
10833        }
10834
10835        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10836
10837        let text_layout_details = &self.text_layout_details(window);
10838        let selection_count = self.selections.count();
10839        let first_selection = self.selections.first_anchor();
10840
10841        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10842            s.move_with(|map, selection| {
10843                if !selection.is_empty() {
10844                    selection.goal = SelectionGoal::None;
10845                }
10846                let (cursor, goal) = movement::up(
10847                    map,
10848                    selection.start,
10849                    selection.goal,
10850                    false,
10851                    text_layout_details,
10852                );
10853                selection.collapse_to(cursor, goal);
10854            });
10855        });
10856
10857        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10858        {
10859            cx.propagate();
10860        }
10861    }
10862
10863    pub fn move_up_by_lines(
10864        &mut self,
10865        action: &MoveUpByLines,
10866        window: &mut Window,
10867        cx: &mut Context<Self>,
10868    ) {
10869        if self.take_rename(true, window, cx).is_some() {
10870            return;
10871        }
10872
10873        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10874            cx.propagate();
10875            return;
10876        }
10877
10878        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10879
10880        let text_layout_details = &self.text_layout_details(window);
10881
10882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883            s.move_with(|map, selection| {
10884                if !selection.is_empty() {
10885                    selection.goal = SelectionGoal::None;
10886                }
10887                let (cursor, goal) = movement::up_by_rows(
10888                    map,
10889                    selection.start,
10890                    action.lines,
10891                    selection.goal,
10892                    false,
10893                    text_layout_details,
10894                );
10895                selection.collapse_to(cursor, goal);
10896            });
10897        })
10898    }
10899
10900    pub fn move_down_by_lines(
10901        &mut self,
10902        action: &MoveDownByLines,
10903        window: &mut Window,
10904        cx: &mut Context<Self>,
10905    ) {
10906        if self.take_rename(true, window, cx).is_some() {
10907            return;
10908        }
10909
10910        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10911            cx.propagate();
10912            return;
10913        }
10914
10915        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10916
10917        let text_layout_details = &self.text_layout_details(window);
10918
10919        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10920            s.move_with(|map, selection| {
10921                if !selection.is_empty() {
10922                    selection.goal = SelectionGoal::None;
10923                }
10924                let (cursor, goal) = movement::down_by_rows(
10925                    map,
10926                    selection.start,
10927                    action.lines,
10928                    selection.goal,
10929                    false,
10930                    text_layout_details,
10931                );
10932                selection.collapse_to(cursor, goal);
10933            });
10934        })
10935    }
10936
10937    pub fn select_down_by_lines(
10938        &mut self,
10939        action: &SelectDownByLines,
10940        window: &mut Window,
10941        cx: &mut Context<Self>,
10942    ) {
10943        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10944        let text_layout_details = &self.text_layout_details(window);
10945        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10946            s.move_heads_with(|map, head, goal| {
10947                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10948            })
10949        })
10950    }
10951
10952    pub fn select_up_by_lines(
10953        &mut self,
10954        action: &SelectUpByLines,
10955        window: &mut Window,
10956        cx: &mut Context<Self>,
10957    ) {
10958        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10959        let text_layout_details = &self.text_layout_details(window);
10960        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10961            s.move_heads_with(|map, head, goal| {
10962                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10963            })
10964        })
10965    }
10966
10967    pub fn select_page_up(
10968        &mut self,
10969        _: &SelectPageUp,
10970        window: &mut Window,
10971        cx: &mut Context<Self>,
10972    ) {
10973        let Some(row_count) = self.visible_row_count() else {
10974            return;
10975        };
10976
10977        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10978
10979        let text_layout_details = &self.text_layout_details(window);
10980
10981        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10982            s.move_heads_with(|map, head, goal| {
10983                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10984            })
10985        })
10986    }
10987
10988    pub fn move_page_up(
10989        &mut self,
10990        action: &MovePageUp,
10991        window: &mut Window,
10992        cx: &mut Context<Self>,
10993    ) {
10994        if self.take_rename(true, window, cx).is_some() {
10995            return;
10996        }
10997
10998        if self
10999            .context_menu
11000            .borrow_mut()
11001            .as_mut()
11002            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11003            .unwrap_or(false)
11004        {
11005            return;
11006        }
11007
11008        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11009            cx.propagate();
11010            return;
11011        }
11012
11013        let Some(row_count) = self.visible_row_count() else {
11014            return;
11015        };
11016
11017        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11018
11019        let autoscroll = if action.center_cursor {
11020            Autoscroll::center()
11021        } else {
11022            Autoscroll::fit()
11023        };
11024
11025        let text_layout_details = &self.text_layout_details(window);
11026
11027        self.change_selections(Some(autoscroll), window, cx, |s| {
11028            s.move_with(|map, selection| {
11029                if !selection.is_empty() {
11030                    selection.goal = SelectionGoal::None;
11031                }
11032                let (cursor, goal) = movement::up_by_rows(
11033                    map,
11034                    selection.end,
11035                    row_count,
11036                    selection.goal,
11037                    false,
11038                    text_layout_details,
11039                );
11040                selection.collapse_to(cursor, goal);
11041            });
11042        });
11043    }
11044
11045    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11046        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11047        let text_layout_details = &self.text_layout_details(window);
11048        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11049            s.move_heads_with(|map, head, goal| {
11050                movement::up(map, head, goal, false, text_layout_details)
11051            })
11052        })
11053    }
11054
11055    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11056        self.take_rename(true, window, cx);
11057
11058        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11059            cx.propagate();
11060            return;
11061        }
11062
11063        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11064
11065        let text_layout_details = &self.text_layout_details(window);
11066        let selection_count = self.selections.count();
11067        let first_selection = self.selections.first_anchor();
11068
11069        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11070            s.move_with(|map, selection| {
11071                if !selection.is_empty() {
11072                    selection.goal = SelectionGoal::None;
11073                }
11074                let (cursor, goal) = movement::down(
11075                    map,
11076                    selection.end,
11077                    selection.goal,
11078                    false,
11079                    text_layout_details,
11080                );
11081                selection.collapse_to(cursor, goal);
11082            });
11083        });
11084
11085        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11086        {
11087            cx.propagate();
11088        }
11089    }
11090
11091    pub fn select_page_down(
11092        &mut self,
11093        _: &SelectPageDown,
11094        window: &mut Window,
11095        cx: &mut Context<Self>,
11096    ) {
11097        let Some(row_count) = self.visible_row_count() else {
11098            return;
11099        };
11100
11101        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11102
11103        let text_layout_details = &self.text_layout_details(window);
11104
11105        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11106            s.move_heads_with(|map, head, goal| {
11107                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11108            })
11109        })
11110    }
11111
11112    pub fn move_page_down(
11113        &mut self,
11114        action: &MovePageDown,
11115        window: &mut Window,
11116        cx: &mut Context<Self>,
11117    ) {
11118        if self.take_rename(true, window, cx).is_some() {
11119            return;
11120        }
11121
11122        if self
11123            .context_menu
11124            .borrow_mut()
11125            .as_mut()
11126            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11127            .unwrap_or(false)
11128        {
11129            return;
11130        }
11131
11132        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11133            cx.propagate();
11134            return;
11135        }
11136
11137        let Some(row_count) = self.visible_row_count() else {
11138            return;
11139        };
11140
11141        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11142
11143        let autoscroll = if action.center_cursor {
11144            Autoscroll::center()
11145        } else {
11146            Autoscroll::fit()
11147        };
11148
11149        let text_layout_details = &self.text_layout_details(window);
11150        self.change_selections(Some(autoscroll), window, cx, |s| {
11151            s.move_with(|map, selection| {
11152                if !selection.is_empty() {
11153                    selection.goal = SelectionGoal::None;
11154                }
11155                let (cursor, goal) = movement::down_by_rows(
11156                    map,
11157                    selection.end,
11158                    row_count,
11159                    selection.goal,
11160                    false,
11161                    text_layout_details,
11162                );
11163                selection.collapse_to(cursor, goal);
11164            });
11165        });
11166    }
11167
11168    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11169        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11170        let text_layout_details = &self.text_layout_details(window);
11171        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11172            s.move_heads_with(|map, head, goal| {
11173                movement::down(map, head, goal, false, text_layout_details)
11174            })
11175        });
11176    }
11177
11178    pub fn context_menu_first(
11179        &mut self,
11180        _: &ContextMenuFirst,
11181        _window: &mut Window,
11182        cx: &mut Context<Self>,
11183    ) {
11184        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11185            context_menu.select_first(self.completion_provider.as_deref(), cx);
11186        }
11187    }
11188
11189    pub fn context_menu_prev(
11190        &mut self,
11191        _: &ContextMenuPrevious,
11192        _window: &mut Window,
11193        cx: &mut Context<Self>,
11194    ) {
11195        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11196            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11197        }
11198    }
11199
11200    pub fn context_menu_next(
11201        &mut self,
11202        _: &ContextMenuNext,
11203        _window: &mut Window,
11204        cx: &mut Context<Self>,
11205    ) {
11206        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11207            context_menu.select_next(self.completion_provider.as_deref(), cx);
11208        }
11209    }
11210
11211    pub fn context_menu_last(
11212        &mut self,
11213        _: &ContextMenuLast,
11214        _window: &mut Window,
11215        cx: &mut Context<Self>,
11216    ) {
11217        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11218            context_menu.select_last(self.completion_provider.as_deref(), cx);
11219        }
11220    }
11221
11222    pub fn move_to_previous_word_start(
11223        &mut self,
11224        _: &MoveToPreviousWordStart,
11225        window: &mut Window,
11226        cx: &mut Context<Self>,
11227    ) {
11228        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11229        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11230            s.move_cursors_with(|map, head, _| {
11231                (
11232                    movement::previous_word_start(map, head),
11233                    SelectionGoal::None,
11234                )
11235            });
11236        })
11237    }
11238
11239    pub fn move_to_previous_subword_start(
11240        &mut self,
11241        _: &MoveToPreviousSubwordStart,
11242        window: &mut Window,
11243        cx: &mut Context<Self>,
11244    ) {
11245        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11246        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247            s.move_cursors_with(|map, head, _| {
11248                (
11249                    movement::previous_subword_start(map, head),
11250                    SelectionGoal::None,
11251                )
11252            });
11253        })
11254    }
11255
11256    pub fn select_to_previous_word_start(
11257        &mut self,
11258        _: &SelectToPreviousWordStart,
11259        window: &mut Window,
11260        cx: &mut Context<Self>,
11261    ) {
11262        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11264            s.move_heads_with(|map, head, _| {
11265                (
11266                    movement::previous_word_start(map, head),
11267                    SelectionGoal::None,
11268                )
11269            });
11270        })
11271    }
11272
11273    pub fn select_to_previous_subword_start(
11274        &mut self,
11275        _: &SelectToPreviousSubwordStart,
11276        window: &mut Window,
11277        cx: &mut Context<Self>,
11278    ) {
11279        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11280        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11281            s.move_heads_with(|map, head, _| {
11282                (
11283                    movement::previous_subword_start(map, head),
11284                    SelectionGoal::None,
11285                )
11286            });
11287        })
11288    }
11289
11290    pub fn delete_to_previous_word_start(
11291        &mut self,
11292        action: &DeleteToPreviousWordStart,
11293        window: &mut Window,
11294        cx: &mut Context<Self>,
11295    ) {
11296        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11297        self.transact(window, cx, |this, window, cx| {
11298            this.select_autoclose_pair(window, cx);
11299            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11300                s.move_with(|map, selection| {
11301                    if selection.is_empty() {
11302                        let cursor = if action.ignore_newlines {
11303                            movement::previous_word_start(map, selection.head())
11304                        } else {
11305                            movement::previous_word_start_or_newline(map, selection.head())
11306                        };
11307                        selection.set_head(cursor, SelectionGoal::None);
11308                    }
11309                });
11310            });
11311            this.insert("", window, cx);
11312        });
11313    }
11314
11315    pub fn delete_to_previous_subword_start(
11316        &mut self,
11317        _: &DeleteToPreviousSubwordStart,
11318        window: &mut Window,
11319        cx: &mut Context<Self>,
11320    ) {
11321        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11322        self.transact(window, cx, |this, window, cx| {
11323            this.select_autoclose_pair(window, cx);
11324            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11325                s.move_with(|map, selection| {
11326                    if selection.is_empty() {
11327                        let cursor = movement::previous_subword_start(map, selection.head());
11328                        selection.set_head(cursor, SelectionGoal::None);
11329                    }
11330                });
11331            });
11332            this.insert("", window, cx);
11333        });
11334    }
11335
11336    pub fn move_to_next_word_end(
11337        &mut self,
11338        _: &MoveToNextWordEnd,
11339        window: &mut Window,
11340        cx: &mut Context<Self>,
11341    ) {
11342        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11343        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11344            s.move_cursors_with(|map, head, _| {
11345                (movement::next_word_end(map, head), SelectionGoal::None)
11346            });
11347        })
11348    }
11349
11350    pub fn move_to_next_subword_end(
11351        &mut self,
11352        _: &MoveToNextSubwordEnd,
11353        window: &mut Window,
11354        cx: &mut Context<Self>,
11355    ) {
11356        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11357        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11358            s.move_cursors_with(|map, head, _| {
11359                (movement::next_subword_end(map, head), SelectionGoal::None)
11360            });
11361        })
11362    }
11363
11364    pub fn select_to_next_word_end(
11365        &mut self,
11366        _: &SelectToNextWordEnd,
11367        window: &mut Window,
11368        cx: &mut Context<Self>,
11369    ) {
11370        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11372            s.move_heads_with(|map, head, _| {
11373                (movement::next_word_end(map, head), SelectionGoal::None)
11374            });
11375        })
11376    }
11377
11378    pub fn select_to_next_subword_end(
11379        &mut self,
11380        _: &SelectToNextSubwordEnd,
11381        window: &mut Window,
11382        cx: &mut Context<Self>,
11383    ) {
11384        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11385        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11386            s.move_heads_with(|map, head, _| {
11387                (movement::next_subword_end(map, head), SelectionGoal::None)
11388            });
11389        })
11390    }
11391
11392    pub fn delete_to_next_word_end(
11393        &mut self,
11394        action: &DeleteToNextWordEnd,
11395        window: &mut Window,
11396        cx: &mut Context<Self>,
11397    ) {
11398        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11399        self.transact(window, cx, |this, window, cx| {
11400            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11401                s.move_with(|map, selection| {
11402                    if selection.is_empty() {
11403                        let cursor = if action.ignore_newlines {
11404                            movement::next_word_end(map, selection.head())
11405                        } else {
11406                            movement::next_word_end_or_newline(map, selection.head())
11407                        };
11408                        selection.set_head(cursor, SelectionGoal::None);
11409                    }
11410                });
11411            });
11412            this.insert("", window, cx);
11413        });
11414    }
11415
11416    pub fn delete_to_next_subword_end(
11417        &mut self,
11418        _: &DeleteToNextSubwordEnd,
11419        window: &mut Window,
11420        cx: &mut Context<Self>,
11421    ) {
11422        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11423        self.transact(window, cx, |this, window, cx| {
11424            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11425                s.move_with(|map, selection| {
11426                    if selection.is_empty() {
11427                        let cursor = movement::next_subword_end(map, selection.head());
11428                        selection.set_head(cursor, SelectionGoal::None);
11429                    }
11430                });
11431            });
11432            this.insert("", window, cx);
11433        });
11434    }
11435
11436    pub fn move_to_beginning_of_line(
11437        &mut self,
11438        action: &MoveToBeginningOfLine,
11439        window: &mut Window,
11440        cx: &mut Context<Self>,
11441    ) {
11442        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11443        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11444            s.move_cursors_with(|map, head, _| {
11445                (
11446                    movement::indented_line_beginning(
11447                        map,
11448                        head,
11449                        action.stop_at_soft_wraps,
11450                        action.stop_at_indent,
11451                    ),
11452                    SelectionGoal::None,
11453                )
11454            });
11455        })
11456    }
11457
11458    pub fn select_to_beginning_of_line(
11459        &mut self,
11460        action: &SelectToBeginningOfLine,
11461        window: &mut Window,
11462        cx: &mut Context<Self>,
11463    ) {
11464        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11465        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11466            s.move_heads_with(|map, head, _| {
11467                (
11468                    movement::indented_line_beginning(
11469                        map,
11470                        head,
11471                        action.stop_at_soft_wraps,
11472                        action.stop_at_indent,
11473                    ),
11474                    SelectionGoal::None,
11475                )
11476            });
11477        });
11478    }
11479
11480    pub fn delete_to_beginning_of_line(
11481        &mut self,
11482        action: &DeleteToBeginningOfLine,
11483        window: &mut Window,
11484        cx: &mut Context<Self>,
11485    ) {
11486        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11487        self.transact(window, cx, |this, window, cx| {
11488            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11489                s.move_with(|_, selection| {
11490                    selection.reversed = true;
11491                });
11492            });
11493
11494            this.select_to_beginning_of_line(
11495                &SelectToBeginningOfLine {
11496                    stop_at_soft_wraps: false,
11497                    stop_at_indent: action.stop_at_indent,
11498                },
11499                window,
11500                cx,
11501            );
11502            this.backspace(&Backspace, window, cx);
11503        });
11504    }
11505
11506    pub fn move_to_end_of_line(
11507        &mut self,
11508        action: &MoveToEndOfLine,
11509        window: &mut Window,
11510        cx: &mut Context<Self>,
11511    ) {
11512        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11513        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11514            s.move_cursors_with(|map, head, _| {
11515                (
11516                    movement::line_end(map, head, action.stop_at_soft_wraps),
11517                    SelectionGoal::None,
11518                )
11519            });
11520        })
11521    }
11522
11523    pub fn select_to_end_of_line(
11524        &mut self,
11525        action: &SelectToEndOfLine,
11526        window: &mut Window,
11527        cx: &mut Context<Self>,
11528    ) {
11529        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11530        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531            s.move_heads_with(|map, head, _| {
11532                (
11533                    movement::line_end(map, head, action.stop_at_soft_wraps),
11534                    SelectionGoal::None,
11535                )
11536            });
11537        })
11538    }
11539
11540    pub fn delete_to_end_of_line(
11541        &mut self,
11542        _: &DeleteToEndOfLine,
11543        window: &mut Window,
11544        cx: &mut Context<Self>,
11545    ) {
11546        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11547        self.transact(window, cx, |this, window, cx| {
11548            this.select_to_end_of_line(
11549                &SelectToEndOfLine {
11550                    stop_at_soft_wraps: false,
11551                },
11552                window,
11553                cx,
11554            );
11555            this.delete(&Delete, window, cx);
11556        });
11557    }
11558
11559    pub fn cut_to_end_of_line(
11560        &mut self,
11561        _: &CutToEndOfLine,
11562        window: &mut Window,
11563        cx: &mut Context<Self>,
11564    ) {
11565        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11566        self.transact(window, cx, |this, window, cx| {
11567            this.select_to_end_of_line(
11568                &SelectToEndOfLine {
11569                    stop_at_soft_wraps: false,
11570                },
11571                window,
11572                cx,
11573            );
11574            this.cut(&Cut, window, cx);
11575        });
11576    }
11577
11578    pub fn move_to_start_of_paragraph(
11579        &mut self,
11580        _: &MoveToStartOfParagraph,
11581        window: &mut Window,
11582        cx: &mut Context<Self>,
11583    ) {
11584        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11585            cx.propagate();
11586            return;
11587        }
11588        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11590            s.move_with(|map, selection| {
11591                selection.collapse_to(
11592                    movement::start_of_paragraph(map, selection.head(), 1),
11593                    SelectionGoal::None,
11594                )
11595            });
11596        })
11597    }
11598
11599    pub fn move_to_end_of_paragraph(
11600        &mut self,
11601        _: &MoveToEndOfParagraph,
11602        window: &mut Window,
11603        cx: &mut Context<Self>,
11604    ) {
11605        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11606            cx.propagate();
11607            return;
11608        }
11609        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11610        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11611            s.move_with(|map, selection| {
11612                selection.collapse_to(
11613                    movement::end_of_paragraph(map, selection.head(), 1),
11614                    SelectionGoal::None,
11615                )
11616            });
11617        })
11618    }
11619
11620    pub fn select_to_start_of_paragraph(
11621        &mut self,
11622        _: &SelectToStartOfParagraph,
11623        window: &mut Window,
11624        cx: &mut Context<Self>,
11625    ) {
11626        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11627            cx.propagate();
11628            return;
11629        }
11630        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11632            s.move_heads_with(|map, head, _| {
11633                (
11634                    movement::start_of_paragraph(map, head, 1),
11635                    SelectionGoal::None,
11636                )
11637            });
11638        })
11639    }
11640
11641    pub fn select_to_end_of_paragraph(
11642        &mut self,
11643        _: &SelectToEndOfParagraph,
11644        window: &mut Window,
11645        cx: &mut Context<Self>,
11646    ) {
11647        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11648            cx.propagate();
11649            return;
11650        }
11651        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11652        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11653            s.move_heads_with(|map, head, _| {
11654                (
11655                    movement::end_of_paragraph(map, head, 1),
11656                    SelectionGoal::None,
11657                )
11658            });
11659        })
11660    }
11661
11662    pub fn move_to_start_of_excerpt(
11663        &mut self,
11664        _: &MoveToStartOfExcerpt,
11665        window: &mut Window,
11666        cx: &mut Context<Self>,
11667    ) {
11668        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11669            cx.propagate();
11670            return;
11671        }
11672        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11673        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11674            s.move_with(|map, selection| {
11675                selection.collapse_to(
11676                    movement::start_of_excerpt(
11677                        map,
11678                        selection.head(),
11679                        workspace::searchable::Direction::Prev,
11680                    ),
11681                    SelectionGoal::None,
11682                )
11683            });
11684        })
11685    }
11686
11687    pub fn move_to_start_of_next_excerpt(
11688        &mut self,
11689        _: &MoveToStartOfNextExcerpt,
11690        window: &mut Window,
11691        cx: &mut Context<Self>,
11692    ) {
11693        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11694            cx.propagate();
11695            return;
11696        }
11697
11698        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11699            s.move_with(|map, selection| {
11700                selection.collapse_to(
11701                    movement::start_of_excerpt(
11702                        map,
11703                        selection.head(),
11704                        workspace::searchable::Direction::Next,
11705                    ),
11706                    SelectionGoal::None,
11707                )
11708            });
11709        })
11710    }
11711
11712    pub fn move_to_end_of_excerpt(
11713        &mut self,
11714        _: &MoveToEndOfExcerpt,
11715        window: &mut Window,
11716        cx: &mut Context<Self>,
11717    ) {
11718        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11719            cx.propagate();
11720            return;
11721        }
11722        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11723        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11724            s.move_with(|map, selection| {
11725                selection.collapse_to(
11726                    movement::end_of_excerpt(
11727                        map,
11728                        selection.head(),
11729                        workspace::searchable::Direction::Next,
11730                    ),
11731                    SelectionGoal::None,
11732                )
11733            });
11734        })
11735    }
11736
11737    pub fn move_to_end_of_previous_excerpt(
11738        &mut self,
11739        _: &MoveToEndOfPreviousExcerpt,
11740        window: &mut Window,
11741        cx: &mut Context<Self>,
11742    ) {
11743        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11744            cx.propagate();
11745            return;
11746        }
11747        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11749            s.move_with(|map, selection| {
11750                selection.collapse_to(
11751                    movement::end_of_excerpt(
11752                        map,
11753                        selection.head(),
11754                        workspace::searchable::Direction::Prev,
11755                    ),
11756                    SelectionGoal::None,
11757                )
11758            });
11759        })
11760    }
11761
11762    pub fn select_to_start_of_excerpt(
11763        &mut self,
11764        _: &SelectToStartOfExcerpt,
11765        window: &mut Window,
11766        cx: &mut Context<Self>,
11767    ) {
11768        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11769            cx.propagate();
11770            return;
11771        }
11772        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11774            s.move_heads_with(|map, head, _| {
11775                (
11776                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11777                    SelectionGoal::None,
11778                )
11779            });
11780        })
11781    }
11782
11783    pub fn select_to_start_of_next_excerpt(
11784        &mut self,
11785        _: &SelectToStartOfNextExcerpt,
11786        window: &mut Window,
11787        cx: &mut Context<Self>,
11788    ) {
11789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11790            cx.propagate();
11791            return;
11792        }
11793        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11795            s.move_heads_with(|map, head, _| {
11796                (
11797                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11798                    SelectionGoal::None,
11799                )
11800            });
11801        })
11802    }
11803
11804    pub fn select_to_end_of_excerpt(
11805        &mut self,
11806        _: &SelectToEndOfExcerpt,
11807        window: &mut Window,
11808        cx: &mut Context<Self>,
11809    ) {
11810        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11811            cx.propagate();
11812            return;
11813        }
11814        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11815        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11816            s.move_heads_with(|map, head, _| {
11817                (
11818                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11819                    SelectionGoal::None,
11820                )
11821            });
11822        })
11823    }
11824
11825    pub fn select_to_end_of_previous_excerpt(
11826        &mut self,
11827        _: &SelectToEndOfPreviousExcerpt,
11828        window: &mut Window,
11829        cx: &mut Context<Self>,
11830    ) {
11831        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11832            cx.propagate();
11833            return;
11834        }
11835        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11836        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11837            s.move_heads_with(|map, head, _| {
11838                (
11839                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11840                    SelectionGoal::None,
11841                )
11842            });
11843        })
11844    }
11845
11846    pub fn move_to_beginning(
11847        &mut self,
11848        _: &MoveToBeginning,
11849        window: &mut Window,
11850        cx: &mut Context<Self>,
11851    ) {
11852        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11853            cx.propagate();
11854            return;
11855        }
11856        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11857        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11858            s.select_ranges(vec![0..0]);
11859        });
11860    }
11861
11862    pub fn select_to_beginning(
11863        &mut self,
11864        _: &SelectToBeginning,
11865        window: &mut Window,
11866        cx: &mut Context<Self>,
11867    ) {
11868        let mut selection = self.selections.last::<Point>(cx);
11869        selection.set_head(Point::zero(), SelectionGoal::None);
11870        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11871        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11872            s.select(vec![selection]);
11873        });
11874    }
11875
11876    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11877        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11878            cx.propagate();
11879            return;
11880        }
11881        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11882        let cursor = self.buffer.read(cx).read(cx).len();
11883        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11884            s.select_ranges(vec![cursor..cursor])
11885        });
11886    }
11887
11888    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11889        self.nav_history = nav_history;
11890    }
11891
11892    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11893        self.nav_history.as_ref()
11894    }
11895
11896    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11897        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11898    }
11899
11900    fn push_to_nav_history(
11901        &mut self,
11902        cursor_anchor: Anchor,
11903        new_position: Option<Point>,
11904        is_deactivate: bool,
11905        cx: &mut Context<Self>,
11906    ) {
11907        if let Some(nav_history) = self.nav_history.as_mut() {
11908            let buffer = self.buffer.read(cx).read(cx);
11909            let cursor_position = cursor_anchor.to_point(&buffer);
11910            let scroll_state = self.scroll_manager.anchor();
11911            let scroll_top_row = scroll_state.top_row(&buffer);
11912            drop(buffer);
11913
11914            if let Some(new_position) = new_position {
11915                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11916                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11917                    return;
11918                }
11919            }
11920
11921            nav_history.push(
11922                Some(NavigationData {
11923                    cursor_anchor,
11924                    cursor_position,
11925                    scroll_anchor: scroll_state,
11926                    scroll_top_row,
11927                }),
11928                cx,
11929            );
11930            cx.emit(EditorEvent::PushedToNavHistory {
11931                anchor: cursor_anchor,
11932                is_deactivate,
11933            })
11934        }
11935    }
11936
11937    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11938        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11939        let buffer = self.buffer.read(cx).snapshot(cx);
11940        let mut selection = self.selections.first::<usize>(cx);
11941        selection.set_head(buffer.len(), SelectionGoal::None);
11942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11943            s.select(vec![selection]);
11944        });
11945    }
11946
11947    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11948        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11949        let end = self.buffer.read(cx).read(cx).len();
11950        self.change_selections(None, window, cx, |s| {
11951            s.select_ranges(vec![0..end]);
11952        });
11953    }
11954
11955    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11956        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11957        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11958        let mut selections = self.selections.all::<Point>(cx);
11959        let max_point = display_map.buffer_snapshot.max_point();
11960        for selection in &mut selections {
11961            let rows = selection.spanned_rows(true, &display_map);
11962            selection.start = Point::new(rows.start.0, 0);
11963            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11964            selection.reversed = false;
11965        }
11966        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11967            s.select(selections);
11968        });
11969    }
11970
11971    pub fn split_selection_into_lines(
11972        &mut self,
11973        _: &SplitSelectionIntoLines,
11974        window: &mut Window,
11975        cx: &mut Context<Self>,
11976    ) {
11977        let selections = self
11978            .selections
11979            .all::<Point>(cx)
11980            .into_iter()
11981            .map(|selection| selection.start..selection.end)
11982            .collect::<Vec<_>>();
11983        self.unfold_ranges(&selections, true, true, cx);
11984
11985        let mut new_selection_ranges = Vec::new();
11986        {
11987            let buffer = self.buffer.read(cx).read(cx);
11988            for selection in selections {
11989                for row in selection.start.row..selection.end.row {
11990                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11991                    new_selection_ranges.push(cursor..cursor);
11992                }
11993
11994                let is_multiline_selection = selection.start.row != selection.end.row;
11995                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11996                // so this action feels more ergonomic when paired with other selection operations
11997                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11998                if !should_skip_last {
11999                    new_selection_ranges.push(selection.end..selection.end);
12000                }
12001            }
12002        }
12003        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12004            s.select_ranges(new_selection_ranges);
12005        });
12006    }
12007
12008    pub fn add_selection_above(
12009        &mut self,
12010        _: &AddSelectionAbove,
12011        window: &mut Window,
12012        cx: &mut Context<Self>,
12013    ) {
12014        self.add_selection(true, window, cx);
12015    }
12016
12017    pub fn add_selection_below(
12018        &mut self,
12019        _: &AddSelectionBelow,
12020        window: &mut Window,
12021        cx: &mut Context<Self>,
12022    ) {
12023        self.add_selection(false, window, cx);
12024    }
12025
12026    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12027        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12028
12029        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12030        let mut selections = self.selections.all::<Point>(cx);
12031        let text_layout_details = self.text_layout_details(window);
12032        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12033            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12034            let range = oldest_selection.display_range(&display_map).sorted();
12035
12036            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12037            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12038            let positions = start_x.min(end_x)..start_x.max(end_x);
12039
12040            selections.clear();
12041            let mut stack = Vec::new();
12042            for row in range.start.row().0..=range.end.row().0 {
12043                if let Some(selection) = self.selections.build_columnar_selection(
12044                    &display_map,
12045                    DisplayRow(row),
12046                    &positions,
12047                    oldest_selection.reversed,
12048                    &text_layout_details,
12049                ) {
12050                    stack.push(selection.id);
12051                    selections.push(selection);
12052                }
12053            }
12054
12055            if above {
12056                stack.reverse();
12057            }
12058
12059            AddSelectionsState { above, stack }
12060        });
12061
12062        let last_added_selection = *state.stack.last().unwrap();
12063        let mut new_selections = Vec::new();
12064        if above == state.above {
12065            let end_row = if above {
12066                DisplayRow(0)
12067            } else {
12068                display_map.max_point().row()
12069            };
12070
12071            'outer: for selection in selections {
12072                if selection.id == last_added_selection {
12073                    let range = selection.display_range(&display_map).sorted();
12074                    debug_assert_eq!(range.start.row(), range.end.row());
12075                    let mut row = range.start.row();
12076                    let positions =
12077                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12078                            px(start)..px(end)
12079                        } else {
12080                            let start_x =
12081                                display_map.x_for_display_point(range.start, &text_layout_details);
12082                            let end_x =
12083                                display_map.x_for_display_point(range.end, &text_layout_details);
12084                            start_x.min(end_x)..start_x.max(end_x)
12085                        };
12086
12087                    while row != end_row {
12088                        if above {
12089                            row.0 -= 1;
12090                        } else {
12091                            row.0 += 1;
12092                        }
12093
12094                        if let Some(new_selection) = self.selections.build_columnar_selection(
12095                            &display_map,
12096                            row,
12097                            &positions,
12098                            selection.reversed,
12099                            &text_layout_details,
12100                        ) {
12101                            state.stack.push(new_selection.id);
12102                            if above {
12103                                new_selections.push(new_selection);
12104                                new_selections.push(selection);
12105                            } else {
12106                                new_selections.push(selection);
12107                                new_selections.push(new_selection);
12108                            }
12109
12110                            continue 'outer;
12111                        }
12112                    }
12113                }
12114
12115                new_selections.push(selection);
12116            }
12117        } else {
12118            new_selections = selections;
12119            new_selections.retain(|s| s.id != last_added_selection);
12120            state.stack.pop();
12121        }
12122
12123        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12124            s.select(new_selections);
12125        });
12126        if state.stack.len() > 1 {
12127            self.add_selections_state = Some(state);
12128        }
12129    }
12130
12131    fn select_match_ranges(
12132        &mut self,
12133        range: Range<usize>,
12134        reversed: bool,
12135        replace_newest: bool,
12136        auto_scroll: Option<Autoscroll>,
12137        window: &mut Window,
12138        cx: &mut Context<Editor>,
12139    ) {
12140        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12141        self.change_selections(auto_scroll, window, cx, |s| {
12142            if replace_newest {
12143                s.delete(s.newest_anchor().id);
12144            }
12145            if reversed {
12146                s.insert_range(range.end..range.start);
12147            } else {
12148                s.insert_range(range);
12149            }
12150        });
12151    }
12152
12153    pub fn select_next_match_internal(
12154        &mut self,
12155        display_map: &DisplaySnapshot,
12156        replace_newest: bool,
12157        autoscroll: Option<Autoscroll>,
12158        window: &mut Window,
12159        cx: &mut Context<Self>,
12160    ) -> Result<()> {
12161        let buffer = &display_map.buffer_snapshot;
12162        let mut selections = self.selections.all::<usize>(cx);
12163        if let Some(mut select_next_state) = self.select_next_state.take() {
12164            let query = &select_next_state.query;
12165            if !select_next_state.done {
12166                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12167                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12168                let mut next_selected_range = None;
12169
12170                let bytes_after_last_selection =
12171                    buffer.bytes_in_range(last_selection.end..buffer.len());
12172                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12173                let query_matches = query
12174                    .stream_find_iter(bytes_after_last_selection)
12175                    .map(|result| (last_selection.end, result))
12176                    .chain(
12177                        query
12178                            .stream_find_iter(bytes_before_first_selection)
12179                            .map(|result| (0, result)),
12180                    );
12181
12182                for (start_offset, query_match) in query_matches {
12183                    let query_match = query_match.unwrap(); // can only fail due to I/O
12184                    let offset_range =
12185                        start_offset + query_match.start()..start_offset + query_match.end();
12186                    let display_range = offset_range.start.to_display_point(display_map)
12187                        ..offset_range.end.to_display_point(display_map);
12188
12189                    if !select_next_state.wordwise
12190                        || (!movement::is_inside_word(display_map, display_range.start)
12191                            && !movement::is_inside_word(display_map, display_range.end))
12192                    {
12193                        // TODO: This is n^2, because we might check all the selections
12194                        if !selections
12195                            .iter()
12196                            .any(|selection| selection.range().overlaps(&offset_range))
12197                        {
12198                            next_selected_range = Some(offset_range);
12199                            break;
12200                        }
12201                    }
12202                }
12203
12204                if let Some(next_selected_range) = next_selected_range {
12205                    self.select_match_ranges(
12206                        next_selected_range,
12207                        last_selection.reversed,
12208                        replace_newest,
12209                        autoscroll,
12210                        window,
12211                        cx,
12212                    );
12213                } else {
12214                    select_next_state.done = true;
12215                }
12216            }
12217
12218            self.select_next_state = Some(select_next_state);
12219        } else {
12220            let mut only_carets = true;
12221            let mut same_text_selected = true;
12222            let mut selected_text = None;
12223
12224            let mut selections_iter = selections.iter().peekable();
12225            while let Some(selection) = selections_iter.next() {
12226                if selection.start != selection.end {
12227                    only_carets = false;
12228                }
12229
12230                if same_text_selected {
12231                    if selected_text.is_none() {
12232                        selected_text =
12233                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12234                    }
12235
12236                    if let Some(next_selection) = selections_iter.peek() {
12237                        if next_selection.range().len() == selection.range().len() {
12238                            let next_selected_text = buffer
12239                                .text_for_range(next_selection.range())
12240                                .collect::<String>();
12241                            if Some(next_selected_text) != selected_text {
12242                                same_text_selected = false;
12243                                selected_text = None;
12244                            }
12245                        } else {
12246                            same_text_selected = false;
12247                            selected_text = None;
12248                        }
12249                    }
12250                }
12251            }
12252
12253            if only_carets {
12254                for selection in &mut selections {
12255                    let word_range = movement::surrounding_word(
12256                        display_map,
12257                        selection.start.to_display_point(display_map),
12258                    );
12259                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12260                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12261                    selection.goal = SelectionGoal::None;
12262                    selection.reversed = false;
12263                    self.select_match_ranges(
12264                        selection.start..selection.end,
12265                        selection.reversed,
12266                        replace_newest,
12267                        autoscroll,
12268                        window,
12269                        cx,
12270                    );
12271                }
12272
12273                if selections.len() == 1 {
12274                    let selection = selections
12275                        .last()
12276                        .expect("ensured that there's only one selection");
12277                    let query = buffer
12278                        .text_for_range(selection.start..selection.end)
12279                        .collect::<String>();
12280                    let is_empty = query.is_empty();
12281                    let select_state = SelectNextState {
12282                        query: AhoCorasick::new(&[query])?,
12283                        wordwise: true,
12284                        done: is_empty,
12285                    };
12286                    self.select_next_state = Some(select_state);
12287                } else {
12288                    self.select_next_state = None;
12289                }
12290            } else if let Some(selected_text) = selected_text {
12291                self.select_next_state = Some(SelectNextState {
12292                    query: AhoCorasick::new(&[selected_text])?,
12293                    wordwise: false,
12294                    done: false,
12295                });
12296                self.select_next_match_internal(
12297                    display_map,
12298                    replace_newest,
12299                    autoscroll,
12300                    window,
12301                    cx,
12302                )?;
12303            }
12304        }
12305        Ok(())
12306    }
12307
12308    pub fn select_all_matches(
12309        &mut self,
12310        _action: &SelectAllMatches,
12311        window: &mut Window,
12312        cx: &mut Context<Self>,
12313    ) -> Result<()> {
12314        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12315
12316        self.push_to_selection_history();
12317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12318
12319        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12320        let Some(select_next_state) = self.select_next_state.as_mut() else {
12321            return Ok(());
12322        };
12323        if select_next_state.done {
12324            return Ok(());
12325        }
12326
12327        let mut new_selections = Vec::new();
12328
12329        let reversed = self.selections.oldest::<usize>(cx).reversed;
12330        let buffer = &display_map.buffer_snapshot;
12331        let query_matches = select_next_state
12332            .query
12333            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12334
12335        for query_match in query_matches.into_iter() {
12336            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12337            let offset_range = if reversed {
12338                query_match.end()..query_match.start()
12339            } else {
12340                query_match.start()..query_match.end()
12341            };
12342            let display_range = offset_range.start.to_display_point(&display_map)
12343                ..offset_range.end.to_display_point(&display_map);
12344
12345            if !select_next_state.wordwise
12346                || (!movement::is_inside_word(&display_map, display_range.start)
12347                    && !movement::is_inside_word(&display_map, display_range.end))
12348            {
12349                new_selections.push(offset_range.start..offset_range.end);
12350            }
12351        }
12352
12353        select_next_state.done = true;
12354        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12355        self.change_selections(None, window, cx, |selections| {
12356            selections.select_ranges(new_selections)
12357        });
12358
12359        Ok(())
12360    }
12361
12362    pub fn select_next(
12363        &mut self,
12364        action: &SelectNext,
12365        window: &mut Window,
12366        cx: &mut Context<Self>,
12367    ) -> Result<()> {
12368        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12369        self.push_to_selection_history();
12370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12371        self.select_next_match_internal(
12372            &display_map,
12373            action.replace_newest,
12374            Some(Autoscroll::newest()),
12375            window,
12376            cx,
12377        )?;
12378        Ok(())
12379    }
12380
12381    pub fn select_previous(
12382        &mut self,
12383        action: &SelectPrevious,
12384        window: &mut Window,
12385        cx: &mut Context<Self>,
12386    ) -> Result<()> {
12387        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12388        self.push_to_selection_history();
12389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12390        let buffer = &display_map.buffer_snapshot;
12391        let mut selections = self.selections.all::<usize>(cx);
12392        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12393            let query = &select_prev_state.query;
12394            if !select_prev_state.done {
12395                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12396                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12397                let mut next_selected_range = None;
12398                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12399                let bytes_before_last_selection =
12400                    buffer.reversed_bytes_in_range(0..last_selection.start);
12401                let bytes_after_first_selection =
12402                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12403                let query_matches = query
12404                    .stream_find_iter(bytes_before_last_selection)
12405                    .map(|result| (last_selection.start, result))
12406                    .chain(
12407                        query
12408                            .stream_find_iter(bytes_after_first_selection)
12409                            .map(|result| (buffer.len(), result)),
12410                    );
12411                for (end_offset, query_match) in query_matches {
12412                    let query_match = query_match.unwrap(); // can only fail due to I/O
12413                    let offset_range =
12414                        end_offset - query_match.end()..end_offset - query_match.start();
12415                    let display_range = offset_range.start.to_display_point(&display_map)
12416                        ..offset_range.end.to_display_point(&display_map);
12417
12418                    if !select_prev_state.wordwise
12419                        || (!movement::is_inside_word(&display_map, display_range.start)
12420                            && !movement::is_inside_word(&display_map, display_range.end))
12421                    {
12422                        next_selected_range = Some(offset_range);
12423                        break;
12424                    }
12425                }
12426
12427                if let Some(next_selected_range) = next_selected_range {
12428                    self.select_match_ranges(
12429                        next_selected_range,
12430                        last_selection.reversed,
12431                        action.replace_newest,
12432                        Some(Autoscroll::newest()),
12433                        window,
12434                        cx,
12435                    );
12436                } else {
12437                    select_prev_state.done = true;
12438                }
12439            }
12440
12441            self.select_prev_state = Some(select_prev_state);
12442        } else {
12443            let mut only_carets = true;
12444            let mut same_text_selected = true;
12445            let mut selected_text = None;
12446
12447            let mut selections_iter = selections.iter().peekable();
12448            while let Some(selection) = selections_iter.next() {
12449                if selection.start != selection.end {
12450                    only_carets = false;
12451                }
12452
12453                if same_text_selected {
12454                    if selected_text.is_none() {
12455                        selected_text =
12456                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12457                    }
12458
12459                    if let Some(next_selection) = selections_iter.peek() {
12460                        if next_selection.range().len() == selection.range().len() {
12461                            let next_selected_text = buffer
12462                                .text_for_range(next_selection.range())
12463                                .collect::<String>();
12464                            if Some(next_selected_text) != selected_text {
12465                                same_text_selected = false;
12466                                selected_text = None;
12467                            }
12468                        } else {
12469                            same_text_selected = false;
12470                            selected_text = None;
12471                        }
12472                    }
12473                }
12474            }
12475
12476            if only_carets {
12477                for selection in &mut selections {
12478                    let word_range = movement::surrounding_word(
12479                        &display_map,
12480                        selection.start.to_display_point(&display_map),
12481                    );
12482                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12483                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12484                    selection.goal = SelectionGoal::None;
12485                    selection.reversed = false;
12486                    self.select_match_ranges(
12487                        selection.start..selection.end,
12488                        selection.reversed,
12489                        action.replace_newest,
12490                        Some(Autoscroll::newest()),
12491                        window,
12492                        cx,
12493                    );
12494                }
12495                if selections.len() == 1 {
12496                    let selection = selections
12497                        .last()
12498                        .expect("ensured that there's only one selection");
12499                    let query = buffer
12500                        .text_for_range(selection.start..selection.end)
12501                        .collect::<String>();
12502                    let is_empty = query.is_empty();
12503                    let select_state = SelectNextState {
12504                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12505                        wordwise: true,
12506                        done: is_empty,
12507                    };
12508                    self.select_prev_state = Some(select_state);
12509                } else {
12510                    self.select_prev_state = None;
12511                }
12512            } else if let Some(selected_text) = selected_text {
12513                self.select_prev_state = Some(SelectNextState {
12514                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12515                    wordwise: false,
12516                    done: false,
12517                });
12518                self.select_previous(action, window, cx)?;
12519            }
12520        }
12521        Ok(())
12522    }
12523
12524    pub fn find_next_match(
12525        &mut self,
12526        _: &FindNextMatch,
12527        window: &mut Window,
12528        cx: &mut Context<Self>,
12529    ) -> Result<()> {
12530        let selections = self.selections.disjoint_anchors();
12531        match selections.first() {
12532            Some(first) if selections.len() >= 2 => {
12533                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12534                    s.select_ranges([first.range()]);
12535                });
12536            }
12537            _ => self.select_next(
12538                &SelectNext {
12539                    replace_newest: true,
12540                },
12541                window,
12542                cx,
12543            )?,
12544        }
12545        Ok(())
12546    }
12547
12548    pub fn find_previous_match(
12549        &mut self,
12550        _: &FindPreviousMatch,
12551        window: &mut Window,
12552        cx: &mut Context<Self>,
12553    ) -> Result<()> {
12554        let selections = self.selections.disjoint_anchors();
12555        match selections.last() {
12556            Some(last) if selections.len() >= 2 => {
12557                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12558                    s.select_ranges([last.range()]);
12559                });
12560            }
12561            _ => self.select_previous(
12562                &SelectPrevious {
12563                    replace_newest: true,
12564                },
12565                window,
12566                cx,
12567            )?,
12568        }
12569        Ok(())
12570    }
12571
12572    pub fn toggle_comments(
12573        &mut self,
12574        action: &ToggleComments,
12575        window: &mut Window,
12576        cx: &mut Context<Self>,
12577    ) {
12578        if self.read_only(cx) {
12579            return;
12580        }
12581        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12582        let text_layout_details = &self.text_layout_details(window);
12583        self.transact(window, cx, |this, window, cx| {
12584            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12585            let mut edits = Vec::new();
12586            let mut selection_edit_ranges = Vec::new();
12587            let mut last_toggled_row = None;
12588            let snapshot = this.buffer.read(cx).read(cx);
12589            let empty_str: Arc<str> = Arc::default();
12590            let mut suffixes_inserted = Vec::new();
12591            let ignore_indent = action.ignore_indent;
12592
12593            fn comment_prefix_range(
12594                snapshot: &MultiBufferSnapshot,
12595                row: MultiBufferRow,
12596                comment_prefix: &str,
12597                comment_prefix_whitespace: &str,
12598                ignore_indent: bool,
12599            ) -> Range<Point> {
12600                let indent_size = if ignore_indent {
12601                    0
12602                } else {
12603                    snapshot.indent_size_for_line(row).len
12604                };
12605
12606                let start = Point::new(row.0, indent_size);
12607
12608                let mut line_bytes = snapshot
12609                    .bytes_in_range(start..snapshot.max_point())
12610                    .flatten()
12611                    .copied();
12612
12613                // If this line currently begins with the line comment prefix, then record
12614                // the range containing the prefix.
12615                if line_bytes
12616                    .by_ref()
12617                    .take(comment_prefix.len())
12618                    .eq(comment_prefix.bytes())
12619                {
12620                    // Include any whitespace that matches the comment prefix.
12621                    let matching_whitespace_len = line_bytes
12622                        .zip(comment_prefix_whitespace.bytes())
12623                        .take_while(|(a, b)| a == b)
12624                        .count() as u32;
12625                    let end = Point::new(
12626                        start.row,
12627                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12628                    );
12629                    start..end
12630                } else {
12631                    start..start
12632                }
12633            }
12634
12635            fn comment_suffix_range(
12636                snapshot: &MultiBufferSnapshot,
12637                row: MultiBufferRow,
12638                comment_suffix: &str,
12639                comment_suffix_has_leading_space: bool,
12640            ) -> Range<Point> {
12641                let end = Point::new(row.0, snapshot.line_len(row));
12642                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12643
12644                let mut line_end_bytes = snapshot
12645                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12646                    .flatten()
12647                    .copied();
12648
12649                let leading_space_len = if suffix_start_column > 0
12650                    && line_end_bytes.next() == Some(b' ')
12651                    && comment_suffix_has_leading_space
12652                {
12653                    1
12654                } else {
12655                    0
12656                };
12657
12658                // If this line currently begins with the line comment prefix, then record
12659                // the range containing the prefix.
12660                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12661                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12662                    start..end
12663                } else {
12664                    end..end
12665                }
12666            }
12667
12668            // TODO: Handle selections that cross excerpts
12669            for selection in &mut selections {
12670                let start_column = snapshot
12671                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12672                    .len;
12673                let language = if let Some(language) =
12674                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12675                {
12676                    language
12677                } else {
12678                    continue;
12679                };
12680
12681                selection_edit_ranges.clear();
12682
12683                // If multiple selections contain a given row, avoid processing that
12684                // row more than once.
12685                let mut start_row = MultiBufferRow(selection.start.row);
12686                if last_toggled_row == Some(start_row) {
12687                    start_row = start_row.next_row();
12688                }
12689                let end_row =
12690                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12691                        MultiBufferRow(selection.end.row - 1)
12692                    } else {
12693                        MultiBufferRow(selection.end.row)
12694                    };
12695                last_toggled_row = Some(end_row);
12696
12697                if start_row > end_row {
12698                    continue;
12699                }
12700
12701                // If the language has line comments, toggle those.
12702                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12703
12704                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12705                if ignore_indent {
12706                    full_comment_prefixes = full_comment_prefixes
12707                        .into_iter()
12708                        .map(|s| Arc::from(s.trim_end()))
12709                        .collect();
12710                }
12711
12712                if !full_comment_prefixes.is_empty() {
12713                    let first_prefix = full_comment_prefixes
12714                        .first()
12715                        .expect("prefixes is non-empty");
12716                    let prefix_trimmed_lengths = full_comment_prefixes
12717                        .iter()
12718                        .map(|p| p.trim_end_matches(' ').len())
12719                        .collect::<SmallVec<[usize; 4]>>();
12720
12721                    let mut all_selection_lines_are_comments = true;
12722
12723                    for row in start_row.0..=end_row.0 {
12724                        let row = MultiBufferRow(row);
12725                        if start_row < end_row && snapshot.is_line_blank(row) {
12726                            continue;
12727                        }
12728
12729                        let prefix_range = full_comment_prefixes
12730                            .iter()
12731                            .zip(prefix_trimmed_lengths.iter().copied())
12732                            .map(|(prefix, trimmed_prefix_len)| {
12733                                comment_prefix_range(
12734                                    snapshot.deref(),
12735                                    row,
12736                                    &prefix[..trimmed_prefix_len],
12737                                    &prefix[trimmed_prefix_len..],
12738                                    ignore_indent,
12739                                )
12740                            })
12741                            .max_by_key(|range| range.end.column - range.start.column)
12742                            .expect("prefixes is non-empty");
12743
12744                        if prefix_range.is_empty() {
12745                            all_selection_lines_are_comments = false;
12746                        }
12747
12748                        selection_edit_ranges.push(prefix_range);
12749                    }
12750
12751                    if all_selection_lines_are_comments {
12752                        edits.extend(
12753                            selection_edit_ranges
12754                                .iter()
12755                                .cloned()
12756                                .map(|range| (range, empty_str.clone())),
12757                        );
12758                    } else {
12759                        let min_column = selection_edit_ranges
12760                            .iter()
12761                            .map(|range| range.start.column)
12762                            .min()
12763                            .unwrap_or(0);
12764                        edits.extend(selection_edit_ranges.iter().map(|range| {
12765                            let position = Point::new(range.start.row, min_column);
12766                            (position..position, first_prefix.clone())
12767                        }));
12768                    }
12769                } else if let Some((full_comment_prefix, comment_suffix)) =
12770                    language.block_comment_delimiters()
12771                {
12772                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12773                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12774                    let prefix_range = comment_prefix_range(
12775                        snapshot.deref(),
12776                        start_row,
12777                        comment_prefix,
12778                        comment_prefix_whitespace,
12779                        ignore_indent,
12780                    );
12781                    let suffix_range = comment_suffix_range(
12782                        snapshot.deref(),
12783                        end_row,
12784                        comment_suffix.trim_start_matches(' '),
12785                        comment_suffix.starts_with(' '),
12786                    );
12787
12788                    if prefix_range.is_empty() || suffix_range.is_empty() {
12789                        edits.push((
12790                            prefix_range.start..prefix_range.start,
12791                            full_comment_prefix.clone(),
12792                        ));
12793                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12794                        suffixes_inserted.push((end_row, comment_suffix.len()));
12795                    } else {
12796                        edits.push((prefix_range, empty_str.clone()));
12797                        edits.push((suffix_range, empty_str.clone()));
12798                    }
12799                } else {
12800                    continue;
12801                }
12802            }
12803
12804            drop(snapshot);
12805            this.buffer.update(cx, |buffer, cx| {
12806                buffer.edit(edits, None, cx);
12807            });
12808
12809            // Adjust selections so that they end before any comment suffixes that
12810            // were inserted.
12811            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12812            let mut selections = this.selections.all::<Point>(cx);
12813            let snapshot = this.buffer.read(cx).read(cx);
12814            for selection in &mut selections {
12815                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12816                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12817                        Ordering::Less => {
12818                            suffixes_inserted.next();
12819                            continue;
12820                        }
12821                        Ordering::Greater => break,
12822                        Ordering::Equal => {
12823                            if selection.end.column == snapshot.line_len(row) {
12824                                if selection.is_empty() {
12825                                    selection.start.column -= suffix_len as u32;
12826                                }
12827                                selection.end.column -= suffix_len as u32;
12828                            }
12829                            break;
12830                        }
12831                    }
12832                }
12833            }
12834
12835            drop(snapshot);
12836            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12837                s.select(selections)
12838            });
12839
12840            let selections = this.selections.all::<Point>(cx);
12841            let selections_on_single_row = selections.windows(2).all(|selections| {
12842                selections[0].start.row == selections[1].start.row
12843                    && selections[0].end.row == selections[1].end.row
12844                    && selections[0].start.row == selections[0].end.row
12845            });
12846            let selections_selecting = selections
12847                .iter()
12848                .any(|selection| selection.start != selection.end);
12849            let advance_downwards = action.advance_downwards
12850                && selections_on_single_row
12851                && !selections_selecting
12852                && !matches!(this.mode, EditorMode::SingleLine { .. });
12853
12854            if advance_downwards {
12855                let snapshot = this.buffer.read(cx).snapshot(cx);
12856
12857                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12858                    s.move_cursors_with(|display_snapshot, display_point, _| {
12859                        let mut point = display_point.to_point(display_snapshot);
12860                        point.row += 1;
12861                        point = snapshot.clip_point(point, Bias::Left);
12862                        let display_point = point.to_display_point(display_snapshot);
12863                        let goal = SelectionGoal::HorizontalPosition(
12864                            display_snapshot
12865                                .x_for_display_point(display_point, text_layout_details)
12866                                .into(),
12867                        );
12868                        (display_point, goal)
12869                    })
12870                });
12871            }
12872        });
12873    }
12874
12875    pub fn select_enclosing_symbol(
12876        &mut self,
12877        _: &SelectEnclosingSymbol,
12878        window: &mut Window,
12879        cx: &mut Context<Self>,
12880    ) {
12881        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12882
12883        let buffer = self.buffer.read(cx).snapshot(cx);
12884        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12885
12886        fn update_selection(
12887            selection: &Selection<usize>,
12888            buffer_snap: &MultiBufferSnapshot,
12889        ) -> Option<Selection<usize>> {
12890            let cursor = selection.head();
12891            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12892            for symbol in symbols.iter().rev() {
12893                let start = symbol.range.start.to_offset(buffer_snap);
12894                let end = symbol.range.end.to_offset(buffer_snap);
12895                let new_range = start..end;
12896                if start < selection.start || end > selection.end {
12897                    return Some(Selection {
12898                        id: selection.id,
12899                        start: new_range.start,
12900                        end: new_range.end,
12901                        goal: SelectionGoal::None,
12902                        reversed: selection.reversed,
12903                    });
12904                }
12905            }
12906            None
12907        }
12908
12909        let mut selected_larger_symbol = false;
12910        let new_selections = old_selections
12911            .iter()
12912            .map(|selection| match update_selection(selection, &buffer) {
12913                Some(new_selection) => {
12914                    if new_selection.range() != selection.range() {
12915                        selected_larger_symbol = true;
12916                    }
12917                    new_selection
12918                }
12919                None => selection.clone(),
12920            })
12921            .collect::<Vec<_>>();
12922
12923        if selected_larger_symbol {
12924            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12925                s.select(new_selections);
12926            });
12927        }
12928    }
12929
12930    pub fn select_larger_syntax_node(
12931        &mut self,
12932        _: &SelectLargerSyntaxNode,
12933        window: &mut Window,
12934        cx: &mut Context<Self>,
12935    ) {
12936        let Some(visible_row_count) = self.visible_row_count() else {
12937            return;
12938        };
12939        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12940        if old_selections.is_empty() {
12941            return;
12942        }
12943
12944        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12945
12946        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12947        let buffer = self.buffer.read(cx).snapshot(cx);
12948
12949        let mut selected_larger_node = false;
12950        let mut new_selections = old_selections
12951            .iter()
12952            .map(|selection| {
12953                let old_range = selection.start..selection.end;
12954
12955                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12956                    // manually select word at selection
12957                    if ["string_content", "inline"].contains(&node.kind()) {
12958                        let word_range = {
12959                            let display_point = buffer
12960                                .offset_to_point(old_range.start)
12961                                .to_display_point(&display_map);
12962                            let Range { start, end } =
12963                                movement::surrounding_word(&display_map, display_point);
12964                            start.to_point(&display_map).to_offset(&buffer)
12965                                ..end.to_point(&display_map).to_offset(&buffer)
12966                        };
12967                        // ignore if word is already selected
12968                        if !word_range.is_empty() && old_range != word_range {
12969                            let last_word_range = {
12970                                let display_point = buffer
12971                                    .offset_to_point(old_range.end)
12972                                    .to_display_point(&display_map);
12973                                let Range { start, end } =
12974                                    movement::surrounding_word(&display_map, display_point);
12975                                start.to_point(&display_map).to_offset(&buffer)
12976                                    ..end.to_point(&display_map).to_offset(&buffer)
12977                            };
12978                            // only select word if start and end point belongs to same word
12979                            if word_range == last_word_range {
12980                                selected_larger_node = true;
12981                                return Selection {
12982                                    id: selection.id,
12983                                    start: word_range.start,
12984                                    end: word_range.end,
12985                                    goal: SelectionGoal::None,
12986                                    reversed: selection.reversed,
12987                                };
12988                            }
12989                        }
12990                    }
12991                }
12992
12993                let mut new_range = old_range.clone();
12994                while let Some((_node, containing_range)) =
12995                    buffer.syntax_ancestor(new_range.clone())
12996                {
12997                    new_range = match containing_range {
12998                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12999                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
13000                    };
13001                    if !display_map.intersects_fold(new_range.start)
13002                        && !display_map.intersects_fold(new_range.end)
13003                    {
13004                        break;
13005                    }
13006                }
13007
13008                selected_larger_node |= new_range != old_range;
13009                Selection {
13010                    id: selection.id,
13011                    start: new_range.start,
13012                    end: new_range.end,
13013                    goal: SelectionGoal::None,
13014                    reversed: selection.reversed,
13015                }
13016            })
13017            .collect::<Vec<_>>();
13018
13019        if !selected_larger_node {
13020            return; // don't put this call in the history
13021        }
13022
13023        // scroll based on transformation done to the last selection created by the user
13024        let (last_old, last_new) = old_selections
13025            .last()
13026            .zip(new_selections.last().cloned())
13027            .expect("old_selections isn't empty");
13028
13029        // revert selection
13030        let is_selection_reversed = {
13031            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13032            new_selections.last_mut().expect("checked above").reversed =
13033                should_newest_selection_be_reversed;
13034            should_newest_selection_be_reversed
13035        };
13036
13037        if selected_larger_node {
13038            self.select_syntax_node_history.disable_clearing = true;
13039            self.change_selections(None, window, cx, |s| {
13040                s.select(new_selections.clone());
13041            });
13042            self.select_syntax_node_history.disable_clearing = false;
13043        }
13044
13045        let start_row = last_new.start.to_display_point(&display_map).row().0;
13046        let end_row = last_new.end.to_display_point(&display_map).row().0;
13047        let selection_height = end_row - start_row + 1;
13048        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13049
13050        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13051        let scroll_behavior = if fits_on_the_screen {
13052            self.request_autoscroll(Autoscroll::fit(), cx);
13053            SelectSyntaxNodeScrollBehavior::FitSelection
13054        } else if is_selection_reversed {
13055            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13056            SelectSyntaxNodeScrollBehavior::CursorTop
13057        } else {
13058            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13059            SelectSyntaxNodeScrollBehavior::CursorBottom
13060        };
13061
13062        self.select_syntax_node_history.push((
13063            old_selections,
13064            scroll_behavior,
13065            is_selection_reversed,
13066        ));
13067    }
13068
13069    pub fn select_smaller_syntax_node(
13070        &mut self,
13071        _: &SelectSmallerSyntaxNode,
13072        window: &mut Window,
13073        cx: &mut Context<Self>,
13074    ) {
13075        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13076
13077        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13078            self.select_syntax_node_history.pop()
13079        {
13080            if let Some(selection) = selections.last_mut() {
13081                selection.reversed = is_selection_reversed;
13082            }
13083
13084            self.select_syntax_node_history.disable_clearing = true;
13085            self.change_selections(None, window, cx, |s| {
13086                s.select(selections.to_vec());
13087            });
13088            self.select_syntax_node_history.disable_clearing = false;
13089
13090            match scroll_behavior {
13091                SelectSyntaxNodeScrollBehavior::CursorTop => {
13092                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13093                }
13094                SelectSyntaxNodeScrollBehavior::FitSelection => {
13095                    self.request_autoscroll(Autoscroll::fit(), cx);
13096                }
13097                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13098                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13099                }
13100            }
13101        }
13102    }
13103
13104    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13105        if !EditorSettings::get_global(cx).gutter.runnables {
13106            self.clear_tasks();
13107            return Task::ready(());
13108        }
13109        let project = self.project.as_ref().map(Entity::downgrade);
13110        let task_sources = self.lsp_task_sources(cx);
13111        cx.spawn_in(window, async move |editor, cx| {
13112            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13113            let Some(project) = project.and_then(|p| p.upgrade()) else {
13114                return;
13115            };
13116            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13117                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13118            }) else {
13119                return;
13120            };
13121
13122            let hide_runnables = project
13123                .update(cx, |project, cx| {
13124                    // Do not display any test indicators in non-dev server remote projects.
13125                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13126                })
13127                .unwrap_or(true);
13128            if hide_runnables {
13129                return;
13130            }
13131            let new_rows =
13132                cx.background_spawn({
13133                    let snapshot = display_snapshot.clone();
13134                    async move {
13135                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13136                    }
13137                })
13138                    .await;
13139            let Ok(lsp_tasks) =
13140                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13141            else {
13142                return;
13143            };
13144            let lsp_tasks = lsp_tasks.await;
13145
13146            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13147                lsp_tasks
13148                    .into_iter()
13149                    .flat_map(|(kind, tasks)| {
13150                        tasks.into_iter().filter_map(move |(location, task)| {
13151                            Some((kind.clone(), location?, task))
13152                        })
13153                    })
13154                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13155                        let buffer = location.target.buffer;
13156                        let buffer_snapshot = buffer.read(cx).snapshot();
13157                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13158                            |(excerpt_id, snapshot, _)| {
13159                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13160                                    display_snapshot
13161                                        .buffer_snapshot
13162                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13163                                } else {
13164                                    None
13165                                }
13166                            },
13167                        );
13168                        if let Some(offset) = offset {
13169                            let task_buffer_range =
13170                                location.target.range.to_point(&buffer_snapshot);
13171                            let context_buffer_range =
13172                                task_buffer_range.to_offset(&buffer_snapshot);
13173                            let context_range = BufferOffset(context_buffer_range.start)
13174                                ..BufferOffset(context_buffer_range.end);
13175
13176                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13177                                .or_insert_with(|| RunnableTasks {
13178                                    templates: Vec::new(),
13179                                    offset,
13180                                    column: task_buffer_range.start.column,
13181                                    extra_variables: HashMap::default(),
13182                                    context_range,
13183                                })
13184                                .templates
13185                                .push((kind, task.original_task().clone()));
13186                        }
13187
13188                        acc
13189                    })
13190            }) else {
13191                return;
13192            };
13193
13194            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13195            editor
13196                .update(cx, |editor, _| {
13197                    editor.clear_tasks();
13198                    for (key, mut value) in rows {
13199                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13200                            value.templates.extend(lsp_tasks.templates);
13201                        }
13202
13203                        editor.insert_tasks(key, value);
13204                    }
13205                    for (key, value) in lsp_tasks_by_rows {
13206                        editor.insert_tasks(key, value);
13207                    }
13208                })
13209                .ok();
13210        })
13211    }
13212    fn fetch_runnable_ranges(
13213        snapshot: &DisplaySnapshot,
13214        range: Range<Anchor>,
13215    ) -> Vec<language::RunnableRange> {
13216        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13217    }
13218
13219    fn runnable_rows(
13220        project: Entity<Project>,
13221        snapshot: DisplaySnapshot,
13222        runnable_ranges: Vec<RunnableRange>,
13223        mut cx: AsyncWindowContext,
13224    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13225        runnable_ranges
13226            .into_iter()
13227            .filter_map(|mut runnable| {
13228                let tasks = cx
13229                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13230                    .ok()?;
13231                if tasks.is_empty() {
13232                    return None;
13233                }
13234
13235                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13236
13237                let row = snapshot
13238                    .buffer_snapshot
13239                    .buffer_line_for_row(MultiBufferRow(point.row))?
13240                    .1
13241                    .start
13242                    .row;
13243
13244                let context_range =
13245                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13246                Some((
13247                    (runnable.buffer_id, row),
13248                    RunnableTasks {
13249                        templates: tasks,
13250                        offset: snapshot
13251                            .buffer_snapshot
13252                            .anchor_before(runnable.run_range.start),
13253                        context_range,
13254                        column: point.column,
13255                        extra_variables: runnable.extra_captures,
13256                    },
13257                ))
13258            })
13259            .collect()
13260    }
13261
13262    fn templates_with_tags(
13263        project: &Entity<Project>,
13264        runnable: &mut Runnable,
13265        cx: &mut App,
13266    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13267        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13268            let (worktree_id, file) = project
13269                .buffer_for_id(runnable.buffer, cx)
13270                .and_then(|buffer| buffer.read(cx).file())
13271                .map(|file| (file.worktree_id(cx), file.clone()))
13272                .unzip();
13273
13274            (
13275                project.task_store().read(cx).task_inventory().cloned(),
13276                worktree_id,
13277                file,
13278            )
13279        });
13280
13281        let mut templates_with_tags = mem::take(&mut runnable.tags)
13282            .into_iter()
13283            .flat_map(|RunnableTag(tag)| {
13284                inventory
13285                    .as_ref()
13286                    .into_iter()
13287                    .flat_map(|inventory| {
13288                        inventory.read(cx).list_tasks(
13289                            file.clone(),
13290                            Some(runnable.language.clone()),
13291                            worktree_id,
13292                            cx,
13293                        )
13294                    })
13295                    .filter(move |(_, template)| {
13296                        template.tags.iter().any(|source_tag| source_tag == &tag)
13297                    })
13298            })
13299            .sorted_by_key(|(kind, _)| kind.to_owned())
13300            .collect::<Vec<_>>();
13301        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13302            // Strongest source wins; if we have worktree tag binding, prefer that to
13303            // global and language bindings;
13304            // if we have a global binding, prefer that to language binding.
13305            let first_mismatch = templates_with_tags
13306                .iter()
13307                .position(|(tag_source, _)| tag_source != leading_tag_source);
13308            if let Some(index) = first_mismatch {
13309                templates_with_tags.truncate(index);
13310            }
13311        }
13312
13313        templates_with_tags
13314    }
13315
13316    pub fn move_to_enclosing_bracket(
13317        &mut self,
13318        _: &MoveToEnclosingBracket,
13319        window: &mut Window,
13320        cx: &mut Context<Self>,
13321    ) {
13322        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13324            s.move_offsets_with(|snapshot, selection| {
13325                let Some(enclosing_bracket_ranges) =
13326                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13327                else {
13328                    return;
13329                };
13330
13331                let mut best_length = usize::MAX;
13332                let mut best_inside = false;
13333                let mut best_in_bracket_range = false;
13334                let mut best_destination = None;
13335                for (open, close) in enclosing_bracket_ranges {
13336                    let close = close.to_inclusive();
13337                    let length = close.end() - open.start;
13338                    let inside = selection.start >= open.end && selection.end <= *close.start();
13339                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13340                        || close.contains(&selection.head());
13341
13342                    // If best is next to a bracket and current isn't, skip
13343                    if !in_bracket_range && best_in_bracket_range {
13344                        continue;
13345                    }
13346
13347                    // Prefer smaller lengths unless best is inside and current isn't
13348                    if length > best_length && (best_inside || !inside) {
13349                        continue;
13350                    }
13351
13352                    best_length = length;
13353                    best_inside = inside;
13354                    best_in_bracket_range = in_bracket_range;
13355                    best_destination = Some(
13356                        if close.contains(&selection.start) && close.contains(&selection.end) {
13357                            if inside { open.end } else { open.start }
13358                        } else if inside {
13359                            *close.start()
13360                        } else {
13361                            *close.end()
13362                        },
13363                    );
13364                }
13365
13366                if let Some(destination) = best_destination {
13367                    selection.collapse_to(destination, SelectionGoal::None);
13368                }
13369            })
13370        });
13371    }
13372
13373    pub fn undo_selection(
13374        &mut self,
13375        _: &UndoSelection,
13376        window: &mut Window,
13377        cx: &mut Context<Self>,
13378    ) {
13379        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13380        self.end_selection(window, cx);
13381        self.selection_history.mode = SelectionHistoryMode::Undoing;
13382        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13383            self.change_selections(None, window, cx, |s| {
13384                s.select_anchors(entry.selections.to_vec())
13385            });
13386            self.select_next_state = entry.select_next_state;
13387            self.select_prev_state = entry.select_prev_state;
13388            self.add_selections_state = entry.add_selections_state;
13389            self.request_autoscroll(Autoscroll::newest(), cx);
13390        }
13391        self.selection_history.mode = SelectionHistoryMode::Normal;
13392    }
13393
13394    pub fn redo_selection(
13395        &mut self,
13396        _: &RedoSelection,
13397        window: &mut Window,
13398        cx: &mut Context<Self>,
13399    ) {
13400        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13401        self.end_selection(window, cx);
13402        self.selection_history.mode = SelectionHistoryMode::Redoing;
13403        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13404            self.change_selections(None, window, cx, |s| {
13405                s.select_anchors(entry.selections.to_vec())
13406            });
13407            self.select_next_state = entry.select_next_state;
13408            self.select_prev_state = entry.select_prev_state;
13409            self.add_selections_state = entry.add_selections_state;
13410            self.request_autoscroll(Autoscroll::newest(), cx);
13411        }
13412        self.selection_history.mode = SelectionHistoryMode::Normal;
13413    }
13414
13415    pub fn expand_excerpts(
13416        &mut self,
13417        action: &ExpandExcerpts,
13418        _: &mut Window,
13419        cx: &mut Context<Self>,
13420    ) {
13421        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13422    }
13423
13424    pub fn expand_excerpts_down(
13425        &mut self,
13426        action: &ExpandExcerptsDown,
13427        _: &mut Window,
13428        cx: &mut Context<Self>,
13429    ) {
13430        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13431    }
13432
13433    pub fn expand_excerpts_up(
13434        &mut self,
13435        action: &ExpandExcerptsUp,
13436        _: &mut Window,
13437        cx: &mut Context<Self>,
13438    ) {
13439        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13440    }
13441
13442    pub fn expand_excerpts_for_direction(
13443        &mut self,
13444        lines: u32,
13445        direction: ExpandExcerptDirection,
13446
13447        cx: &mut Context<Self>,
13448    ) {
13449        let selections = self.selections.disjoint_anchors();
13450
13451        let lines = if lines == 0 {
13452            EditorSettings::get_global(cx).expand_excerpt_lines
13453        } else {
13454            lines
13455        };
13456
13457        self.buffer.update(cx, |buffer, cx| {
13458            let snapshot = buffer.snapshot(cx);
13459            let mut excerpt_ids = selections
13460                .iter()
13461                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13462                .collect::<Vec<_>>();
13463            excerpt_ids.sort();
13464            excerpt_ids.dedup();
13465            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13466        })
13467    }
13468
13469    pub fn expand_excerpt(
13470        &mut self,
13471        excerpt: ExcerptId,
13472        direction: ExpandExcerptDirection,
13473        window: &mut Window,
13474        cx: &mut Context<Self>,
13475    ) {
13476        let current_scroll_position = self.scroll_position(cx);
13477        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13478        let mut should_scroll_up = false;
13479
13480        if direction == ExpandExcerptDirection::Down {
13481            let multi_buffer = self.buffer.read(cx);
13482            let snapshot = multi_buffer.snapshot(cx);
13483            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13484                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13485                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13486                        let buffer_snapshot = buffer.read(cx).snapshot();
13487                        let excerpt_end_row =
13488                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13489                        let last_row = buffer_snapshot.max_point().row;
13490                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13491                        should_scroll_up = lines_below >= lines_to_expand;
13492                    }
13493                }
13494            }
13495        }
13496
13497        self.buffer.update(cx, |buffer, cx| {
13498            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13499        });
13500
13501        if should_scroll_up {
13502            let new_scroll_position =
13503                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13504            self.set_scroll_position(new_scroll_position, window, cx);
13505        }
13506    }
13507
13508    pub fn go_to_singleton_buffer_point(
13509        &mut self,
13510        point: Point,
13511        window: &mut Window,
13512        cx: &mut Context<Self>,
13513    ) {
13514        self.go_to_singleton_buffer_range(point..point, window, cx);
13515    }
13516
13517    pub fn go_to_singleton_buffer_range(
13518        &mut self,
13519        range: Range<Point>,
13520        window: &mut Window,
13521        cx: &mut Context<Self>,
13522    ) {
13523        let multibuffer = self.buffer().read(cx);
13524        let Some(buffer) = multibuffer.as_singleton() else {
13525            return;
13526        };
13527        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13528            return;
13529        };
13530        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13531            return;
13532        };
13533        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13534            s.select_anchor_ranges([start..end])
13535        });
13536    }
13537
13538    pub fn go_to_diagnostic(
13539        &mut self,
13540        _: &GoToDiagnostic,
13541        window: &mut Window,
13542        cx: &mut Context<Self>,
13543    ) {
13544        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13545        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13546    }
13547
13548    pub fn go_to_prev_diagnostic(
13549        &mut self,
13550        _: &GoToPreviousDiagnostic,
13551        window: &mut Window,
13552        cx: &mut Context<Self>,
13553    ) {
13554        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13555        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13556    }
13557
13558    pub fn go_to_diagnostic_impl(
13559        &mut self,
13560        direction: Direction,
13561        window: &mut Window,
13562        cx: &mut Context<Self>,
13563    ) {
13564        let buffer = self.buffer.read(cx).snapshot(cx);
13565        let selection = self.selections.newest::<usize>(cx);
13566
13567        let mut active_group_id = None;
13568        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13569            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13570                active_group_id = Some(active_group.group_id);
13571            }
13572        }
13573
13574        fn filtered(
13575            snapshot: EditorSnapshot,
13576            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13577        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13578            diagnostics
13579                .filter(|entry| entry.range.start != entry.range.end)
13580                .filter(|entry| !entry.diagnostic.is_unnecessary)
13581                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13582        }
13583
13584        let snapshot = self.snapshot(window, cx);
13585        let before = filtered(
13586            snapshot.clone(),
13587            buffer
13588                .diagnostics_in_range(0..selection.start)
13589                .filter(|entry| entry.range.start <= selection.start),
13590        );
13591        let after = filtered(
13592            snapshot,
13593            buffer
13594                .diagnostics_in_range(selection.start..buffer.len())
13595                .filter(|entry| entry.range.start >= selection.start),
13596        );
13597
13598        let mut found: Option<DiagnosticEntry<usize>> = None;
13599        if direction == Direction::Prev {
13600            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13601            {
13602                for diagnostic in prev_diagnostics.into_iter().rev() {
13603                    if diagnostic.range.start != selection.start
13604                        || active_group_id
13605                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13606                    {
13607                        found = Some(diagnostic);
13608                        break 'outer;
13609                    }
13610                }
13611            }
13612        } else {
13613            for diagnostic in after.chain(before) {
13614                if diagnostic.range.start != selection.start
13615                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13616                {
13617                    found = Some(diagnostic);
13618                    break;
13619                }
13620            }
13621        }
13622        let Some(next_diagnostic) = found else {
13623            return;
13624        };
13625
13626        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13627            return;
13628        };
13629        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13630            s.select_ranges(vec![
13631                next_diagnostic.range.start..next_diagnostic.range.start,
13632            ])
13633        });
13634        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13635        self.refresh_inline_completion(false, true, window, cx);
13636    }
13637
13638    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13639        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13640        let snapshot = self.snapshot(window, cx);
13641        let selection = self.selections.newest::<Point>(cx);
13642        self.go_to_hunk_before_or_after_position(
13643            &snapshot,
13644            selection.head(),
13645            Direction::Next,
13646            window,
13647            cx,
13648        );
13649    }
13650
13651    pub fn go_to_hunk_before_or_after_position(
13652        &mut self,
13653        snapshot: &EditorSnapshot,
13654        position: Point,
13655        direction: Direction,
13656        window: &mut Window,
13657        cx: &mut Context<Editor>,
13658    ) {
13659        let row = if direction == Direction::Next {
13660            self.hunk_after_position(snapshot, position)
13661                .map(|hunk| hunk.row_range.start)
13662        } else {
13663            self.hunk_before_position(snapshot, position)
13664        };
13665
13666        if let Some(row) = row {
13667            let destination = Point::new(row.0, 0);
13668            let autoscroll = Autoscroll::center();
13669
13670            self.unfold_ranges(&[destination..destination], false, false, cx);
13671            self.change_selections(Some(autoscroll), window, cx, |s| {
13672                s.select_ranges([destination..destination]);
13673            });
13674        }
13675    }
13676
13677    fn hunk_after_position(
13678        &mut self,
13679        snapshot: &EditorSnapshot,
13680        position: Point,
13681    ) -> Option<MultiBufferDiffHunk> {
13682        snapshot
13683            .buffer_snapshot
13684            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13685            .find(|hunk| hunk.row_range.start.0 > position.row)
13686            .or_else(|| {
13687                snapshot
13688                    .buffer_snapshot
13689                    .diff_hunks_in_range(Point::zero()..position)
13690                    .find(|hunk| hunk.row_range.end.0 < position.row)
13691            })
13692    }
13693
13694    fn go_to_prev_hunk(
13695        &mut self,
13696        _: &GoToPreviousHunk,
13697        window: &mut Window,
13698        cx: &mut Context<Self>,
13699    ) {
13700        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13701        let snapshot = self.snapshot(window, cx);
13702        let selection = self.selections.newest::<Point>(cx);
13703        self.go_to_hunk_before_or_after_position(
13704            &snapshot,
13705            selection.head(),
13706            Direction::Prev,
13707            window,
13708            cx,
13709        );
13710    }
13711
13712    fn hunk_before_position(
13713        &mut self,
13714        snapshot: &EditorSnapshot,
13715        position: Point,
13716    ) -> Option<MultiBufferRow> {
13717        snapshot
13718            .buffer_snapshot
13719            .diff_hunk_before(position)
13720            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13721    }
13722
13723    fn go_to_next_change(
13724        &mut self,
13725        _: &GoToNextChange,
13726        window: &mut Window,
13727        cx: &mut Context<Self>,
13728    ) {
13729        if let Some(selections) = self
13730            .change_list
13731            .next_change(1, Direction::Next)
13732            .map(|s| s.to_vec())
13733        {
13734            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13735                let map = s.display_map();
13736                s.select_display_ranges(selections.iter().map(|a| {
13737                    let point = a.to_display_point(&map);
13738                    point..point
13739                }))
13740            })
13741        }
13742    }
13743
13744    fn go_to_previous_change(
13745        &mut self,
13746        _: &GoToPreviousChange,
13747        window: &mut Window,
13748        cx: &mut Context<Self>,
13749    ) {
13750        if let Some(selections) = self
13751            .change_list
13752            .next_change(1, Direction::Prev)
13753            .map(|s| s.to_vec())
13754        {
13755            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13756                let map = s.display_map();
13757                s.select_display_ranges(selections.iter().map(|a| {
13758                    let point = a.to_display_point(&map);
13759                    point..point
13760                }))
13761            })
13762        }
13763    }
13764
13765    fn go_to_line<T: 'static>(
13766        &mut self,
13767        position: Anchor,
13768        highlight_color: Option<Hsla>,
13769        window: &mut Window,
13770        cx: &mut Context<Self>,
13771    ) {
13772        let snapshot = self.snapshot(window, cx).display_snapshot;
13773        let position = position.to_point(&snapshot.buffer_snapshot);
13774        let start = snapshot
13775            .buffer_snapshot
13776            .clip_point(Point::new(position.row, 0), Bias::Left);
13777        let end = start + Point::new(1, 0);
13778        let start = snapshot.buffer_snapshot.anchor_before(start);
13779        let end = snapshot.buffer_snapshot.anchor_before(end);
13780
13781        self.highlight_rows::<T>(
13782            start..end,
13783            highlight_color
13784                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13785            Default::default(),
13786            cx,
13787        );
13788        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13789    }
13790
13791    pub fn go_to_definition(
13792        &mut self,
13793        _: &GoToDefinition,
13794        window: &mut Window,
13795        cx: &mut Context<Self>,
13796    ) -> Task<Result<Navigated>> {
13797        let definition =
13798            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13799        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13800        cx.spawn_in(window, async move |editor, cx| {
13801            if definition.await? == Navigated::Yes {
13802                return Ok(Navigated::Yes);
13803            }
13804            match fallback_strategy {
13805                GoToDefinitionFallback::None => Ok(Navigated::No),
13806                GoToDefinitionFallback::FindAllReferences => {
13807                    match editor.update_in(cx, |editor, window, cx| {
13808                        editor.find_all_references(&FindAllReferences, window, cx)
13809                    })? {
13810                        Some(references) => references.await,
13811                        None => Ok(Navigated::No),
13812                    }
13813                }
13814            }
13815        })
13816    }
13817
13818    pub fn go_to_declaration(
13819        &mut self,
13820        _: &GoToDeclaration,
13821        window: &mut Window,
13822        cx: &mut Context<Self>,
13823    ) -> Task<Result<Navigated>> {
13824        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13825    }
13826
13827    pub fn go_to_declaration_split(
13828        &mut self,
13829        _: &GoToDeclaration,
13830        window: &mut Window,
13831        cx: &mut Context<Self>,
13832    ) -> Task<Result<Navigated>> {
13833        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13834    }
13835
13836    pub fn go_to_implementation(
13837        &mut self,
13838        _: &GoToImplementation,
13839        window: &mut Window,
13840        cx: &mut Context<Self>,
13841    ) -> Task<Result<Navigated>> {
13842        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13843    }
13844
13845    pub fn go_to_implementation_split(
13846        &mut self,
13847        _: &GoToImplementationSplit,
13848        window: &mut Window,
13849        cx: &mut Context<Self>,
13850    ) -> Task<Result<Navigated>> {
13851        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13852    }
13853
13854    pub fn go_to_type_definition(
13855        &mut self,
13856        _: &GoToTypeDefinition,
13857        window: &mut Window,
13858        cx: &mut Context<Self>,
13859    ) -> Task<Result<Navigated>> {
13860        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13861    }
13862
13863    pub fn go_to_definition_split(
13864        &mut self,
13865        _: &GoToDefinitionSplit,
13866        window: &mut Window,
13867        cx: &mut Context<Self>,
13868    ) -> Task<Result<Navigated>> {
13869        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13870    }
13871
13872    pub fn go_to_type_definition_split(
13873        &mut self,
13874        _: &GoToTypeDefinitionSplit,
13875        window: &mut Window,
13876        cx: &mut Context<Self>,
13877    ) -> Task<Result<Navigated>> {
13878        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13879    }
13880
13881    fn go_to_definition_of_kind(
13882        &mut self,
13883        kind: GotoDefinitionKind,
13884        split: bool,
13885        window: &mut Window,
13886        cx: &mut Context<Self>,
13887    ) -> Task<Result<Navigated>> {
13888        let Some(provider) = self.semantics_provider.clone() else {
13889            return Task::ready(Ok(Navigated::No));
13890        };
13891        let head = self.selections.newest::<usize>(cx).head();
13892        let buffer = self.buffer.read(cx);
13893        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13894            text_anchor
13895        } else {
13896            return Task::ready(Ok(Navigated::No));
13897        };
13898
13899        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13900            return Task::ready(Ok(Navigated::No));
13901        };
13902
13903        cx.spawn_in(window, async move |editor, cx| {
13904            let definitions = definitions.await?;
13905            let navigated = editor
13906                .update_in(cx, |editor, window, cx| {
13907                    editor.navigate_to_hover_links(
13908                        Some(kind),
13909                        definitions
13910                            .into_iter()
13911                            .filter(|location| {
13912                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13913                            })
13914                            .map(HoverLink::Text)
13915                            .collect::<Vec<_>>(),
13916                        split,
13917                        window,
13918                        cx,
13919                    )
13920                })?
13921                .await?;
13922            anyhow::Ok(navigated)
13923        })
13924    }
13925
13926    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13927        let selection = self.selections.newest_anchor();
13928        let head = selection.head();
13929        let tail = selection.tail();
13930
13931        let Some((buffer, start_position)) =
13932            self.buffer.read(cx).text_anchor_for_position(head, cx)
13933        else {
13934            return;
13935        };
13936
13937        let end_position = if head != tail {
13938            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13939                return;
13940            };
13941            Some(pos)
13942        } else {
13943            None
13944        };
13945
13946        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13947            let url = if let Some(end_pos) = end_position {
13948                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13949            } else {
13950                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13951            };
13952
13953            if let Some(url) = url {
13954                editor.update(cx, |_, cx| {
13955                    cx.open_url(&url);
13956                })
13957            } else {
13958                Ok(())
13959            }
13960        });
13961
13962        url_finder.detach();
13963    }
13964
13965    pub fn open_selected_filename(
13966        &mut self,
13967        _: &OpenSelectedFilename,
13968        window: &mut Window,
13969        cx: &mut Context<Self>,
13970    ) {
13971        let Some(workspace) = self.workspace() else {
13972            return;
13973        };
13974
13975        let position = self.selections.newest_anchor().head();
13976
13977        let Some((buffer, buffer_position)) =
13978            self.buffer.read(cx).text_anchor_for_position(position, cx)
13979        else {
13980            return;
13981        };
13982
13983        let project = self.project.clone();
13984
13985        cx.spawn_in(window, async move |_, cx| {
13986            let result = find_file(&buffer, project, buffer_position, cx).await;
13987
13988            if let Some((_, path)) = result {
13989                workspace
13990                    .update_in(cx, |workspace, window, cx| {
13991                        workspace.open_resolved_path(path, window, cx)
13992                    })?
13993                    .await?;
13994            }
13995            anyhow::Ok(())
13996        })
13997        .detach();
13998    }
13999
14000    pub(crate) fn navigate_to_hover_links(
14001        &mut self,
14002        kind: Option<GotoDefinitionKind>,
14003        mut definitions: Vec<HoverLink>,
14004        split: bool,
14005        window: &mut Window,
14006        cx: &mut Context<Editor>,
14007    ) -> Task<Result<Navigated>> {
14008        // If there is one definition, just open it directly
14009        if definitions.len() == 1 {
14010            let definition = definitions.pop().unwrap();
14011
14012            enum TargetTaskResult {
14013                Location(Option<Location>),
14014                AlreadyNavigated,
14015            }
14016
14017            let target_task = match definition {
14018                HoverLink::Text(link) => {
14019                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14020                }
14021                HoverLink::InlayHint(lsp_location, server_id) => {
14022                    let computation =
14023                        self.compute_target_location(lsp_location, server_id, window, cx);
14024                    cx.background_spawn(async move {
14025                        let location = computation.await?;
14026                        Ok(TargetTaskResult::Location(location))
14027                    })
14028                }
14029                HoverLink::Url(url) => {
14030                    cx.open_url(&url);
14031                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14032                }
14033                HoverLink::File(path) => {
14034                    if let Some(workspace) = self.workspace() {
14035                        cx.spawn_in(window, async move |_, cx| {
14036                            workspace
14037                                .update_in(cx, |workspace, window, cx| {
14038                                    workspace.open_resolved_path(path, window, cx)
14039                                })?
14040                                .await
14041                                .map(|_| TargetTaskResult::AlreadyNavigated)
14042                        })
14043                    } else {
14044                        Task::ready(Ok(TargetTaskResult::Location(None)))
14045                    }
14046                }
14047            };
14048            cx.spawn_in(window, async move |editor, cx| {
14049                let target = match target_task.await.context("target resolution task")? {
14050                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14051                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14052                    TargetTaskResult::Location(Some(target)) => target,
14053                };
14054
14055                editor.update_in(cx, |editor, window, cx| {
14056                    let Some(workspace) = editor.workspace() else {
14057                        return Navigated::No;
14058                    };
14059                    let pane = workspace.read(cx).active_pane().clone();
14060
14061                    let range = target.range.to_point(target.buffer.read(cx));
14062                    let range = editor.range_for_match(&range);
14063                    let range = collapse_multiline_range(range);
14064
14065                    if !split
14066                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14067                    {
14068                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14069                    } else {
14070                        window.defer(cx, move |window, cx| {
14071                            let target_editor: Entity<Self> =
14072                                workspace.update(cx, |workspace, cx| {
14073                                    let pane = if split {
14074                                        workspace.adjacent_pane(window, cx)
14075                                    } else {
14076                                        workspace.active_pane().clone()
14077                                    };
14078
14079                                    workspace.open_project_item(
14080                                        pane,
14081                                        target.buffer.clone(),
14082                                        true,
14083                                        true,
14084                                        window,
14085                                        cx,
14086                                    )
14087                                });
14088                            target_editor.update(cx, |target_editor, cx| {
14089                                // When selecting a definition in a different buffer, disable the nav history
14090                                // to avoid creating a history entry at the previous cursor location.
14091                                pane.update(cx, |pane, _| pane.disable_history());
14092                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14093                                pane.update(cx, |pane, _| pane.enable_history());
14094                            });
14095                        });
14096                    }
14097                    Navigated::Yes
14098                })
14099            })
14100        } else if !definitions.is_empty() {
14101            cx.spawn_in(window, async move |editor, cx| {
14102                let (title, location_tasks, workspace) = editor
14103                    .update_in(cx, |editor, window, cx| {
14104                        let tab_kind = match kind {
14105                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14106                            _ => "Definitions",
14107                        };
14108                        let title = definitions
14109                            .iter()
14110                            .find_map(|definition| match definition {
14111                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14112                                    let buffer = origin.buffer.read(cx);
14113                                    format!(
14114                                        "{} for {}",
14115                                        tab_kind,
14116                                        buffer
14117                                            .text_for_range(origin.range.clone())
14118                                            .collect::<String>()
14119                                    )
14120                                }),
14121                                HoverLink::InlayHint(_, _) => None,
14122                                HoverLink::Url(_) => None,
14123                                HoverLink::File(_) => None,
14124                            })
14125                            .unwrap_or(tab_kind.to_string());
14126                        let location_tasks = definitions
14127                            .into_iter()
14128                            .map(|definition| match definition {
14129                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14130                                HoverLink::InlayHint(lsp_location, server_id) => editor
14131                                    .compute_target_location(lsp_location, server_id, window, cx),
14132                                HoverLink::Url(_) => Task::ready(Ok(None)),
14133                                HoverLink::File(_) => Task::ready(Ok(None)),
14134                            })
14135                            .collect::<Vec<_>>();
14136                        (title, location_tasks, editor.workspace().clone())
14137                    })
14138                    .context("location tasks preparation")?;
14139
14140                let locations = future::join_all(location_tasks)
14141                    .await
14142                    .into_iter()
14143                    .filter_map(|location| location.transpose())
14144                    .collect::<Result<_>>()
14145                    .context("location tasks")?;
14146
14147                let Some(workspace) = workspace else {
14148                    return Ok(Navigated::No);
14149                };
14150                let opened = workspace
14151                    .update_in(cx, |workspace, window, cx| {
14152                        Self::open_locations_in_multibuffer(
14153                            workspace,
14154                            locations,
14155                            title,
14156                            split,
14157                            MultibufferSelectionMode::First,
14158                            window,
14159                            cx,
14160                        )
14161                    })
14162                    .ok();
14163
14164                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14165            })
14166        } else {
14167            Task::ready(Ok(Navigated::No))
14168        }
14169    }
14170
14171    fn compute_target_location(
14172        &self,
14173        lsp_location: lsp::Location,
14174        server_id: LanguageServerId,
14175        window: &mut Window,
14176        cx: &mut Context<Self>,
14177    ) -> Task<anyhow::Result<Option<Location>>> {
14178        let Some(project) = self.project.clone() else {
14179            return Task::ready(Ok(None));
14180        };
14181
14182        cx.spawn_in(window, async move |editor, cx| {
14183            let location_task = editor.update(cx, |_, cx| {
14184                project.update(cx, |project, cx| {
14185                    let language_server_name = project
14186                        .language_server_statuses(cx)
14187                        .find(|(id, _)| server_id == *id)
14188                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14189                    language_server_name.map(|language_server_name| {
14190                        project.open_local_buffer_via_lsp(
14191                            lsp_location.uri.clone(),
14192                            server_id,
14193                            language_server_name,
14194                            cx,
14195                        )
14196                    })
14197                })
14198            })?;
14199            let location = match location_task {
14200                Some(task) => Some({
14201                    let target_buffer_handle = task.await.context("open local buffer")?;
14202                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14203                        let target_start = target_buffer
14204                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14205                        let target_end = target_buffer
14206                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14207                        target_buffer.anchor_after(target_start)
14208                            ..target_buffer.anchor_before(target_end)
14209                    })?;
14210                    Location {
14211                        buffer: target_buffer_handle,
14212                        range,
14213                    }
14214                }),
14215                None => None,
14216            };
14217            Ok(location)
14218        })
14219    }
14220
14221    pub fn find_all_references(
14222        &mut self,
14223        _: &FindAllReferences,
14224        window: &mut Window,
14225        cx: &mut Context<Self>,
14226    ) -> Option<Task<Result<Navigated>>> {
14227        let selection = self.selections.newest::<usize>(cx);
14228        let multi_buffer = self.buffer.read(cx);
14229        let head = selection.head();
14230
14231        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14232        let head_anchor = multi_buffer_snapshot.anchor_at(
14233            head,
14234            if head < selection.tail() {
14235                Bias::Right
14236            } else {
14237                Bias::Left
14238            },
14239        );
14240
14241        match self
14242            .find_all_references_task_sources
14243            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14244        {
14245            Ok(_) => {
14246                log::info!(
14247                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14248                );
14249                return None;
14250            }
14251            Err(i) => {
14252                self.find_all_references_task_sources.insert(i, head_anchor);
14253            }
14254        }
14255
14256        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14257        let workspace = self.workspace()?;
14258        let project = workspace.read(cx).project().clone();
14259        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14260        Some(cx.spawn_in(window, async move |editor, cx| {
14261            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14262                if let Ok(i) = editor
14263                    .find_all_references_task_sources
14264                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14265                {
14266                    editor.find_all_references_task_sources.remove(i);
14267                }
14268            });
14269
14270            let locations = references.await?;
14271            if locations.is_empty() {
14272                return anyhow::Ok(Navigated::No);
14273            }
14274
14275            workspace.update_in(cx, |workspace, window, cx| {
14276                let title = locations
14277                    .first()
14278                    .as_ref()
14279                    .map(|location| {
14280                        let buffer = location.buffer.read(cx);
14281                        format!(
14282                            "References to `{}`",
14283                            buffer
14284                                .text_for_range(location.range.clone())
14285                                .collect::<String>()
14286                        )
14287                    })
14288                    .unwrap();
14289                Self::open_locations_in_multibuffer(
14290                    workspace,
14291                    locations,
14292                    title,
14293                    false,
14294                    MultibufferSelectionMode::First,
14295                    window,
14296                    cx,
14297                );
14298                Navigated::Yes
14299            })
14300        }))
14301    }
14302
14303    /// Opens a multibuffer with the given project locations in it
14304    pub fn open_locations_in_multibuffer(
14305        workspace: &mut Workspace,
14306        mut locations: Vec<Location>,
14307        title: String,
14308        split: bool,
14309        multibuffer_selection_mode: MultibufferSelectionMode,
14310        window: &mut Window,
14311        cx: &mut Context<Workspace>,
14312    ) {
14313        // If there are multiple definitions, open them in a multibuffer
14314        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14315        let mut locations = locations.into_iter().peekable();
14316        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14317        let capability = workspace.project().read(cx).capability();
14318
14319        let excerpt_buffer = cx.new(|cx| {
14320            let mut multibuffer = MultiBuffer::new(capability);
14321            while let Some(location) = locations.next() {
14322                let buffer = location.buffer.read(cx);
14323                let mut ranges_for_buffer = Vec::new();
14324                let range = location.range.to_point(buffer);
14325                ranges_for_buffer.push(range.clone());
14326
14327                while let Some(next_location) = locations.peek() {
14328                    if next_location.buffer == location.buffer {
14329                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14330                        locations.next();
14331                    } else {
14332                        break;
14333                    }
14334                }
14335
14336                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14337                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14338                    PathKey::for_buffer(&location.buffer, cx),
14339                    location.buffer.clone(),
14340                    ranges_for_buffer,
14341                    DEFAULT_MULTIBUFFER_CONTEXT,
14342                    cx,
14343                );
14344                ranges.extend(new_ranges)
14345            }
14346
14347            multibuffer.with_title(title)
14348        });
14349
14350        let editor = cx.new(|cx| {
14351            Editor::for_multibuffer(
14352                excerpt_buffer,
14353                Some(workspace.project().clone()),
14354                window,
14355                cx,
14356            )
14357        });
14358        editor.update(cx, |editor, cx| {
14359            match multibuffer_selection_mode {
14360                MultibufferSelectionMode::First => {
14361                    if let Some(first_range) = ranges.first() {
14362                        editor.change_selections(None, window, cx, |selections| {
14363                            selections.clear_disjoint();
14364                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14365                        });
14366                    }
14367                    editor.highlight_background::<Self>(
14368                        &ranges,
14369                        |theme| theme.editor_highlighted_line_background,
14370                        cx,
14371                    );
14372                }
14373                MultibufferSelectionMode::All => {
14374                    editor.change_selections(None, window, cx, |selections| {
14375                        selections.clear_disjoint();
14376                        selections.select_anchor_ranges(ranges);
14377                    });
14378                }
14379            }
14380            editor.register_buffers_with_language_servers(cx);
14381        });
14382
14383        let item = Box::new(editor);
14384        let item_id = item.item_id();
14385
14386        if split {
14387            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14388        } else {
14389            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14390                let (preview_item_id, preview_item_idx) =
14391                    workspace.active_pane().update(cx, |pane, _| {
14392                        (pane.preview_item_id(), pane.preview_item_idx())
14393                    });
14394
14395                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14396
14397                if let Some(preview_item_id) = preview_item_id {
14398                    workspace.active_pane().update(cx, |pane, cx| {
14399                        pane.remove_item(preview_item_id, false, false, window, cx);
14400                    });
14401                }
14402            } else {
14403                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14404            }
14405        }
14406        workspace.active_pane().update(cx, |pane, cx| {
14407            pane.set_preview_item_id(Some(item_id), cx);
14408        });
14409    }
14410
14411    pub fn rename(
14412        &mut self,
14413        _: &Rename,
14414        window: &mut Window,
14415        cx: &mut Context<Self>,
14416    ) -> Option<Task<Result<()>>> {
14417        use language::ToOffset as _;
14418
14419        let provider = self.semantics_provider.clone()?;
14420        let selection = self.selections.newest_anchor().clone();
14421        let (cursor_buffer, cursor_buffer_position) = self
14422            .buffer
14423            .read(cx)
14424            .text_anchor_for_position(selection.head(), cx)?;
14425        let (tail_buffer, cursor_buffer_position_end) = self
14426            .buffer
14427            .read(cx)
14428            .text_anchor_for_position(selection.tail(), cx)?;
14429        if tail_buffer != cursor_buffer {
14430            return None;
14431        }
14432
14433        let snapshot = cursor_buffer.read(cx).snapshot();
14434        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14435        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14436        let prepare_rename = provider
14437            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14438            .unwrap_or_else(|| Task::ready(Ok(None)));
14439        drop(snapshot);
14440
14441        Some(cx.spawn_in(window, async move |this, cx| {
14442            let rename_range = if let Some(range) = prepare_rename.await? {
14443                Some(range)
14444            } else {
14445                this.update(cx, |this, cx| {
14446                    let buffer = this.buffer.read(cx).snapshot(cx);
14447                    let mut buffer_highlights = this
14448                        .document_highlights_for_position(selection.head(), &buffer)
14449                        .filter(|highlight| {
14450                            highlight.start.excerpt_id == selection.head().excerpt_id
14451                                && highlight.end.excerpt_id == selection.head().excerpt_id
14452                        });
14453                    buffer_highlights
14454                        .next()
14455                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14456                })?
14457            };
14458            if let Some(rename_range) = rename_range {
14459                this.update_in(cx, |this, window, cx| {
14460                    let snapshot = cursor_buffer.read(cx).snapshot();
14461                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14462                    let cursor_offset_in_rename_range =
14463                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14464                    let cursor_offset_in_rename_range_end =
14465                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14466
14467                    this.take_rename(false, window, cx);
14468                    let buffer = this.buffer.read(cx).read(cx);
14469                    let cursor_offset = selection.head().to_offset(&buffer);
14470                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14471                    let rename_end = rename_start + rename_buffer_range.len();
14472                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14473                    let mut old_highlight_id = None;
14474                    let old_name: Arc<str> = buffer
14475                        .chunks(rename_start..rename_end, true)
14476                        .map(|chunk| {
14477                            if old_highlight_id.is_none() {
14478                                old_highlight_id = chunk.syntax_highlight_id;
14479                            }
14480                            chunk.text
14481                        })
14482                        .collect::<String>()
14483                        .into();
14484
14485                    drop(buffer);
14486
14487                    // Position the selection in the rename editor so that it matches the current selection.
14488                    this.show_local_selections = false;
14489                    let rename_editor = cx.new(|cx| {
14490                        let mut editor = Editor::single_line(window, cx);
14491                        editor.buffer.update(cx, |buffer, cx| {
14492                            buffer.edit([(0..0, old_name.clone())], None, cx)
14493                        });
14494                        let rename_selection_range = match cursor_offset_in_rename_range
14495                            .cmp(&cursor_offset_in_rename_range_end)
14496                        {
14497                            Ordering::Equal => {
14498                                editor.select_all(&SelectAll, window, cx);
14499                                return editor;
14500                            }
14501                            Ordering::Less => {
14502                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14503                            }
14504                            Ordering::Greater => {
14505                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14506                            }
14507                        };
14508                        if rename_selection_range.end > old_name.len() {
14509                            editor.select_all(&SelectAll, window, cx);
14510                        } else {
14511                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14512                                s.select_ranges([rename_selection_range]);
14513                            });
14514                        }
14515                        editor
14516                    });
14517                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14518                        if e == &EditorEvent::Focused {
14519                            cx.emit(EditorEvent::FocusedIn)
14520                        }
14521                    })
14522                    .detach();
14523
14524                    let write_highlights =
14525                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14526                    let read_highlights =
14527                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14528                    let ranges = write_highlights
14529                        .iter()
14530                        .flat_map(|(_, ranges)| ranges.iter())
14531                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14532                        .cloned()
14533                        .collect();
14534
14535                    this.highlight_text::<Rename>(
14536                        ranges,
14537                        HighlightStyle {
14538                            fade_out: Some(0.6),
14539                            ..Default::default()
14540                        },
14541                        cx,
14542                    );
14543                    let rename_focus_handle = rename_editor.focus_handle(cx);
14544                    window.focus(&rename_focus_handle);
14545                    let block_id = this.insert_blocks(
14546                        [BlockProperties {
14547                            style: BlockStyle::Flex,
14548                            placement: BlockPlacement::Below(range.start),
14549                            height: Some(1),
14550                            render: Arc::new({
14551                                let rename_editor = rename_editor.clone();
14552                                move |cx: &mut BlockContext| {
14553                                    let mut text_style = cx.editor_style.text.clone();
14554                                    if let Some(highlight_style) = old_highlight_id
14555                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14556                                    {
14557                                        text_style = text_style.highlight(highlight_style);
14558                                    }
14559                                    div()
14560                                        .block_mouse_down()
14561                                        .pl(cx.anchor_x)
14562                                        .child(EditorElement::new(
14563                                            &rename_editor,
14564                                            EditorStyle {
14565                                                background: cx.theme().system().transparent,
14566                                                local_player: cx.editor_style.local_player,
14567                                                text: text_style,
14568                                                scrollbar_width: cx.editor_style.scrollbar_width,
14569                                                syntax: cx.editor_style.syntax.clone(),
14570                                                status: cx.editor_style.status.clone(),
14571                                                inlay_hints_style: HighlightStyle {
14572                                                    font_weight: Some(FontWeight::BOLD),
14573                                                    ..make_inlay_hints_style(cx.app)
14574                                                },
14575                                                inline_completion_styles: make_suggestion_styles(
14576                                                    cx.app,
14577                                                ),
14578                                                ..EditorStyle::default()
14579                                            },
14580                                        ))
14581                                        .into_any_element()
14582                                }
14583                            }),
14584                            priority: 0,
14585                        }],
14586                        Some(Autoscroll::fit()),
14587                        cx,
14588                    )[0];
14589                    this.pending_rename = Some(RenameState {
14590                        range,
14591                        old_name,
14592                        editor: rename_editor,
14593                        block_id,
14594                    });
14595                })?;
14596            }
14597
14598            Ok(())
14599        }))
14600    }
14601
14602    pub fn confirm_rename(
14603        &mut self,
14604        _: &ConfirmRename,
14605        window: &mut Window,
14606        cx: &mut Context<Self>,
14607    ) -> Option<Task<Result<()>>> {
14608        let rename = self.take_rename(false, window, cx)?;
14609        let workspace = self.workspace()?.downgrade();
14610        let (buffer, start) = self
14611            .buffer
14612            .read(cx)
14613            .text_anchor_for_position(rename.range.start, cx)?;
14614        let (end_buffer, _) = self
14615            .buffer
14616            .read(cx)
14617            .text_anchor_for_position(rename.range.end, cx)?;
14618        if buffer != end_buffer {
14619            return None;
14620        }
14621
14622        let old_name = rename.old_name;
14623        let new_name = rename.editor.read(cx).text(cx);
14624
14625        let rename = self.semantics_provider.as_ref()?.perform_rename(
14626            &buffer,
14627            start,
14628            new_name.clone(),
14629            cx,
14630        )?;
14631
14632        Some(cx.spawn_in(window, async move |editor, cx| {
14633            let project_transaction = rename.await?;
14634            Self::open_project_transaction(
14635                &editor,
14636                workspace,
14637                project_transaction,
14638                format!("Rename: {}{}", old_name, new_name),
14639                cx,
14640            )
14641            .await?;
14642
14643            editor.update(cx, |editor, cx| {
14644                editor.refresh_document_highlights(cx);
14645            })?;
14646            Ok(())
14647        }))
14648    }
14649
14650    fn take_rename(
14651        &mut self,
14652        moving_cursor: bool,
14653        window: &mut Window,
14654        cx: &mut Context<Self>,
14655    ) -> Option<RenameState> {
14656        let rename = self.pending_rename.take()?;
14657        if rename.editor.focus_handle(cx).is_focused(window) {
14658            window.focus(&self.focus_handle);
14659        }
14660
14661        self.remove_blocks(
14662            [rename.block_id].into_iter().collect(),
14663            Some(Autoscroll::fit()),
14664            cx,
14665        );
14666        self.clear_highlights::<Rename>(cx);
14667        self.show_local_selections = true;
14668
14669        if moving_cursor {
14670            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14671                editor.selections.newest::<usize>(cx).head()
14672            });
14673
14674            // Update the selection to match the position of the selection inside
14675            // the rename editor.
14676            let snapshot = self.buffer.read(cx).read(cx);
14677            let rename_range = rename.range.to_offset(&snapshot);
14678            let cursor_in_editor = snapshot
14679                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14680                .min(rename_range.end);
14681            drop(snapshot);
14682
14683            self.change_selections(None, window, cx, |s| {
14684                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14685            });
14686        } else {
14687            self.refresh_document_highlights(cx);
14688        }
14689
14690        Some(rename)
14691    }
14692
14693    pub fn pending_rename(&self) -> Option<&RenameState> {
14694        self.pending_rename.as_ref()
14695    }
14696
14697    fn format(
14698        &mut self,
14699        _: &Format,
14700        window: &mut Window,
14701        cx: &mut Context<Self>,
14702    ) -> Option<Task<Result<()>>> {
14703        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14704
14705        let project = match &self.project {
14706            Some(project) => project.clone(),
14707            None => return None,
14708        };
14709
14710        Some(self.perform_format(
14711            project,
14712            FormatTrigger::Manual,
14713            FormatTarget::Buffers,
14714            window,
14715            cx,
14716        ))
14717    }
14718
14719    fn format_selections(
14720        &mut self,
14721        _: &FormatSelections,
14722        window: &mut Window,
14723        cx: &mut Context<Self>,
14724    ) -> Option<Task<Result<()>>> {
14725        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14726
14727        let project = match &self.project {
14728            Some(project) => project.clone(),
14729            None => return None,
14730        };
14731
14732        let ranges = self
14733            .selections
14734            .all_adjusted(cx)
14735            .into_iter()
14736            .map(|selection| selection.range())
14737            .collect_vec();
14738
14739        Some(self.perform_format(
14740            project,
14741            FormatTrigger::Manual,
14742            FormatTarget::Ranges(ranges),
14743            window,
14744            cx,
14745        ))
14746    }
14747
14748    fn perform_format(
14749        &mut self,
14750        project: Entity<Project>,
14751        trigger: FormatTrigger,
14752        target: FormatTarget,
14753        window: &mut Window,
14754        cx: &mut Context<Self>,
14755    ) -> Task<Result<()>> {
14756        let buffer = self.buffer.clone();
14757        let (buffers, target) = match target {
14758            FormatTarget::Buffers => {
14759                let mut buffers = buffer.read(cx).all_buffers();
14760                if trigger == FormatTrigger::Save {
14761                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14762                }
14763                (buffers, LspFormatTarget::Buffers)
14764            }
14765            FormatTarget::Ranges(selection_ranges) => {
14766                let multi_buffer = buffer.read(cx);
14767                let snapshot = multi_buffer.read(cx);
14768                let mut buffers = HashSet::default();
14769                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14770                    BTreeMap::new();
14771                for selection_range in selection_ranges {
14772                    for (buffer, buffer_range, _) in
14773                        snapshot.range_to_buffer_ranges(selection_range)
14774                    {
14775                        let buffer_id = buffer.remote_id();
14776                        let start = buffer.anchor_before(buffer_range.start);
14777                        let end = buffer.anchor_after(buffer_range.end);
14778                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14779                        buffer_id_to_ranges
14780                            .entry(buffer_id)
14781                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14782                            .or_insert_with(|| vec![start..end]);
14783                    }
14784                }
14785                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14786            }
14787        };
14788
14789        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14790        let selections_prev = transaction_id_prev
14791            .and_then(|transaction_id_prev| {
14792                // default to selections as they were after the last edit, if we have them,
14793                // instead of how they are now.
14794                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14795                // will take you back to where you made the last edit, instead of staying where you scrolled
14796                self.selection_history
14797                    .transaction(transaction_id_prev)
14798                    .map(|t| t.0.clone())
14799            })
14800            .unwrap_or_else(|| {
14801                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14802                self.selections.disjoint_anchors()
14803            });
14804
14805        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14806        let format = project.update(cx, |project, cx| {
14807            project.format(buffers, target, true, trigger, cx)
14808        });
14809
14810        cx.spawn_in(window, async move |editor, cx| {
14811            let transaction = futures::select_biased! {
14812                transaction = format.log_err().fuse() => transaction,
14813                () = timeout => {
14814                    log::warn!("timed out waiting for formatting");
14815                    None
14816                }
14817            };
14818
14819            buffer
14820                .update(cx, |buffer, cx| {
14821                    if let Some(transaction) = transaction {
14822                        if !buffer.is_singleton() {
14823                            buffer.push_transaction(&transaction.0, cx);
14824                        }
14825                    }
14826                    cx.notify();
14827                })
14828                .ok();
14829
14830            if let Some(transaction_id_now) =
14831                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14832            {
14833                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14834                if has_new_transaction {
14835                    _ = editor.update(cx, |editor, _| {
14836                        editor
14837                            .selection_history
14838                            .insert_transaction(transaction_id_now, selections_prev);
14839                    });
14840                }
14841            }
14842
14843            Ok(())
14844        })
14845    }
14846
14847    fn organize_imports(
14848        &mut self,
14849        _: &OrganizeImports,
14850        window: &mut Window,
14851        cx: &mut Context<Self>,
14852    ) -> Option<Task<Result<()>>> {
14853        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14854        let project = match &self.project {
14855            Some(project) => project.clone(),
14856            None => return None,
14857        };
14858        Some(self.perform_code_action_kind(
14859            project,
14860            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14861            window,
14862            cx,
14863        ))
14864    }
14865
14866    fn perform_code_action_kind(
14867        &mut self,
14868        project: Entity<Project>,
14869        kind: CodeActionKind,
14870        window: &mut Window,
14871        cx: &mut Context<Self>,
14872    ) -> Task<Result<()>> {
14873        let buffer = self.buffer.clone();
14874        let buffers = buffer.read(cx).all_buffers();
14875        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14876        let apply_action = project.update(cx, |project, cx| {
14877            project.apply_code_action_kind(buffers, kind, true, cx)
14878        });
14879        cx.spawn_in(window, async move |_, cx| {
14880            let transaction = futures::select_biased! {
14881                () = timeout => {
14882                    log::warn!("timed out waiting for executing code action");
14883                    None
14884                }
14885                transaction = apply_action.log_err().fuse() => transaction,
14886            };
14887            buffer
14888                .update(cx, |buffer, cx| {
14889                    // check if we need this
14890                    if let Some(transaction) = transaction {
14891                        if !buffer.is_singleton() {
14892                            buffer.push_transaction(&transaction.0, cx);
14893                        }
14894                    }
14895                    cx.notify();
14896                })
14897                .ok();
14898            Ok(())
14899        })
14900    }
14901
14902    fn restart_language_server(
14903        &mut self,
14904        _: &RestartLanguageServer,
14905        _: &mut Window,
14906        cx: &mut Context<Self>,
14907    ) {
14908        if let Some(project) = self.project.clone() {
14909            self.buffer.update(cx, |multi_buffer, cx| {
14910                project.update(cx, |project, cx| {
14911                    project.restart_language_servers_for_buffers(
14912                        multi_buffer.all_buffers().into_iter().collect(),
14913                        cx,
14914                    );
14915                });
14916            })
14917        }
14918    }
14919
14920    fn stop_language_server(
14921        &mut self,
14922        _: &StopLanguageServer,
14923        _: &mut Window,
14924        cx: &mut Context<Self>,
14925    ) {
14926        if let Some(project) = self.project.clone() {
14927            self.buffer.update(cx, |multi_buffer, cx| {
14928                project.update(cx, |project, cx| {
14929                    project.stop_language_servers_for_buffers(
14930                        multi_buffer.all_buffers().into_iter().collect(),
14931                        cx,
14932                    );
14933                    cx.emit(project::Event::RefreshInlayHints);
14934                });
14935            });
14936        }
14937    }
14938
14939    fn cancel_language_server_work(
14940        workspace: &mut Workspace,
14941        _: &actions::CancelLanguageServerWork,
14942        _: &mut Window,
14943        cx: &mut Context<Workspace>,
14944    ) {
14945        let project = workspace.project();
14946        let buffers = workspace
14947            .active_item(cx)
14948            .and_then(|item| item.act_as::<Editor>(cx))
14949            .map_or(HashSet::default(), |editor| {
14950                editor.read(cx).buffer.read(cx).all_buffers()
14951            });
14952        project.update(cx, |project, cx| {
14953            project.cancel_language_server_work_for_buffers(buffers, cx);
14954        });
14955    }
14956
14957    fn show_character_palette(
14958        &mut self,
14959        _: &ShowCharacterPalette,
14960        window: &mut Window,
14961        _: &mut Context<Self>,
14962    ) {
14963        window.show_character_palette();
14964    }
14965
14966    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14967        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14968            let buffer = self.buffer.read(cx).snapshot(cx);
14969            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14970            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14971            let is_valid = buffer
14972                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14973                .any(|entry| {
14974                    entry.diagnostic.is_primary
14975                        && !entry.range.is_empty()
14976                        && entry.range.start == primary_range_start
14977                        && entry.diagnostic.message == active_diagnostics.active_message
14978                });
14979
14980            if !is_valid {
14981                self.dismiss_diagnostics(cx);
14982            }
14983        }
14984    }
14985
14986    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14987        match &self.active_diagnostics {
14988            ActiveDiagnostic::Group(group) => Some(group),
14989            _ => None,
14990        }
14991    }
14992
14993    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14994        self.dismiss_diagnostics(cx);
14995        self.active_diagnostics = ActiveDiagnostic::All;
14996    }
14997
14998    fn activate_diagnostics(
14999        &mut self,
15000        buffer_id: BufferId,
15001        diagnostic: DiagnosticEntry<usize>,
15002        window: &mut Window,
15003        cx: &mut Context<Self>,
15004    ) {
15005        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15006            return;
15007        }
15008        self.dismiss_diagnostics(cx);
15009        let snapshot = self.snapshot(window, cx);
15010        let buffer = self.buffer.read(cx).snapshot(cx);
15011        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15012            return;
15013        };
15014
15015        let diagnostic_group = buffer
15016            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15017            .collect::<Vec<_>>();
15018
15019        let blocks =
15020            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15021
15022        let blocks = self.display_map.update(cx, |display_map, cx| {
15023            display_map.insert_blocks(blocks, cx).into_iter().collect()
15024        });
15025        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15026            active_range: buffer.anchor_before(diagnostic.range.start)
15027                ..buffer.anchor_after(diagnostic.range.end),
15028            active_message: diagnostic.diagnostic.message.clone(),
15029            group_id: diagnostic.diagnostic.group_id,
15030            blocks,
15031        });
15032        cx.notify();
15033    }
15034
15035    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15036        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15037            return;
15038        };
15039
15040        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15041        if let ActiveDiagnostic::Group(group) = prev {
15042            self.display_map.update(cx, |display_map, cx| {
15043                display_map.remove_blocks(group.blocks, cx);
15044            });
15045            cx.notify();
15046        }
15047    }
15048
15049    /// Disable inline diagnostics rendering for this editor.
15050    pub fn disable_inline_diagnostics(&mut self) {
15051        self.inline_diagnostics_enabled = false;
15052        self.inline_diagnostics_update = Task::ready(());
15053        self.inline_diagnostics.clear();
15054    }
15055
15056    pub fn inline_diagnostics_enabled(&self) -> bool {
15057        self.inline_diagnostics_enabled
15058    }
15059
15060    pub fn show_inline_diagnostics(&self) -> bool {
15061        self.show_inline_diagnostics
15062    }
15063
15064    pub fn toggle_inline_diagnostics(
15065        &mut self,
15066        _: &ToggleInlineDiagnostics,
15067        window: &mut Window,
15068        cx: &mut Context<Editor>,
15069    ) {
15070        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15071        self.refresh_inline_diagnostics(false, window, cx);
15072    }
15073
15074    fn refresh_inline_diagnostics(
15075        &mut self,
15076        debounce: bool,
15077        window: &mut Window,
15078        cx: &mut Context<Self>,
15079    ) {
15080        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15081            self.inline_diagnostics_update = Task::ready(());
15082            self.inline_diagnostics.clear();
15083            return;
15084        }
15085
15086        let debounce_ms = ProjectSettings::get_global(cx)
15087            .diagnostics
15088            .inline
15089            .update_debounce_ms;
15090        let debounce = if debounce && debounce_ms > 0 {
15091            Some(Duration::from_millis(debounce_ms))
15092        } else {
15093            None
15094        };
15095        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15096            let editor = editor.upgrade().unwrap();
15097
15098            if let Some(debounce) = debounce {
15099                cx.background_executor().timer(debounce).await;
15100            }
15101            let Some(snapshot) = editor
15102                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15103                .ok()
15104            else {
15105                return;
15106            };
15107
15108            let new_inline_diagnostics = cx
15109                .background_spawn(async move {
15110                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15111                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15112                        let message = diagnostic_entry
15113                            .diagnostic
15114                            .message
15115                            .split_once('\n')
15116                            .map(|(line, _)| line)
15117                            .map(SharedString::new)
15118                            .unwrap_or_else(|| {
15119                                SharedString::from(diagnostic_entry.diagnostic.message)
15120                            });
15121                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15122                        let (Ok(i) | Err(i)) = inline_diagnostics
15123                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15124                        inline_diagnostics.insert(
15125                            i,
15126                            (
15127                                start_anchor,
15128                                InlineDiagnostic {
15129                                    message,
15130                                    group_id: diagnostic_entry.diagnostic.group_id,
15131                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15132                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15133                                    severity: diagnostic_entry.diagnostic.severity,
15134                                },
15135                            ),
15136                        );
15137                    }
15138                    inline_diagnostics
15139                })
15140                .await;
15141
15142            editor
15143                .update(cx, |editor, cx| {
15144                    editor.inline_diagnostics = new_inline_diagnostics;
15145                    cx.notify();
15146                })
15147                .ok();
15148        });
15149    }
15150
15151    pub fn set_selections_from_remote(
15152        &mut self,
15153        selections: Vec<Selection<Anchor>>,
15154        pending_selection: Option<Selection<Anchor>>,
15155        window: &mut Window,
15156        cx: &mut Context<Self>,
15157    ) {
15158        let old_cursor_position = self.selections.newest_anchor().head();
15159        self.selections.change_with(cx, |s| {
15160            s.select_anchors(selections);
15161            if let Some(pending_selection) = pending_selection {
15162                s.set_pending(pending_selection, SelectMode::Character);
15163            } else {
15164                s.clear_pending();
15165            }
15166        });
15167        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15168    }
15169
15170    fn push_to_selection_history(&mut self) {
15171        self.selection_history.push(SelectionHistoryEntry {
15172            selections: self.selections.disjoint_anchors(),
15173            select_next_state: self.select_next_state.clone(),
15174            select_prev_state: self.select_prev_state.clone(),
15175            add_selections_state: self.add_selections_state.clone(),
15176        });
15177    }
15178
15179    pub fn transact(
15180        &mut self,
15181        window: &mut Window,
15182        cx: &mut Context<Self>,
15183        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15184    ) -> Option<TransactionId> {
15185        self.start_transaction_at(Instant::now(), window, cx);
15186        update(self, window, cx);
15187        self.end_transaction_at(Instant::now(), cx)
15188    }
15189
15190    pub fn start_transaction_at(
15191        &mut self,
15192        now: Instant,
15193        window: &mut Window,
15194        cx: &mut Context<Self>,
15195    ) {
15196        self.end_selection(window, cx);
15197        if let Some(tx_id) = self
15198            .buffer
15199            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15200        {
15201            self.selection_history
15202                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15203            cx.emit(EditorEvent::TransactionBegun {
15204                transaction_id: tx_id,
15205            })
15206        }
15207    }
15208
15209    pub fn end_transaction_at(
15210        &mut self,
15211        now: Instant,
15212        cx: &mut Context<Self>,
15213    ) -> Option<TransactionId> {
15214        if let Some(transaction_id) = self
15215            .buffer
15216            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15217        {
15218            if let Some((_, end_selections)) =
15219                self.selection_history.transaction_mut(transaction_id)
15220            {
15221                *end_selections = Some(self.selections.disjoint_anchors());
15222            } else {
15223                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15224            }
15225
15226            cx.emit(EditorEvent::Edited { transaction_id });
15227            Some(transaction_id)
15228        } else {
15229            None
15230        }
15231    }
15232
15233    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15234        if self.selection_mark_mode {
15235            self.change_selections(None, window, cx, |s| {
15236                s.move_with(|_, sel| {
15237                    sel.collapse_to(sel.head(), SelectionGoal::None);
15238                });
15239            })
15240        }
15241        self.selection_mark_mode = true;
15242        cx.notify();
15243    }
15244
15245    pub fn swap_selection_ends(
15246        &mut self,
15247        _: &actions::SwapSelectionEnds,
15248        window: &mut Window,
15249        cx: &mut Context<Self>,
15250    ) {
15251        self.change_selections(None, window, cx, |s| {
15252            s.move_with(|_, sel| {
15253                if sel.start != sel.end {
15254                    sel.reversed = !sel.reversed
15255                }
15256            });
15257        });
15258        self.request_autoscroll(Autoscroll::newest(), cx);
15259        cx.notify();
15260    }
15261
15262    pub fn toggle_fold(
15263        &mut self,
15264        _: &actions::ToggleFold,
15265        window: &mut Window,
15266        cx: &mut Context<Self>,
15267    ) {
15268        if self.is_singleton(cx) {
15269            let selection = self.selections.newest::<Point>(cx);
15270
15271            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15272            let range = if selection.is_empty() {
15273                let point = selection.head().to_display_point(&display_map);
15274                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15275                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15276                    .to_point(&display_map);
15277                start..end
15278            } else {
15279                selection.range()
15280            };
15281            if display_map.folds_in_range(range).next().is_some() {
15282                self.unfold_lines(&Default::default(), window, cx)
15283            } else {
15284                self.fold(&Default::default(), window, cx)
15285            }
15286        } else {
15287            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15288            let buffer_ids: HashSet<_> = self
15289                .selections
15290                .disjoint_anchor_ranges()
15291                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15292                .collect();
15293
15294            let should_unfold = buffer_ids
15295                .iter()
15296                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15297
15298            for buffer_id in buffer_ids {
15299                if should_unfold {
15300                    self.unfold_buffer(buffer_id, cx);
15301                } else {
15302                    self.fold_buffer(buffer_id, cx);
15303                }
15304            }
15305        }
15306    }
15307
15308    pub fn toggle_fold_recursive(
15309        &mut self,
15310        _: &actions::ToggleFoldRecursive,
15311        window: &mut Window,
15312        cx: &mut Context<Self>,
15313    ) {
15314        let selection = self.selections.newest::<Point>(cx);
15315
15316        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15317        let range = if selection.is_empty() {
15318            let point = selection.head().to_display_point(&display_map);
15319            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15320            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15321                .to_point(&display_map);
15322            start..end
15323        } else {
15324            selection.range()
15325        };
15326        if display_map.folds_in_range(range).next().is_some() {
15327            self.unfold_recursive(&Default::default(), window, cx)
15328        } else {
15329            self.fold_recursive(&Default::default(), window, cx)
15330        }
15331    }
15332
15333    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15334        if self.is_singleton(cx) {
15335            let mut to_fold = Vec::new();
15336            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15337            let selections = self.selections.all_adjusted(cx);
15338
15339            for selection in selections {
15340                let range = selection.range().sorted();
15341                let buffer_start_row = range.start.row;
15342
15343                if range.start.row != range.end.row {
15344                    let mut found = false;
15345                    let mut row = range.start.row;
15346                    while row <= range.end.row {
15347                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15348                        {
15349                            found = true;
15350                            row = crease.range().end.row + 1;
15351                            to_fold.push(crease);
15352                        } else {
15353                            row += 1
15354                        }
15355                    }
15356                    if found {
15357                        continue;
15358                    }
15359                }
15360
15361                for row in (0..=range.start.row).rev() {
15362                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15363                        if crease.range().end.row >= buffer_start_row {
15364                            to_fold.push(crease);
15365                            if row <= range.start.row {
15366                                break;
15367                            }
15368                        }
15369                    }
15370                }
15371            }
15372
15373            self.fold_creases(to_fold, true, window, cx);
15374        } else {
15375            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15376            let buffer_ids = self
15377                .selections
15378                .disjoint_anchor_ranges()
15379                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15380                .collect::<HashSet<_>>();
15381            for buffer_id in buffer_ids {
15382                self.fold_buffer(buffer_id, cx);
15383            }
15384        }
15385    }
15386
15387    fn fold_at_level(
15388        &mut self,
15389        fold_at: &FoldAtLevel,
15390        window: &mut Window,
15391        cx: &mut Context<Self>,
15392    ) {
15393        if !self.buffer.read(cx).is_singleton() {
15394            return;
15395        }
15396
15397        let fold_at_level = fold_at.0;
15398        let snapshot = self.buffer.read(cx).snapshot(cx);
15399        let mut to_fold = Vec::new();
15400        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15401
15402        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15403            while start_row < end_row {
15404                match self
15405                    .snapshot(window, cx)
15406                    .crease_for_buffer_row(MultiBufferRow(start_row))
15407                {
15408                    Some(crease) => {
15409                        let nested_start_row = crease.range().start.row + 1;
15410                        let nested_end_row = crease.range().end.row;
15411
15412                        if current_level < fold_at_level {
15413                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15414                        } else if current_level == fold_at_level {
15415                            to_fold.push(crease);
15416                        }
15417
15418                        start_row = nested_end_row + 1;
15419                    }
15420                    None => start_row += 1,
15421                }
15422            }
15423        }
15424
15425        self.fold_creases(to_fold, true, window, cx);
15426    }
15427
15428    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15429        if self.buffer.read(cx).is_singleton() {
15430            let mut fold_ranges = Vec::new();
15431            let snapshot = self.buffer.read(cx).snapshot(cx);
15432
15433            for row in 0..snapshot.max_row().0 {
15434                if let Some(foldable_range) = self
15435                    .snapshot(window, cx)
15436                    .crease_for_buffer_row(MultiBufferRow(row))
15437                {
15438                    fold_ranges.push(foldable_range);
15439                }
15440            }
15441
15442            self.fold_creases(fold_ranges, true, window, cx);
15443        } else {
15444            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15445                editor
15446                    .update_in(cx, |editor, _, cx| {
15447                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15448                            editor.fold_buffer(buffer_id, cx);
15449                        }
15450                    })
15451                    .ok();
15452            });
15453        }
15454    }
15455
15456    pub fn fold_function_bodies(
15457        &mut self,
15458        _: &actions::FoldFunctionBodies,
15459        window: &mut Window,
15460        cx: &mut Context<Self>,
15461    ) {
15462        let snapshot = self.buffer.read(cx).snapshot(cx);
15463
15464        let ranges = snapshot
15465            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15466            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15467            .collect::<Vec<_>>();
15468
15469        let creases = ranges
15470            .into_iter()
15471            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15472            .collect();
15473
15474        self.fold_creases(creases, true, window, cx);
15475    }
15476
15477    pub fn fold_recursive(
15478        &mut self,
15479        _: &actions::FoldRecursive,
15480        window: &mut Window,
15481        cx: &mut Context<Self>,
15482    ) {
15483        let mut to_fold = Vec::new();
15484        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15485        let selections = self.selections.all_adjusted(cx);
15486
15487        for selection in selections {
15488            let range = selection.range().sorted();
15489            let buffer_start_row = range.start.row;
15490
15491            if range.start.row != range.end.row {
15492                let mut found = false;
15493                for row in range.start.row..=range.end.row {
15494                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15495                        found = true;
15496                        to_fold.push(crease);
15497                    }
15498                }
15499                if found {
15500                    continue;
15501                }
15502            }
15503
15504            for row in (0..=range.start.row).rev() {
15505                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15506                    if crease.range().end.row >= buffer_start_row {
15507                        to_fold.push(crease);
15508                    } else {
15509                        break;
15510                    }
15511                }
15512            }
15513        }
15514
15515        self.fold_creases(to_fold, true, window, cx);
15516    }
15517
15518    pub fn fold_at(
15519        &mut self,
15520        buffer_row: MultiBufferRow,
15521        window: &mut Window,
15522        cx: &mut Context<Self>,
15523    ) {
15524        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15525
15526        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15527            let autoscroll = self
15528                .selections
15529                .all::<Point>(cx)
15530                .iter()
15531                .any(|selection| crease.range().overlaps(&selection.range()));
15532
15533            self.fold_creases(vec![crease], autoscroll, window, cx);
15534        }
15535    }
15536
15537    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15538        if self.is_singleton(cx) {
15539            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15540            let buffer = &display_map.buffer_snapshot;
15541            let selections = self.selections.all::<Point>(cx);
15542            let ranges = selections
15543                .iter()
15544                .map(|s| {
15545                    let range = s.display_range(&display_map).sorted();
15546                    let mut start = range.start.to_point(&display_map);
15547                    let mut end = range.end.to_point(&display_map);
15548                    start.column = 0;
15549                    end.column = buffer.line_len(MultiBufferRow(end.row));
15550                    start..end
15551                })
15552                .collect::<Vec<_>>();
15553
15554            self.unfold_ranges(&ranges, true, true, cx);
15555        } else {
15556            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15557            let buffer_ids = self
15558                .selections
15559                .disjoint_anchor_ranges()
15560                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15561                .collect::<HashSet<_>>();
15562            for buffer_id in buffer_ids {
15563                self.unfold_buffer(buffer_id, cx);
15564            }
15565        }
15566    }
15567
15568    pub fn unfold_recursive(
15569        &mut self,
15570        _: &UnfoldRecursive,
15571        _window: &mut Window,
15572        cx: &mut Context<Self>,
15573    ) {
15574        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15575        let selections = self.selections.all::<Point>(cx);
15576        let ranges = selections
15577            .iter()
15578            .map(|s| {
15579                let mut range = s.display_range(&display_map).sorted();
15580                *range.start.column_mut() = 0;
15581                *range.end.column_mut() = display_map.line_len(range.end.row());
15582                let start = range.start.to_point(&display_map);
15583                let end = range.end.to_point(&display_map);
15584                start..end
15585            })
15586            .collect::<Vec<_>>();
15587
15588        self.unfold_ranges(&ranges, true, true, cx);
15589    }
15590
15591    pub fn unfold_at(
15592        &mut self,
15593        buffer_row: MultiBufferRow,
15594        _window: &mut Window,
15595        cx: &mut Context<Self>,
15596    ) {
15597        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15598
15599        let intersection_range = Point::new(buffer_row.0, 0)
15600            ..Point::new(
15601                buffer_row.0,
15602                display_map.buffer_snapshot.line_len(buffer_row),
15603            );
15604
15605        let autoscroll = self
15606            .selections
15607            .all::<Point>(cx)
15608            .iter()
15609            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15610
15611        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15612    }
15613
15614    pub fn unfold_all(
15615        &mut self,
15616        _: &actions::UnfoldAll,
15617        _window: &mut Window,
15618        cx: &mut Context<Self>,
15619    ) {
15620        if self.buffer.read(cx).is_singleton() {
15621            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15622            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15623        } else {
15624            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15625                editor
15626                    .update(cx, |editor, cx| {
15627                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15628                            editor.unfold_buffer(buffer_id, cx);
15629                        }
15630                    })
15631                    .ok();
15632            });
15633        }
15634    }
15635
15636    pub fn fold_selected_ranges(
15637        &mut self,
15638        _: &FoldSelectedRanges,
15639        window: &mut Window,
15640        cx: &mut Context<Self>,
15641    ) {
15642        let selections = self.selections.all_adjusted(cx);
15643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15644        let ranges = selections
15645            .into_iter()
15646            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15647            .collect::<Vec<_>>();
15648        self.fold_creases(ranges, true, window, cx);
15649    }
15650
15651    pub fn fold_ranges<T: ToOffset + Clone>(
15652        &mut self,
15653        ranges: Vec<Range<T>>,
15654        auto_scroll: bool,
15655        window: &mut Window,
15656        cx: &mut Context<Self>,
15657    ) {
15658        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15659        let ranges = ranges
15660            .into_iter()
15661            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15662            .collect::<Vec<_>>();
15663        self.fold_creases(ranges, auto_scroll, window, cx);
15664    }
15665
15666    pub fn fold_creases<T: ToOffset + Clone>(
15667        &mut self,
15668        creases: Vec<Crease<T>>,
15669        auto_scroll: bool,
15670        _window: &mut Window,
15671        cx: &mut Context<Self>,
15672    ) {
15673        if creases.is_empty() {
15674            return;
15675        }
15676
15677        let mut buffers_affected = HashSet::default();
15678        let multi_buffer = self.buffer().read(cx);
15679        for crease in &creases {
15680            if let Some((_, buffer, _)) =
15681                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15682            {
15683                buffers_affected.insert(buffer.read(cx).remote_id());
15684            };
15685        }
15686
15687        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15688
15689        if auto_scroll {
15690            self.request_autoscroll(Autoscroll::fit(), cx);
15691        }
15692
15693        cx.notify();
15694
15695        self.scrollbar_marker_state.dirty = true;
15696        self.folds_did_change(cx);
15697    }
15698
15699    /// Removes any folds whose ranges intersect any of the given ranges.
15700    pub fn unfold_ranges<T: ToOffset + Clone>(
15701        &mut self,
15702        ranges: &[Range<T>],
15703        inclusive: bool,
15704        auto_scroll: bool,
15705        cx: &mut Context<Self>,
15706    ) {
15707        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15708            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15709        });
15710        self.folds_did_change(cx);
15711    }
15712
15713    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15714        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15715            return;
15716        }
15717        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15718        self.display_map.update(cx, |display_map, cx| {
15719            display_map.fold_buffers([buffer_id], cx)
15720        });
15721        cx.emit(EditorEvent::BufferFoldToggled {
15722            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15723            folded: true,
15724        });
15725        cx.notify();
15726    }
15727
15728    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15729        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15730            return;
15731        }
15732        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15733        self.display_map.update(cx, |display_map, cx| {
15734            display_map.unfold_buffers([buffer_id], cx);
15735        });
15736        cx.emit(EditorEvent::BufferFoldToggled {
15737            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15738            folded: false,
15739        });
15740        cx.notify();
15741    }
15742
15743    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15744        self.display_map.read(cx).is_buffer_folded(buffer)
15745    }
15746
15747    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15748        self.display_map.read(cx).folded_buffers()
15749    }
15750
15751    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15752        self.display_map.update(cx, |display_map, cx| {
15753            display_map.disable_header_for_buffer(buffer_id, cx);
15754        });
15755        cx.notify();
15756    }
15757
15758    /// Removes any folds with the given ranges.
15759    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15760        &mut self,
15761        ranges: &[Range<T>],
15762        type_id: TypeId,
15763        auto_scroll: bool,
15764        cx: &mut Context<Self>,
15765    ) {
15766        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15767            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15768        });
15769        self.folds_did_change(cx);
15770    }
15771
15772    fn remove_folds_with<T: ToOffset + Clone>(
15773        &mut self,
15774        ranges: &[Range<T>],
15775        auto_scroll: bool,
15776        cx: &mut Context<Self>,
15777        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15778    ) {
15779        if ranges.is_empty() {
15780            return;
15781        }
15782
15783        let mut buffers_affected = HashSet::default();
15784        let multi_buffer = self.buffer().read(cx);
15785        for range in ranges {
15786            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15787                buffers_affected.insert(buffer.read(cx).remote_id());
15788            };
15789        }
15790
15791        self.display_map.update(cx, update);
15792
15793        if auto_scroll {
15794            self.request_autoscroll(Autoscroll::fit(), cx);
15795        }
15796
15797        cx.notify();
15798        self.scrollbar_marker_state.dirty = true;
15799        self.active_indent_guides_state.dirty = true;
15800    }
15801
15802    pub fn update_fold_widths(
15803        &mut self,
15804        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15805        cx: &mut Context<Self>,
15806    ) -> bool {
15807        self.display_map
15808            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15809    }
15810
15811    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15812        self.display_map.read(cx).fold_placeholder.clone()
15813    }
15814
15815    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15816        self.buffer.update(cx, |buffer, cx| {
15817            buffer.set_all_diff_hunks_expanded(cx);
15818        });
15819    }
15820
15821    pub fn expand_all_diff_hunks(
15822        &mut self,
15823        _: &ExpandAllDiffHunks,
15824        _window: &mut Window,
15825        cx: &mut Context<Self>,
15826    ) {
15827        self.buffer.update(cx, |buffer, cx| {
15828            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15829        });
15830    }
15831
15832    pub fn toggle_selected_diff_hunks(
15833        &mut self,
15834        _: &ToggleSelectedDiffHunks,
15835        _window: &mut Window,
15836        cx: &mut Context<Self>,
15837    ) {
15838        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15839        self.toggle_diff_hunks_in_ranges(ranges, cx);
15840    }
15841
15842    pub fn diff_hunks_in_ranges<'a>(
15843        &'a self,
15844        ranges: &'a [Range<Anchor>],
15845        buffer: &'a MultiBufferSnapshot,
15846    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15847        ranges.iter().flat_map(move |range| {
15848            let end_excerpt_id = range.end.excerpt_id;
15849            let range = range.to_point(buffer);
15850            let mut peek_end = range.end;
15851            if range.end.row < buffer.max_row().0 {
15852                peek_end = Point::new(range.end.row + 1, 0);
15853            }
15854            buffer
15855                .diff_hunks_in_range(range.start..peek_end)
15856                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15857        })
15858    }
15859
15860    pub fn has_stageable_diff_hunks_in_ranges(
15861        &self,
15862        ranges: &[Range<Anchor>],
15863        snapshot: &MultiBufferSnapshot,
15864    ) -> bool {
15865        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15866        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15867    }
15868
15869    pub fn toggle_staged_selected_diff_hunks(
15870        &mut self,
15871        _: &::git::ToggleStaged,
15872        _: &mut Window,
15873        cx: &mut Context<Self>,
15874    ) {
15875        let snapshot = self.buffer.read(cx).snapshot(cx);
15876        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15877        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15878        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15879    }
15880
15881    pub fn set_render_diff_hunk_controls(
15882        &mut self,
15883        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15884        cx: &mut Context<Self>,
15885    ) {
15886        self.render_diff_hunk_controls = render_diff_hunk_controls;
15887        cx.notify();
15888    }
15889
15890    pub fn stage_and_next(
15891        &mut self,
15892        _: &::git::StageAndNext,
15893        window: &mut Window,
15894        cx: &mut Context<Self>,
15895    ) {
15896        self.do_stage_or_unstage_and_next(true, window, cx);
15897    }
15898
15899    pub fn unstage_and_next(
15900        &mut self,
15901        _: &::git::UnstageAndNext,
15902        window: &mut Window,
15903        cx: &mut Context<Self>,
15904    ) {
15905        self.do_stage_or_unstage_and_next(false, window, cx);
15906    }
15907
15908    pub fn stage_or_unstage_diff_hunks(
15909        &mut self,
15910        stage: bool,
15911        ranges: Vec<Range<Anchor>>,
15912        cx: &mut Context<Self>,
15913    ) {
15914        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15915        cx.spawn(async move |this, cx| {
15916            task.await?;
15917            this.update(cx, |this, cx| {
15918                let snapshot = this.buffer.read(cx).snapshot(cx);
15919                let chunk_by = this
15920                    .diff_hunks_in_ranges(&ranges, &snapshot)
15921                    .chunk_by(|hunk| hunk.buffer_id);
15922                for (buffer_id, hunks) in &chunk_by {
15923                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15924                }
15925            })
15926        })
15927        .detach_and_log_err(cx);
15928    }
15929
15930    fn save_buffers_for_ranges_if_needed(
15931        &mut self,
15932        ranges: &[Range<Anchor>],
15933        cx: &mut Context<Editor>,
15934    ) -> Task<Result<()>> {
15935        let multibuffer = self.buffer.read(cx);
15936        let snapshot = multibuffer.read(cx);
15937        let buffer_ids: HashSet<_> = ranges
15938            .iter()
15939            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15940            .collect();
15941        drop(snapshot);
15942
15943        let mut buffers = HashSet::default();
15944        for buffer_id in buffer_ids {
15945            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15946                let buffer = buffer_entity.read(cx);
15947                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15948                {
15949                    buffers.insert(buffer_entity);
15950                }
15951            }
15952        }
15953
15954        if let Some(project) = &self.project {
15955            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15956        } else {
15957            Task::ready(Ok(()))
15958        }
15959    }
15960
15961    fn do_stage_or_unstage_and_next(
15962        &mut self,
15963        stage: bool,
15964        window: &mut Window,
15965        cx: &mut Context<Self>,
15966    ) {
15967        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15968
15969        if ranges.iter().any(|range| range.start != range.end) {
15970            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15971            return;
15972        }
15973
15974        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15975        let snapshot = self.snapshot(window, cx);
15976        let position = self.selections.newest::<Point>(cx).head();
15977        let mut row = snapshot
15978            .buffer_snapshot
15979            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15980            .find(|hunk| hunk.row_range.start.0 > position.row)
15981            .map(|hunk| hunk.row_range.start);
15982
15983        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15984        // Outside of the project diff editor, wrap around to the beginning.
15985        if !all_diff_hunks_expanded {
15986            row = row.or_else(|| {
15987                snapshot
15988                    .buffer_snapshot
15989                    .diff_hunks_in_range(Point::zero()..position)
15990                    .find(|hunk| hunk.row_range.end.0 < position.row)
15991                    .map(|hunk| hunk.row_range.start)
15992            });
15993        }
15994
15995        if let Some(row) = row {
15996            let destination = Point::new(row.0, 0);
15997            let autoscroll = Autoscroll::center();
15998
15999            self.unfold_ranges(&[destination..destination], false, false, cx);
16000            self.change_selections(Some(autoscroll), window, cx, |s| {
16001                s.select_ranges([destination..destination]);
16002            });
16003        }
16004    }
16005
16006    fn do_stage_or_unstage(
16007        &self,
16008        stage: bool,
16009        buffer_id: BufferId,
16010        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16011        cx: &mut App,
16012    ) -> Option<()> {
16013        let project = self.project.as_ref()?;
16014        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16015        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16016        let buffer_snapshot = buffer.read(cx).snapshot();
16017        let file_exists = buffer_snapshot
16018            .file()
16019            .is_some_and(|file| file.disk_state().exists());
16020        diff.update(cx, |diff, cx| {
16021            diff.stage_or_unstage_hunks(
16022                stage,
16023                &hunks
16024                    .map(|hunk| buffer_diff::DiffHunk {
16025                        buffer_range: hunk.buffer_range,
16026                        diff_base_byte_range: hunk.diff_base_byte_range,
16027                        secondary_status: hunk.secondary_status,
16028                        range: Point::zero()..Point::zero(), // unused
16029                    })
16030                    .collect::<Vec<_>>(),
16031                &buffer_snapshot,
16032                file_exists,
16033                cx,
16034            )
16035        });
16036        None
16037    }
16038
16039    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16040        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16041        self.buffer
16042            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16043    }
16044
16045    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16046        self.buffer.update(cx, |buffer, cx| {
16047            let ranges = vec![Anchor::min()..Anchor::max()];
16048            if !buffer.all_diff_hunks_expanded()
16049                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16050            {
16051                buffer.collapse_diff_hunks(ranges, cx);
16052                true
16053            } else {
16054                false
16055            }
16056        })
16057    }
16058
16059    fn toggle_diff_hunks_in_ranges(
16060        &mut self,
16061        ranges: Vec<Range<Anchor>>,
16062        cx: &mut Context<Editor>,
16063    ) {
16064        self.buffer.update(cx, |buffer, cx| {
16065            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16066            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16067        })
16068    }
16069
16070    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16071        self.buffer.update(cx, |buffer, cx| {
16072            let snapshot = buffer.snapshot(cx);
16073            let excerpt_id = range.end.excerpt_id;
16074            let point_range = range.to_point(&snapshot);
16075            let expand = !buffer.single_hunk_is_expanded(range, cx);
16076            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16077        })
16078    }
16079
16080    pub(crate) fn apply_all_diff_hunks(
16081        &mut self,
16082        _: &ApplyAllDiffHunks,
16083        window: &mut Window,
16084        cx: &mut Context<Self>,
16085    ) {
16086        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16087
16088        let buffers = self.buffer.read(cx).all_buffers();
16089        for branch_buffer in buffers {
16090            branch_buffer.update(cx, |branch_buffer, cx| {
16091                branch_buffer.merge_into_base(Vec::new(), cx);
16092            });
16093        }
16094
16095        if let Some(project) = self.project.clone() {
16096            self.save(true, project, window, cx).detach_and_log_err(cx);
16097        }
16098    }
16099
16100    pub(crate) fn apply_selected_diff_hunks(
16101        &mut self,
16102        _: &ApplyDiffHunk,
16103        window: &mut Window,
16104        cx: &mut Context<Self>,
16105    ) {
16106        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16107        let snapshot = self.snapshot(window, cx);
16108        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16109        let mut ranges_by_buffer = HashMap::default();
16110        self.transact(window, cx, |editor, _window, cx| {
16111            for hunk in hunks {
16112                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16113                    ranges_by_buffer
16114                        .entry(buffer.clone())
16115                        .or_insert_with(Vec::new)
16116                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16117                }
16118            }
16119
16120            for (buffer, ranges) in ranges_by_buffer {
16121                buffer.update(cx, |buffer, cx| {
16122                    buffer.merge_into_base(ranges, cx);
16123                });
16124            }
16125        });
16126
16127        if let Some(project) = self.project.clone() {
16128            self.save(true, project, window, cx).detach_and_log_err(cx);
16129        }
16130    }
16131
16132    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16133        if hovered != self.gutter_hovered {
16134            self.gutter_hovered = hovered;
16135            cx.notify();
16136        }
16137    }
16138
16139    pub fn insert_blocks(
16140        &mut self,
16141        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16142        autoscroll: Option<Autoscroll>,
16143        cx: &mut Context<Self>,
16144    ) -> Vec<CustomBlockId> {
16145        let blocks = self
16146            .display_map
16147            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16148        if let Some(autoscroll) = autoscroll {
16149            self.request_autoscroll(autoscroll, cx);
16150        }
16151        cx.notify();
16152        blocks
16153    }
16154
16155    pub fn resize_blocks(
16156        &mut self,
16157        heights: HashMap<CustomBlockId, u32>,
16158        autoscroll: Option<Autoscroll>,
16159        cx: &mut Context<Self>,
16160    ) {
16161        self.display_map
16162            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16163        if let Some(autoscroll) = autoscroll {
16164            self.request_autoscroll(autoscroll, cx);
16165        }
16166        cx.notify();
16167    }
16168
16169    pub fn replace_blocks(
16170        &mut self,
16171        renderers: HashMap<CustomBlockId, RenderBlock>,
16172        autoscroll: Option<Autoscroll>,
16173        cx: &mut Context<Self>,
16174    ) {
16175        self.display_map
16176            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16177        if let Some(autoscroll) = autoscroll {
16178            self.request_autoscroll(autoscroll, cx);
16179        }
16180        cx.notify();
16181    }
16182
16183    pub fn remove_blocks(
16184        &mut self,
16185        block_ids: HashSet<CustomBlockId>,
16186        autoscroll: Option<Autoscroll>,
16187        cx: &mut Context<Self>,
16188    ) {
16189        self.display_map.update(cx, |display_map, cx| {
16190            display_map.remove_blocks(block_ids, cx)
16191        });
16192        if let Some(autoscroll) = autoscroll {
16193            self.request_autoscroll(autoscroll, cx);
16194        }
16195        cx.notify();
16196    }
16197
16198    pub fn row_for_block(
16199        &self,
16200        block_id: CustomBlockId,
16201        cx: &mut Context<Self>,
16202    ) -> Option<DisplayRow> {
16203        self.display_map
16204            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16205    }
16206
16207    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16208        self.focused_block = Some(focused_block);
16209    }
16210
16211    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16212        self.focused_block.take()
16213    }
16214
16215    pub fn insert_creases(
16216        &mut self,
16217        creases: impl IntoIterator<Item = Crease<Anchor>>,
16218        cx: &mut Context<Self>,
16219    ) -> Vec<CreaseId> {
16220        self.display_map
16221            .update(cx, |map, cx| map.insert_creases(creases, cx))
16222    }
16223
16224    pub fn remove_creases(
16225        &mut self,
16226        ids: impl IntoIterator<Item = CreaseId>,
16227        cx: &mut Context<Self>,
16228    ) -> Vec<(CreaseId, Range<Anchor>)> {
16229        self.display_map
16230            .update(cx, |map, cx| map.remove_creases(ids, cx))
16231    }
16232
16233    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16234        self.display_map
16235            .update(cx, |map, cx| map.snapshot(cx))
16236            .longest_row()
16237    }
16238
16239    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16240        self.display_map
16241            .update(cx, |map, cx| map.snapshot(cx))
16242            .max_point()
16243    }
16244
16245    pub fn text(&self, cx: &App) -> String {
16246        self.buffer.read(cx).read(cx).text()
16247    }
16248
16249    pub fn is_empty(&self, cx: &App) -> bool {
16250        self.buffer.read(cx).read(cx).is_empty()
16251    }
16252
16253    pub fn text_option(&self, cx: &App) -> Option<String> {
16254        let text = self.text(cx);
16255        let text = text.trim();
16256
16257        if text.is_empty() {
16258            return None;
16259        }
16260
16261        Some(text.to_string())
16262    }
16263
16264    pub fn set_text(
16265        &mut self,
16266        text: impl Into<Arc<str>>,
16267        window: &mut Window,
16268        cx: &mut Context<Self>,
16269    ) {
16270        self.transact(window, cx, |this, _, cx| {
16271            this.buffer
16272                .read(cx)
16273                .as_singleton()
16274                .expect("you can only call set_text on editors for singleton buffers")
16275                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16276        });
16277    }
16278
16279    pub fn display_text(&self, cx: &mut App) -> String {
16280        self.display_map
16281            .update(cx, |map, cx| map.snapshot(cx))
16282            .text()
16283    }
16284
16285    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16286        let mut wrap_guides = smallvec::smallvec![];
16287
16288        if self.show_wrap_guides == Some(false) {
16289            return wrap_guides;
16290        }
16291
16292        let settings = self.buffer.read(cx).language_settings(cx);
16293        if settings.show_wrap_guides {
16294            match self.soft_wrap_mode(cx) {
16295                SoftWrap::Column(soft_wrap) => {
16296                    wrap_guides.push((soft_wrap as usize, true));
16297                }
16298                SoftWrap::Bounded(soft_wrap) => {
16299                    wrap_guides.push((soft_wrap as usize, true));
16300                }
16301                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16302            }
16303            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16304        }
16305
16306        wrap_guides
16307    }
16308
16309    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16310        let settings = self.buffer.read(cx).language_settings(cx);
16311        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16312        match mode {
16313            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16314                SoftWrap::None
16315            }
16316            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16317            language_settings::SoftWrap::PreferredLineLength => {
16318                SoftWrap::Column(settings.preferred_line_length)
16319            }
16320            language_settings::SoftWrap::Bounded => {
16321                SoftWrap::Bounded(settings.preferred_line_length)
16322            }
16323        }
16324    }
16325
16326    pub fn set_soft_wrap_mode(
16327        &mut self,
16328        mode: language_settings::SoftWrap,
16329
16330        cx: &mut Context<Self>,
16331    ) {
16332        self.soft_wrap_mode_override = Some(mode);
16333        cx.notify();
16334    }
16335
16336    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16337        self.hard_wrap = hard_wrap;
16338        cx.notify();
16339    }
16340
16341    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16342        self.text_style_refinement = Some(style);
16343    }
16344
16345    /// called by the Element so we know what style we were most recently rendered with.
16346    pub(crate) fn set_style(
16347        &mut self,
16348        style: EditorStyle,
16349        window: &mut Window,
16350        cx: &mut Context<Self>,
16351    ) {
16352        let rem_size = window.rem_size();
16353        self.display_map.update(cx, |map, cx| {
16354            map.set_font(
16355                style.text.font(),
16356                style.text.font_size.to_pixels(rem_size),
16357                cx,
16358            )
16359        });
16360        self.style = Some(style);
16361    }
16362
16363    pub fn style(&self) -> Option<&EditorStyle> {
16364        self.style.as_ref()
16365    }
16366
16367    // Called by the element. This method is not designed to be called outside of the editor
16368    // element's layout code because it does not notify when rewrapping is computed synchronously.
16369    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16370        self.display_map
16371            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16372    }
16373
16374    pub fn set_soft_wrap(&mut self) {
16375        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16376    }
16377
16378    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16379        if self.soft_wrap_mode_override.is_some() {
16380            self.soft_wrap_mode_override.take();
16381        } else {
16382            let soft_wrap = match self.soft_wrap_mode(cx) {
16383                SoftWrap::GitDiff => return,
16384                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16385                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16386                    language_settings::SoftWrap::None
16387                }
16388            };
16389            self.soft_wrap_mode_override = Some(soft_wrap);
16390        }
16391        cx.notify();
16392    }
16393
16394    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16395        let Some(workspace) = self.workspace() else {
16396            return;
16397        };
16398        let fs = workspace.read(cx).app_state().fs.clone();
16399        let current_show = TabBarSettings::get_global(cx).show;
16400        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16401            setting.show = Some(!current_show);
16402        });
16403    }
16404
16405    pub fn toggle_indent_guides(
16406        &mut self,
16407        _: &ToggleIndentGuides,
16408        _: &mut Window,
16409        cx: &mut Context<Self>,
16410    ) {
16411        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16412            self.buffer
16413                .read(cx)
16414                .language_settings(cx)
16415                .indent_guides
16416                .enabled
16417        });
16418        self.show_indent_guides = Some(!currently_enabled);
16419        cx.notify();
16420    }
16421
16422    fn should_show_indent_guides(&self) -> Option<bool> {
16423        self.show_indent_guides
16424    }
16425
16426    pub fn toggle_line_numbers(
16427        &mut self,
16428        _: &ToggleLineNumbers,
16429        _: &mut Window,
16430        cx: &mut Context<Self>,
16431    ) {
16432        let mut editor_settings = EditorSettings::get_global(cx).clone();
16433        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16434        EditorSettings::override_global(editor_settings, cx);
16435    }
16436
16437    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16438        if let Some(show_line_numbers) = self.show_line_numbers {
16439            return show_line_numbers;
16440        }
16441        EditorSettings::get_global(cx).gutter.line_numbers
16442    }
16443
16444    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16445        self.use_relative_line_numbers
16446            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16447    }
16448
16449    pub fn toggle_relative_line_numbers(
16450        &mut self,
16451        _: &ToggleRelativeLineNumbers,
16452        _: &mut Window,
16453        cx: &mut Context<Self>,
16454    ) {
16455        let is_relative = self.should_use_relative_line_numbers(cx);
16456        self.set_relative_line_number(Some(!is_relative), cx)
16457    }
16458
16459    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16460        self.use_relative_line_numbers = is_relative;
16461        cx.notify();
16462    }
16463
16464    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16465        self.show_gutter = show_gutter;
16466        cx.notify();
16467    }
16468
16469    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16470        self.show_scrollbars = show_scrollbars;
16471        cx.notify();
16472    }
16473
16474    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16475        self.show_line_numbers = Some(show_line_numbers);
16476        cx.notify();
16477    }
16478
16479    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16480        self.disable_expand_excerpt_buttons = true;
16481        cx.notify();
16482    }
16483
16484    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16485        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16486        cx.notify();
16487    }
16488
16489    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16490        self.show_code_actions = Some(show_code_actions);
16491        cx.notify();
16492    }
16493
16494    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16495        self.show_runnables = Some(show_runnables);
16496        cx.notify();
16497    }
16498
16499    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16500        self.show_breakpoints = Some(show_breakpoints);
16501        cx.notify();
16502    }
16503
16504    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16505        if self.display_map.read(cx).masked != masked {
16506            self.display_map.update(cx, |map, _| map.masked = masked);
16507        }
16508        cx.notify()
16509    }
16510
16511    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16512        self.show_wrap_guides = Some(show_wrap_guides);
16513        cx.notify();
16514    }
16515
16516    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16517        self.show_indent_guides = Some(show_indent_guides);
16518        cx.notify();
16519    }
16520
16521    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16522        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16523            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16524                if let Some(dir) = file.abs_path(cx).parent() {
16525                    return Some(dir.to_owned());
16526                }
16527            }
16528
16529            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16530                return Some(project_path.path.to_path_buf());
16531            }
16532        }
16533
16534        None
16535    }
16536
16537    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16538        self.active_excerpt(cx)?
16539            .1
16540            .read(cx)
16541            .file()
16542            .and_then(|f| f.as_local())
16543    }
16544
16545    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16546        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16547            let buffer = buffer.read(cx);
16548            if let Some(project_path) = buffer.project_path(cx) {
16549                let project = self.project.as_ref()?.read(cx);
16550                project.absolute_path(&project_path, cx)
16551            } else {
16552                buffer
16553                    .file()
16554                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16555            }
16556        })
16557    }
16558
16559    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16560        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16561            let project_path = buffer.read(cx).project_path(cx)?;
16562            let project = self.project.as_ref()?.read(cx);
16563            let entry = project.entry_for_path(&project_path, cx)?;
16564            let path = entry.path.to_path_buf();
16565            Some(path)
16566        })
16567    }
16568
16569    pub fn reveal_in_finder(
16570        &mut self,
16571        _: &RevealInFileManager,
16572        _window: &mut Window,
16573        cx: &mut Context<Self>,
16574    ) {
16575        if let Some(target) = self.target_file(cx) {
16576            cx.reveal_path(&target.abs_path(cx));
16577        }
16578    }
16579
16580    pub fn copy_path(
16581        &mut self,
16582        _: &zed_actions::workspace::CopyPath,
16583        _window: &mut Window,
16584        cx: &mut Context<Self>,
16585    ) {
16586        if let Some(path) = self.target_file_abs_path(cx) {
16587            if let Some(path) = path.to_str() {
16588                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16589            }
16590        }
16591    }
16592
16593    pub fn copy_relative_path(
16594        &mut self,
16595        _: &zed_actions::workspace::CopyRelativePath,
16596        _window: &mut Window,
16597        cx: &mut Context<Self>,
16598    ) {
16599        if let Some(path) = self.target_file_path(cx) {
16600            if let Some(path) = path.to_str() {
16601                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16602            }
16603        }
16604    }
16605
16606    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16607        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16608            buffer.read(cx).project_path(cx)
16609        } else {
16610            None
16611        }
16612    }
16613
16614    // Returns true if the editor handled a go-to-line request
16615    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16616        maybe!({
16617            let breakpoint_store = self.breakpoint_store.as_ref()?;
16618
16619            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16620            else {
16621                self.clear_row_highlights::<ActiveDebugLine>();
16622                return None;
16623            };
16624
16625            let position = active_stack_frame.position;
16626            let buffer_id = position.buffer_id?;
16627            let snapshot = self
16628                .project
16629                .as_ref()?
16630                .read(cx)
16631                .buffer_for_id(buffer_id, cx)?
16632                .read(cx)
16633                .snapshot();
16634
16635            let mut handled = false;
16636            for (id, ExcerptRange { context, .. }) in
16637                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16638            {
16639                if context.start.cmp(&position, &snapshot).is_ge()
16640                    || context.end.cmp(&position, &snapshot).is_lt()
16641                {
16642                    continue;
16643                }
16644                let snapshot = self.buffer.read(cx).snapshot(cx);
16645                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16646
16647                handled = true;
16648                self.clear_row_highlights::<ActiveDebugLine>();
16649                self.go_to_line::<ActiveDebugLine>(
16650                    multibuffer_anchor,
16651                    Some(cx.theme().colors().editor_debugger_active_line_background),
16652                    window,
16653                    cx,
16654                );
16655
16656                cx.notify();
16657            }
16658
16659            handled.then_some(())
16660        })
16661        .is_some()
16662    }
16663
16664    pub fn copy_file_name_without_extension(
16665        &mut self,
16666        _: &CopyFileNameWithoutExtension,
16667        _: &mut Window,
16668        cx: &mut Context<Self>,
16669    ) {
16670        if let Some(file) = self.target_file(cx) {
16671            if let Some(file_stem) = file.path().file_stem() {
16672                if let Some(name) = file_stem.to_str() {
16673                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16674                }
16675            }
16676        }
16677    }
16678
16679    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16680        if let Some(file) = self.target_file(cx) {
16681            if let Some(file_name) = file.path().file_name() {
16682                if let Some(name) = file_name.to_str() {
16683                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16684                }
16685            }
16686        }
16687    }
16688
16689    pub fn toggle_git_blame(
16690        &mut self,
16691        _: &::git::Blame,
16692        window: &mut Window,
16693        cx: &mut Context<Self>,
16694    ) {
16695        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16696
16697        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16698            self.start_git_blame(true, window, cx);
16699        }
16700
16701        cx.notify();
16702    }
16703
16704    pub fn toggle_git_blame_inline(
16705        &mut self,
16706        _: &ToggleGitBlameInline,
16707        window: &mut Window,
16708        cx: &mut Context<Self>,
16709    ) {
16710        self.toggle_git_blame_inline_internal(true, window, cx);
16711        cx.notify();
16712    }
16713
16714    pub fn open_git_blame_commit(
16715        &mut self,
16716        _: &OpenGitBlameCommit,
16717        window: &mut Window,
16718        cx: &mut Context<Self>,
16719    ) {
16720        self.open_git_blame_commit_internal(window, cx);
16721    }
16722
16723    fn open_git_blame_commit_internal(
16724        &mut self,
16725        window: &mut Window,
16726        cx: &mut Context<Self>,
16727    ) -> Option<()> {
16728        let blame = self.blame.as_ref()?;
16729        let snapshot = self.snapshot(window, cx);
16730        let cursor = self.selections.newest::<Point>(cx).head();
16731        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16732        let blame_entry = blame
16733            .update(cx, |blame, cx| {
16734                blame
16735                    .blame_for_rows(
16736                        &[RowInfo {
16737                            buffer_id: Some(buffer.remote_id()),
16738                            buffer_row: Some(point.row),
16739                            ..Default::default()
16740                        }],
16741                        cx,
16742                    )
16743                    .next()
16744            })
16745            .flatten()?;
16746        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16747        let repo = blame.read(cx).repository(cx)?;
16748        let workspace = self.workspace()?.downgrade();
16749        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16750        None
16751    }
16752
16753    pub fn git_blame_inline_enabled(&self) -> bool {
16754        self.git_blame_inline_enabled
16755    }
16756
16757    pub fn toggle_selection_menu(
16758        &mut self,
16759        _: &ToggleSelectionMenu,
16760        _: &mut Window,
16761        cx: &mut Context<Self>,
16762    ) {
16763        self.show_selection_menu = self
16764            .show_selection_menu
16765            .map(|show_selections_menu| !show_selections_menu)
16766            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16767
16768        cx.notify();
16769    }
16770
16771    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16772        self.show_selection_menu
16773            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16774    }
16775
16776    fn start_git_blame(
16777        &mut self,
16778        user_triggered: bool,
16779        window: &mut Window,
16780        cx: &mut Context<Self>,
16781    ) {
16782        if let Some(project) = self.project.as_ref() {
16783            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16784                return;
16785            };
16786
16787            if buffer.read(cx).file().is_none() {
16788                return;
16789            }
16790
16791            let focused = self.focus_handle(cx).contains_focused(window, cx);
16792
16793            let project = project.clone();
16794            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16795            self.blame_subscription =
16796                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16797            self.blame = Some(blame);
16798        }
16799    }
16800
16801    fn toggle_git_blame_inline_internal(
16802        &mut self,
16803        user_triggered: bool,
16804        window: &mut Window,
16805        cx: &mut Context<Self>,
16806    ) {
16807        if self.git_blame_inline_enabled {
16808            self.git_blame_inline_enabled = false;
16809            self.show_git_blame_inline = false;
16810            self.show_git_blame_inline_delay_task.take();
16811        } else {
16812            self.git_blame_inline_enabled = true;
16813            self.start_git_blame_inline(user_triggered, window, cx);
16814        }
16815
16816        cx.notify();
16817    }
16818
16819    fn start_git_blame_inline(
16820        &mut self,
16821        user_triggered: bool,
16822        window: &mut Window,
16823        cx: &mut Context<Self>,
16824    ) {
16825        self.start_git_blame(user_triggered, window, cx);
16826
16827        if ProjectSettings::get_global(cx)
16828            .git
16829            .inline_blame_delay()
16830            .is_some()
16831        {
16832            self.start_inline_blame_timer(window, cx);
16833        } else {
16834            self.show_git_blame_inline = true
16835        }
16836    }
16837
16838    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16839        self.blame.as_ref()
16840    }
16841
16842    pub fn show_git_blame_gutter(&self) -> bool {
16843        self.show_git_blame_gutter
16844    }
16845
16846    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16847        self.show_git_blame_gutter && self.has_blame_entries(cx)
16848    }
16849
16850    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16851        self.show_git_blame_inline
16852            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16853            && !self.newest_selection_head_on_empty_line(cx)
16854            && self.has_blame_entries(cx)
16855    }
16856
16857    fn has_blame_entries(&self, cx: &App) -> bool {
16858        self.blame()
16859            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16860    }
16861
16862    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16863        let cursor_anchor = self.selections.newest_anchor().head();
16864
16865        let snapshot = self.buffer.read(cx).snapshot(cx);
16866        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16867
16868        snapshot.line_len(buffer_row) == 0
16869    }
16870
16871    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16872        let buffer_and_selection = maybe!({
16873            let selection = self.selections.newest::<Point>(cx);
16874            let selection_range = selection.range();
16875
16876            let multi_buffer = self.buffer().read(cx);
16877            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16878            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16879
16880            let (buffer, range, _) = if selection.reversed {
16881                buffer_ranges.first()
16882            } else {
16883                buffer_ranges.last()
16884            }?;
16885
16886            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16887                ..text::ToPoint::to_point(&range.end, &buffer).row;
16888            Some((
16889                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16890                selection,
16891            ))
16892        });
16893
16894        let Some((buffer, selection)) = buffer_and_selection else {
16895            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16896        };
16897
16898        let Some(project) = self.project.as_ref() else {
16899            return Task::ready(Err(anyhow!("editor does not have project")));
16900        };
16901
16902        project.update(cx, |project, cx| {
16903            project.get_permalink_to_line(&buffer, selection, cx)
16904        })
16905    }
16906
16907    pub fn copy_permalink_to_line(
16908        &mut self,
16909        _: &CopyPermalinkToLine,
16910        window: &mut Window,
16911        cx: &mut Context<Self>,
16912    ) {
16913        let permalink_task = self.get_permalink_to_line(cx);
16914        let workspace = self.workspace();
16915
16916        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16917            Ok(permalink) => {
16918                cx.update(|_, cx| {
16919                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16920                })
16921                .ok();
16922            }
16923            Err(err) => {
16924                let message = format!("Failed to copy permalink: {err}");
16925
16926                Err::<(), anyhow::Error>(err).log_err();
16927
16928                if let Some(workspace) = workspace {
16929                    workspace
16930                        .update_in(cx, |workspace, _, cx| {
16931                            struct CopyPermalinkToLine;
16932
16933                            workspace.show_toast(
16934                                Toast::new(
16935                                    NotificationId::unique::<CopyPermalinkToLine>(),
16936                                    message,
16937                                ),
16938                                cx,
16939                            )
16940                        })
16941                        .ok();
16942                }
16943            }
16944        })
16945        .detach();
16946    }
16947
16948    pub fn copy_file_location(
16949        &mut self,
16950        _: &CopyFileLocation,
16951        _: &mut Window,
16952        cx: &mut Context<Self>,
16953    ) {
16954        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16955        if let Some(file) = self.target_file(cx) {
16956            if let Some(path) = file.path().to_str() {
16957                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16958            }
16959        }
16960    }
16961
16962    pub fn open_permalink_to_line(
16963        &mut self,
16964        _: &OpenPermalinkToLine,
16965        window: &mut Window,
16966        cx: &mut Context<Self>,
16967    ) {
16968        let permalink_task = self.get_permalink_to_line(cx);
16969        let workspace = self.workspace();
16970
16971        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16972            Ok(permalink) => {
16973                cx.update(|_, cx| {
16974                    cx.open_url(permalink.as_ref());
16975                })
16976                .ok();
16977            }
16978            Err(err) => {
16979                let message = format!("Failed to open permalink: {err}");
16980
16981                Err::<(), anyhow::Error>(err).log_err();
16982
16983                if let Some(workspace) = workspace {
16984                    workspace
16985                        .update(cx, |workspace, cx| {
16986                            struct OpenPermalinkToLine;
16987
16988                            workspace.show_toast(
16989                                Toast::new(
16990                                    NotificationId::unique::<OpenPermalinkToLine>(),
16991                                    message,
16992                                ),
16993                                cx,
16994                            )
16995                        })
16996                        .ok();
16997                }
16998            }
16999        })
17000        .detach();
17001    }
17002
17003    pub fn insert_uuid_v4(
17004        &mut self,
17005        _: &InsertUuidV4,
17006        window: &mut Window,
17007        cx: &mut Context<Self>,
17008    ) {
17009        self.insert_uuid(UuidVersion::V4, window, cx);
17010    }
17011
17012    pub fn insert_uuid_v7(
17013        &mut self,
17014        _: &InsertUuidV7,
17015        window: &mut Window,
17016        cx: &mut Context<Self>,
17017    ) {
17018        self.insert_uuid(UuidVersion::V7, window, cx);
17019    }
17020
17021    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17022        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17023        self.transact(window, cx, |this, window, cx| {
17024            let edits = this
17025                .selections
17026                .all::<Point>(cx)
17027                .into_iter()
17028                .map(|selection| {
17029                    let uuid = match version {
17030                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17031                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17032                    };
17033
17034                    (selection.range(), uuid.to_string())
17035                });
17036            this.edit(edits, cx);
17037            this.refresh_inline_completion(true, false, window, cx);
17038        });
17039    }
17040
17041    pub fn open_selections_in_multibuffer(
17042        &mut self,
17043        _: &OpenSelectionsInMultibuffer,
17044        window: &mut Window,
17045        cx: &mut Context<Self>,
17046    ) {
17047        let multibuffer = self.buffer.read(cx);
17048
17049        let Some(buffer) = multibuffer.as_singleton() else {
17050            return;
17051        };
17052
17053        let Some(workspace) = self.workspace() else {
17054            return;
17055        };
17056
17057        let locations = self
17058            .selections
17059            .disjoint_anchors()
17060            .iter()
17061            .map(|range| Location {
17062                buffer: buffer.clone(),
17063                range: range.start.text_anchor..range.end.text_anchor,
17064            })
17065            .collect::<Vec<_>>();
17066
17067        let title = multibuffer.title(cx).to_string();
17068
17069        cx.spawn_in(window, async move |_, cx| {
17070            workspace.update_in(cx, |workspace, window, cx| {
17071                Self::open_locations_in_multibuffer(
17072                    workspace,
17073                    locations,
17074                    format!("Selections for '{title}'"),
17075                    false,
17076                    MultibufferSelectionMode::All,
17077                    window,
17078                    cx,
17079                );
17080            })
17081        })
17082        .detach();
17083    }
17084
17085    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17086    /// last highlight added will be used.
17087    ///
17088    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17089    pub fn highlight_rows<T: 'static>(
17090        &mut self,
17091        range: Range<Anchor>,
17092        color: Hsla,
17093        options: RowHighlightOptions,
17094        cx: &mut Context<Self>,
17095    ) {
17096        let snapshot = self.buffer().read(cx).snapshot(cx);
17097        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17098        let ix = row_highlights.binary_search_by(|highlight| {
17099            Ordering::Equal
17100                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17101                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17102        });
17103
17104        if let Err(mut ix) = ix {
17105            let index = post_inc(&mut self.highlight_order);
17106
17107            // If this range intersects with the preceding highlight, then merge it with
17108            // the preceding highlight. Otherwise insert a new highlight.
17109            let mut merged = false;
17110            if ix > 0 {
17111                let prev_highlight = &mut row_highlights[ix - 1];
17112                if prev_highlight
17113                    .range
17114                    .end
17115                    .cmp(&range.start, &snapshot)
17116                    .is_ge()
17117                {
17118                    ix -= 1;
17119                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17120                        prev_highlight.range.end = range.end;
17121                    }
17122                    merged = true;
17123                    prev_highlight.index = index;
17124                    prev_highlight.color = color;
17125                    prev_highlight.options = options;
17126                }
17127            }
17128
17129            if !merged {
17130                row_highlights.insert(
17131                    ix,
17132                    RowHighlight {
17133                        range: range.clone(),
17134                        index,
17135                        color,
17136                        options,
17137                        type_id: TypeId::of::<T>(),
17138                    },
17139                );
17140            }
17141
17142            // If any of the following highlights intersect with this one, merge them.
17143            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17144                let highlight = &row_highlights[ix];
17145                if next_highlight
17146                    .range
17147                    .start
17148                    .cmp(&highlight.range.end, &snapshot)
17149                    .is_le()
17150                {
17151                    if next_highlight
17152                        .range
17153                        .end
17154                        .cmp(&highlight.range.end, &snapshot)
17155                        .is_gt()
17156                    {
17157                        row_highlights[ix].range.end = next_highlight.range.end;
17158                    }
17159                    row_highlights.remove(ix + 1);
17160                } else {
17161                    break;
17162                }
17163            }
17164        }
17165    }
17166
17167    /// Remove any highlighted row ranges of the given type that intersect the
17168    /// given ranges.
17169    pub fn remove_highlighted_rows<T: 'static>(
17170        &mut self,
17171        ranges_to_remove: Vec<Range<Anchor>>,
17172        cx: &mut Context<Self>,
17173    ) {
17174        let snapshot = self.buffer().read(cx).snapshot(cx);
17175        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17176        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17177        row_highlights.retain(|highlight| {
17178            while let Some(range_to_remove) = ranges_to_remove.peek() {
17179                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17180                    Ordering::Less | Ordering::Equal => {
17181                        ranges_to_remove.next();
17182                    }
17183                    Ordering::Greater => {
17184                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17185                            Ordering::Less | Ordering::Equal => {
17186                                return false;
17187                            }
17188                            Ordering::Greater => break,
17189                        }
17190                    }
17191                }
17192            }
17193
17194            true
17195        })
17196    }
17197
17198    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17199    pub fn clear_row_highlights<T: 'static>(&mut self) {
17200        self.highlighted_rows.remove(&TypeId::of::<T>());
17201    }
17202
17203    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17204    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17205        self.highlighted_rows
17206            .get(&TypeId::of::<T>())
17207            .map_or(&[] as &[_], |vec| vec.as_slice())
17208            .iter()
17209            .map(|highlight| (highlight.range.clone(), highlight.color))
17210    }
17211
17212    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17213    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17214    /// Allows to ignore certain kinds of highlights.
17215    pub fn highlighted_display_rows(
17216        &self,
17217        window: &mut Window,
17218        cx: &mut App,
17219    ) -> BTreeMap<DisplayRow, LineHighlight> {
17220        let snapshot = self.snapshot(window, cx);
17221        let mut used_highlight_orders = HashMap::default();
17222        self.highlighted_rows
17223            .iter()
17224            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17225            .fold(
17226                BTreeMap::<DisplayRow, LineHighlight>::new(),
17227                |mut unique_rows, highlight| {
17228                    let start = highlight.range.start.to_display_point(&snapshot);
17229                    let end = highlight.range.end.to_display_point(&snapshot);
17230                    let start_row = start.row().0;
17231                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17232                        && end.column() == 0
17233                    {
17234                        end.row().0.saturating_sub(1)
17235                    } else {
17236                        end.row().0
17237                    };
17238                    for row in start_row..=end_row {
17239                        let used_index =
17240                            used_highlight_orders.entry(row).or_insert(highlight.index);
17241                        if highlight.index >= *used_index {
17242                            *used_index = highlight.index;
17243                            unique_rows.insert(
17244                                DisplayRow(row),
17245                                LineHighlight {
17246                                    include_gutter: highlight.options.include_gutter,
17247                                    border: None,
17248                                    background: highlight.color.into(),
17249                                    type_id: Some(highlight.type_id),
17250                                },
17251                            );
17252                        }
17253                    }
17254                    unique_rows
17255                },
17256            )
17257    }
17258
17259    pub fn highlighted_display_row_for_autoscroll(
17260        &self,
17261        snapshot: &DisplaySnapshot,
17262    ) -> Option<DisplayRow> {
17263        self.highlighted_rows
17264            .values()
17265            .flat_map(|highlighted_rows| highlighted_rows.iter())
17266            .filter_map(|highlight| {
17267                if highlight.options.autoscroll {
17268                    Some(highlight.range.start.to_display_point(snapshot).row())
17269                } else {
17270                    None
17271                }
17272            })
17273            .min()
17274    }
17275
17276    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17277        self.highlight_background::<SearchWithinRange>(
17278            ranges,
17279            |colors| colors.editor_document_highlight_read_background,
17280            cx,
17281        )
17282    }
17283
17284    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17285        self.breadcrumb_header = Some(new_header);
17286    }
17287
17288    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17289        self.clear_background_highlights::<SearchWithinRange>(cx);
17290    }
17291
17292    pub fn highlight_background<T: 'static>(
17293        &mut self,
17294        ranges: &[Range<Anchor>],
17295        color_fetcher: fn(&ThemeColors) -> Hsla,
17296        cx: &mut Context<Self>,
17297    ) {
17298        self.background_highlights
17299            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17300        self.scrollbar_marker_state.dirty = true;
17301        cx.notify();
17302    }
17303
17304    pub fn clear_background_highlights<T: 'static>(
17305        &mut self,
17306        cx: &mut Context<Self>,
17307    ) -> Option<BackgroundHighlight> {
17308        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17309        if !text_highlights.1.is_empty() {
17310            self.scrollbar_marker_state.dirty = true;
17311            cx.notify();
17312        }
17313        Some(text_highlights)
17314    }
17315
17316    pub fn highlight_gutter<T: 'static>(
17317        &mut self,
17318        ranges: &[Range<Anchor>],
17319        color_fetcher: fn(&App) -> Hsla,
17320        cx: &mut Context<Self>,
17321    ) {
17322        self.gutter_highlights
17323            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17324        cx.notify();
17325    }
17326
17327    pub fn clear_gutter_highlights<T: 'static>(
17328        &mut self,
17329        cx: &mut Context<Self>,
17330    ) -> Option<GutterHighlight> {
17331        cx.notify();
17332        self.gutter_highlights.remove(&TypeId::of::<T>())
17333    }
17334
17335    #[cfg(feature = "test-support")]
17336    pub fn all_text_background_highlights(
17337        &self,
17338        window: &mut Window,
17339        cx: &mut Context<Self>,
17340    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17341        let snapshot = self.snapshot(window, cx);
17342        let buffer = &snapshot.buffer_snapshot;
17343        let start = buffer.anchor_before(0);
17344        let end = buffer.anchor_after(buffer.len());
17345        let theme = cx.theme().colors();
17346        self.background_highlights_in_range(start..end, &snapshot, theme)
17347    }
17348
17349    #[cfg(feature = "test-support")]
17350    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17351        let snapshot = self.buffer().read(cx).snapshot(cx);
17352
17353        let highlights = self
17354            .background_highlights
17355            .get(&TypeId::of::<items::BufferSearchHighlights>());
17356
17357        if let Some((_color, ranges)) = highlights {
17358            ranges
17359                .iter()
17360                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17361                .collect_vec()
17362        } else {
17363            vec![]
17364        }
17365    }
17366
17367    fn document_highlights_for_position<'a>(
17368        &'a self,
17369        position: Anchor,
17370        buffer: &'a MultiBufferSnapshot,
17371    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17372        let read_highlights = self
17373            .background_highlights
17374            .get(&TypeId::of::<DocumentHighlightRead>())
17375            .map(|h| &h.1);
17376        let write_highlights = self
17377            .background_highlights
17378            .get(&TypeId::of::<DocumentHighlightWrite>())
17379            .map(|h| &h.1);
17380        let left_position = position.bias_left(buffer);
17381        let right_position = position.bias_right(buffer);
17382        read_highlights
17383            .into_iter()
17384            .chain(write_highlights)
17385            .flat_map(move |ranges| {
17386                let start_ix = match ranges.binary_search_by(|probe| {
17387                    let cmp = probe.end.cmp(&left_position, buffer);
17388                    if cmp.is_ge() {
17389                        Ordering::Greater
17390                    } else {
17391                        Ordering::Less
17392                    }
17393                }) {
17394                    Ok(i) | Err(i) => i,
17395                };
17396
17397                ranges[start_ix..]
17398                    .iter()
17399                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17400            })
17401    }
17402
17403    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17404        self.background_highlights
17405            .get(&TypeId::of::<T>())
17406            .map_or(false, |(_, highlights)| !highlights.is_empty())
17407    }
17408
17409    pub fn background_highlights_in_range(
17410        &self,
17411        search_range: Range<Anchor>,
17412        display_snapshot: &DisplaySnapshot,
17413        theme: &ThemeColors,
17414    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17415        let mut results = Vec::new();
17416        for (color_fetcher, ranges) in self.background_highlights.values() {
17417            let color = color_fetcher(theme);
17418            let start_ix = match ranges.binary_search_by(|probe| {
17419                let cmp = probe
17420                    .end
17421                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17422                if cmp.is_gt() {
17423                    Ordering::Greater
17424                } else {
17425                    Ordering::Less
17426                }
17427            }) {
17428                Ok(i) | Err(i) => i,
17429            };
17430            for range in &ranges[start_ix..] {
17431                if range
17432                    .start
17433                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17434                    .is_ge()
17435                {
17436                    break;
17437                }
17438
17439                let start = range.start.to_display_point(display_snapshot);
17440                let end = range.end.to_display_point(display_snapshot);
17441                results.push((start..end, color))
17442            }
17443        }
17444        results
17445    }
17446
17447    pub fn background_highlight_row_ranges<T: 'static>(
17448        &self,
17449        search_range: Range<Anchor>,
17450        display_snapshot: &DisplaySnapshot,
17451        count: usize,
17452    ) -> Vec<RangeInclusive<DisplayPoint>> {
17453        let mut results = Vec::new();
17454        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17455            return vec![];
17456        };
17457
17458        let start_ix = match ranges.binary_search_by(|probe| {
17459            let cmp = probe
17460                .end
17461                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17462            if cmp.is_gt() {
17463                Ordering::Greater
17464            } else {
17465                Ordering::Less
17466            }
17467        }) {
17468            Ok(i) | Err(i) => i,
17469        };
17470        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17471            if let (Some(start_display), Some(end_display)) = (start, end) {
17472                results.push(
17473                    start_display.to_display_point(display_snapshot)
17474                        ..=end_display.to_display_point(display_snapshot),
17475                );
17476            }
17477        };
17478        let mut start_row: Option<Point> = None;
17479        let mut end_row: Option<Point> = None;
17480        if ranges.len() > count {
17481            return Vec::new();
17482        }
17483        for range in &ranges[start_ix..] {
17484            if range
17485                .start
17486                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17487                .is_ge()
17488            {
17489                break;
17490            }
17491            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17492            if let Some(current_row) = &end_row {
17493                if end.row == current_row.row {
17494                    continue;
17495                }
17496            }
17497            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17498            if start_row.is_none() {
17499                assert_eq!(end_row, None);
17500                start_row = Some(start);
17501                end_row = Some(end);
17502                continue;
17503            }
17504            if let Some(current_end) = end_row.as_mut() {
17505                if start.row > current_end.row + 1 {
17506                    push_region(start_row, end_row);
17507                    start_row = Some(start);
17508                    end_row = Some(end);
17509                } else {
17510                    // Merge two hunks.
17511                    *current_end = end;
17512                }
17513            } else {
17514                unreachable!();
17515            }
17516        }
17517        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17518        push_region(start_row, end_row);
17519        results
17520    }
17521
17522    pub fn gutter_highlights_in_range(
17523        &self,
17524        search_range: Range<Anchor>,
17525        display_snapshot: &DisplaySnapshot,
17526        cx: &App,
17527    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17528        let mut results = Vec::new();
17529        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17530            let color = color_fetcher(cx);
17531            let start_ix = match ranges.binary_search_by(|probe| {
17532                let cmp = probe
17533                    .end
17534                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17535                if cmp.is_gt() {
17536                    Ordering::Greater
17537                } else {
17538                    Ordering::Less
17539                }
17540            }) {
17541                Ok(i) | Err(i) => i,
17542            };
17543            for range in &ranges[start_ix..] {
17544                if range
17545                    .start
17546                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17547                    .is_ge()
17548                {
17549                    break;
17550                }
17551
17552                let start = range.start.to_display_point(display_snapshot);
17553                let end = range.end.to_display_point(display_snapshot);
17554                results.push((start..end, color))
17555            }
17556        }
17557        results
17558    }
17559
17560    /// Get the text ranges corresponding to the redaction query
17561    pub fn redacted_ranges(
17562        &self,
17563        search_range: Range<Anchor>,
17564        display_snapshot: &DisplaySnapshot,
17565        cx: &App,
17566    ) -> Vec<Range<DisplayPoint>> {
17567        display_snapshot
17568            .buffer_snapshot
17569            .redacted_ranges(search_range, |file| {
17570                if let Some(file) = file {
17571                    file.is_private()
17572                        && EditorSettings::get(
17573                            Some(SettingsLocation {
17574                                worktree_id: file.worktree_id(cx),
17575                                path: file.path().as_ref(),
17576                            }),
17577                            cx,
17578                        )
17579                        .redact_private_values
17580                } else {
17581                    false
17582                }
17583            })
17584            .map(|range| {
17585                range.start.to_display_point(display_snapshot)
17586                    ..range.end.to_display_point(display_snapshot)
17587            })
17588            .collect()
17589    }
17590
17591    pub fn highlight_text<T: 'static>(
17592        &mut self,
17593        ranges: Vec<Range<Anchor>>,
17594        style: HighlightStyle,
17595        cx: &mut Context<Self>,
17596    ) {
17597        self.display_map.update(cx, |map, _| {
17598            map.highlight_text(TypeId::of::<T>(), ranges, style)
17599        });
17600        cx.notify();
17601    }
17602
17603    pub(crate) fn highlight_inlays<T: 'static>(
17604        &mut self,
17605        highlights: Vec<InlayHighlight>,
17606        style: HighlightStyle,
17607        cx: &mut Context<Self>,
17608    ) {
17609        self.display_map.update(cx, |map, _| {
17610            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17611        });
17612        cx.notify();
17613    }
17614
17615    pub fn text_highlights<'a, T: 'static>(
17616        &'a self,
17617        cx: &'a App,
17618    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17619        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17620    }
17621
17622    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17623        let cleared = self
17624            .display_map
17625            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17626        if cleared {
17627            cx.notify();
17628        }
17629    }
17630
17631    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17632        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17633            && self.focus_handle.is_focused(window)
17634    }
17635
17636    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17637        self.show_cursor_when_unfocused = is_enabled;
17638        cx.notify();
17639    }
17640
17641    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17642        cx.notify();
17643    }
17644
17645    fn on_debug_session_event(
17646        &mut self,
17647        _session: Entity<Session>,
17648        event: &SessionEvent,
17649        cx: &mut Context<Self>,
17650    ) {
17651        match event {
17652            SessionEvent::InvalidateInlineValue => {
17653                self.refresh_inline_values(cx);
17654            }
17655            _ => {}
17656        }
17657    }
17658
17659    fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17660        let Some(project) = self.project.clone() else {
17661            return;
17662        };
17663        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17664            return;
17665        };
17666        if !self.inline_value_cache.enabled {
17667            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17668            self.splice_inlays(&inlays, Vec::new(), cx);
17669            return;
17670        }
17671
17672        let current_execution_position = self
17673            .highlighted_rows
17674            .get(&TypeId::of::<ActiveDebugLine>())
17675            .and_then(|lines| lines.last().map(|line| line.range.start));
17676
17677        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17678            let snapshot = editor
17679                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17680                .ok()?;
17681
17682            let inline_values = editor
17683                .update(cx, |_, cx| {
17684                    let Some(current_execution_position) = current_execution_position else {
17685                        return Some(Task::ready(Ok(Vec::new())));
17686                    };
17687
17688                    // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17689                    // anchor is in the same buffer
17690                    let range =
17691                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17692                    project.inline_values(buffer, range, cx)
17693                })
17694                .ok()
17695                .flatten()?
17696                .await
17697                .context("refreshing debugger inlays")
17698                .log_err()?;
17699
17700            let (excerpt_id, buffer_id) = snapshot
17701                .excerpts()
17702                .next()
17703                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17704            editor
17705                .update(cx, |editor, cx| {
17706                    let new_inlays = inline_values
17707                        .into_iter()
17708                        .map(|debugger_value| {
17709                            Inlay::debugger_hint(
17710                                post_inc(&mut editor.next_inlay_id),
17711                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17712                                debugger_value.text(),
17713                            )
17714                        })
17715                        .collect::<Vec<_>>();
17716                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17717                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17718
17719                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17720                })
17721                .ok()?;
17722            Some(())
17723        });
17724    }
17725
17726    fn on_buffer_event(
17727        &mut self,
17728        multibuffer: &Entity<MultiBuffer>,
17729        event: &multi_buffer::Event,
17730        window: &mut Window,
17731        cx: &mut Context<Self>,
17732    ) {
17733        match event {
17734            multi_buffer::Event::Edited {
17735                singleton_buffer_edited,
17736                edited_buffer: buffer_edited,
17737            } => {
17738                self.scrollbar_marker_state.dirty = true;
17739                self.active_indent_guides_state.dirty = true;
17740                self.refresh_active_diagnostics(cx);
17741                self.refresh_code_actions(window, cx);
17742                self.refresh_selected_text_highlights(true, window, cx);
17743                refresh_matching_bracket_highlights(self, window, cx);
17744                if self.has_active_inline_completion() {
17745                    self.update_visible_inline_completion(window, cx);
17746                }
17747                if let Some(buffer) = buffer_edited {
17748                    let buffer_id = buffer.read(cx).remote_id();
17749                    if !self.registered_buffers.contains_key(&buffer_id) {
17750                        if let Some(project) = self.project.as_ref() {
17751                            project.update(cx, |project, cx| {
17752                                self.registered_buffers.insert(
17753                                    buffer_id,
17754                                    project.register_buffer_with_language_servers(&buffer, cx),
17755                                );
17756                            })
17757                        }
17758                    }
17759                }
17760                cx.emit(EditorEvent::BufferEdited);
17761                cx.emit(SearchEvent::MatchesInvalidated);
17762                if *singleton_buffer_edited {
17763                    if let Some(project) = &self.project {
17764                        #[allow(clippy::mutable_key_type)]
17765                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17766                            multibuffer
17767                                .all_buffers()
17768                                .into_iter()
17769                                .filter_map(|buffer| {
17770                                    buffer.update(cx, |buffer, cx| {
17771                                        let language = buffer.language()?;
17772                                        let should_discard = project.update(cx, |project, cx| {
17773                                            project.is_local()
17774                                                && !project.has_language_servers_for(buffer, cx)
17775                                        });
17776                                        should_discard.not().then_some(language.clone())
17777                                    })
17778                                })
17779                                .collect::<HashSet<_>>()
17780                        });
17781                        if !languages_affected.is_empty() {
17782                            self.refresh_inlay_hints(
17783                                InlayHintRefreshReason::BufferEdited(languages_affected),
17784                                cx,
17785                            );
17786                        }
17787                    }
17788                }
17789
17790                let Some(project) = &self.project else { return };
17791                let (telemetry, is_via_ssh) = {
17792                    let project = project.read(cx);
17793                    let telemetry = project.client().telemetry().clone();
17794                    let is_via_ssh = project.is_via_ssh();
17795                    (telemetry, is_via_ssh)
17796                };
17797                refresh_linked_ranges(self, window, cx);
17798                telemetry.log_edit_event("editor", is_via_ssh);
17799            }
17800            multi_buffer::Event::ExcerptsAdded {
17801                buffer,
17802                predecessor,
17803                excerpts,
17804            } => {
17805                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17806                let buffer_id = buffer.read(cx).remote_id();
17807                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17808                    if let Some(project) = &self.project {
17809                        update_uncommitted_diff_for_buffer(
17810                            cx.entity(),
17811                            project,
17812                            [buffer.clone()],
17813                            self.buffer.clone(),
17814                            cx,
17815                        )
17816                        .detach();
17817                    }
17818                }
17819                cx.emit(EditorEvent::ExcerptsAdded {
17820                    buffer: buffer.clone(),
17821                    predecessor: *predecessor,
17822                    excerpts: excerpts.clone(),
17823                });
17824                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17825            }
17826            multi_buffer::Event::ExcerptsRemoved {
17827                ids,
17828                removed_buffer_ids,
17829            } => {
17830                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17831                let buffer = self.buffer.read(cx);
17832                self.registered_buffers
17833                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17834                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17835                cx.emit(EditorEvent::ExcerptsRemoved {
17836                    ids: ids.clone(),
17837                    removed_buffer_ids: removed_buffer_ids.clone(),
17838                })
17839            }
17840            multi_buffer::Event::ExcerptsEdited {
17841                excerpt_ids,
17842                buffer_ids,
17843            } => {
17844                self.display_map.update(cx, |map, cx| {
17845                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17846                });
17847                cx.emit(EditorEvent::ExcerptsEdited {
17848                    ids: excerpt_ids.clone(),
17849                })
17850            }
17851            multi_buffer::Event::ExcerptsExpanded { ids } => {
17852                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17853                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17854            }
17855            multi_buffer::Event::Reparsed(buffer_id) => {
17856                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17857                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17858
17859                cx.emit(EditorEvent::Reparsed(*buffer_id));
17860            }
17861            multi_buffer::Event::DiffHunksToggled => {
17862                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17863            }
17864            multi_buffer::Event::LanguageChanged(buffer_id) => {
17865                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17866                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17867                cx.emit(EditorEvent::Reparsed(*buffer_id));
17868                cx.notify();
17869            }
17870            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17871            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17872            multi_buffer::Event::FileHandleChanged
17873            | multi_buffer::Event::Reloaded
17874            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17875            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17876            multi_buffer::Event::DiagnosticsUpdated => {
17877                self.refresh_active_diagnostics(cx);
17878                self.refresh_inline_diagnostics(true, window, cx);
17879                self.scrollbar_marker_state.dirty = true;
17880                cx.notify();
17881            }
17882            _ => {}
17883        };
17884    }
17885
17886    pub fn start_temporary_diff_override(&mut self) {
17887        self.load_diff_task.take();
17888        self.temporary_diff_override = true;
17889    }
17890
17891    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17892        self.temporary_diff_override = false;
17893        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17894        self.buffer.update(cx, |buffer, cx| {
17895            buffer.set_all_diff_hunks_collapsed(cx);
17896        });
17897
17898        if let Some(project) = self.project.clone() {
17899            self.load_diff_task = Some(
17900                update_uncommitted_diff_for_buffer(
17901                    cx.entity(),
17902                    &project,
17903                    self.buffer.read(cx).all_buffers(),
17904                    self.buffer.clone(),
17905                    cx,
17906                )
17907                .shared(),
17908            );
17909        }
17910    }
17911
17912    fn on_display_map_changed(
17913        &mut self,
17914        _: Entity<DisplayMap>,
17915        _: &mut Window,
17916        cx: &mut Context<Self>,
17917    ) {
17918        cx.notify();
17919    }
17920
17921    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17922        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17923        self.update_edit_prediction_settings(cx);
17924        self.refresh_inline_completion(true, false, window, cx);
17925        self.refresh_inlay_hints(
17926            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17927                self.selections.newest_anchor().head(),
17928                &self.buffer.read(cx).snapshot(cx),
17929                cx,
17930            )),
17931            cx,
17932        );
17933
17934        let old_cursor_shape = self.cursor_shape;
17935
17936        {
17937            let editor_settings = EditorSettings::get_global(cx);
17938            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17939            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17940            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17941            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17942        }
17943
17944        if old_cursor_shape != self.cursor_shape {
17945            cx.emit(EditorEvent::CursorShapeChanged);
17946        }
17947
17948        let project_settings = ProjectSettings::get_global(cx);
17949        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17950
17951        if self.mode.is_full() {
17952            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17953            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17954            if self.show_inline_diagnostics != show_inline_diagnostics {
17955                self.show_inline_diagnostics = show_inline_diagnostics;
17956                self.refresh_inline_diagnostics(false, window, cx);
17957            }
17958
17959            if self.git_blame_inline_enabled != inline_blame_enabled {
17960                self.toggle_git_blame_inline_internal(false, window, cx);
17961            }
17962        }
17963
17964        cx.notify();
17965    }
17966
17967    pub fn set_searchable(&mut self, searchable: bool) {
17968        self.searchable = searchable;
17969    }
17970
17971    pub fn searchable(&self) -> bool {
17972        self.searchable
17973    }
17974
17975    fn open_proposed_changes_editor(
17976        &mut self,
17977        _: &OpenProposedChangesEditor,
17978        window: &mut Window,
17979        cx: &mut Context<Self>,
17980    ) {
17981        let Some(workspace) = self.workspace() else {
17982            cx.propagate();
17983            return;
17984        };
17985
17986        let selections = self.selections.all::<usize>(cx);
17987        let multi_buffer = self.buffer.read(cx);
17988        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17989        let mut new_selections_by_buffer = HashMap::default();
17990        for selection in selections {
17991            for (buffer, range, _) in
17992                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17993            {
17994                let mut range = range.to_point(buffer);
17995                range.start.column = 0;
17996                range.end.column = buffer.line_len(range.end.row);
17997                new_selections_by_buffer
17998                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17999                    .or_insert(Vec::new())
18000                    .push(range)
18001            }
18002        }
18003
18004        let proposed_changes_buffers = new_selections_by_buffer
18005            .into_iter()
18006            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18007            .collect::<Vec<_>>();
18008        let proposed_changes_editor = cx.new(|cx| {
18009            ProposedChangesEditor::new(
18010                "Proposed changes",
18011                proposed_changes_buffers,
18012                self.project.clone(),
18013                window,
18014                cx,
18015            )
18016        });
18017
18018        window.defer(cx, move |window, cx| {
18019            workspace.update(cx, |workspace, cx| {
18020                workspace.active_pane().update(cx, |pane, cx| {
18021                    pane.add_item(
18022                        Box::new(proposed_changes_editor),
18023                        true,
18024                        true,
18025                        None,
18026                        window,
18027                        cx,
18028                    );
18029                });
18030            });
18031        });
18032    }
18033
18034    pub fn open_excerpts_in_split(
18035        &mut self,
18036        _: &OpenExcerptsSplit,
18037        window: &mut Window,
18038        cx: &mut Context<Self>,
18039    ) {
18040        self.open_excerpts_common(None, true, window, cx)
18041    }
18042
18043    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18044        self.open_excerpts_common(None, false, window, cx)
18045    }
18046
18047    fn open_excerpts_common(
18048        &mut self,
18049        jump_data: Option<JumpData>,
18050        split: bool,
18051        window: &mut Window,
18052        cx: &mut Context<Self>,
18053    ) {
18054        let Some(workspace) = self.workspace() else {
18055            cx.propagate();
18056            return;
18057        };
18058
18059        if self.buffer.read(cx).is_singleton() {
18060            cx.propagate();
18061            return;
18062        }
18063
18064        let mut new_selections_by_buffer = HashMap::default();
18065        match &jump_data {
18066            Some(JumpData::MultiBufferPoint {
18067                excerpt_id,
18068                position,
18069                anchor,
18070                line_offset_from_top,
18071            }) => {
18072                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18073                if let Some(buffer) = multi_buffer_snapshot
18074                    .buffer_id_for_excerpt(*excerpt_id)
18075                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18076                {
18077                    let buffer_snapshot = buffer.read(cx).snapshot();
18078                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18079                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18080                    } else {
18081                        buffer_snapshot.clip_point(*position, Bias::Left)
18082                    };
18083                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18084                    new_selections_by_buffer.insert(
18085                        buffer,
18086                        (
18087                            vec![jump_to_offset..jump_to_offset],
18088                            Some(*line_offset_from_top),
18089                        ),
18090                    );
18091                }
18092            }
18093            Some(JumpData::MultiBufferRow {
18094                row,
18095                line_offset_from_top,
18096            }) => {
18097                let point = MultiBufferPoint::new(row.0, 0);
18098                if let Some((buffer, buffer_point, _)) =
18099                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18100                {
18101                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18102                    new_selections_by_buffer
18103                        .entry(buffer)
18104                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18105                        .0
18106                        .push(buffer_offset..buffer_offset)
18107                }
18108            }
18109            None => {
18110                let selections = self.selections.all::<usize>(cx);
18111                let multi_buffer = self.buffer.read(cx);
18112                for selection in selections {
18113                    for (snapshot, range, _, anchor) in multi_buffer
18114                        .snapshot(cx)
18115                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18116                    {
18117                        if let Some(anchor) = anchor {
18118                            // selection is in a deleted hunk
18119                            let Some(buffer_id) = anchor.buffer_id else {
18120                                continue;
18121                            };
18122                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18123                                continue;
18124                            };
18125                            let offset = text::ToOffset::to_offset(
18126                                &anchor.text_anchor,
18127                                &buffer_handle.read(cx).snapshot(),
18128                            );
18129                            let range = offset..offset;
18130                            new_selections_by_buffer
18131                                .entry(buffer_handle)
18132                                .or_insert((Vec::new(), None))
18133                                .0
18134                                .push(range)
18135                        } else {
18136                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18137                            else {
18138                                continue;
18139                            };
18140                            new_selections_by_buffer
18141                                .entry(buffer_handle)
18142                                .or_insert((Vec::new(), None))
18143                                .0
18144                                .push(range)
18145                        }
18146                    }
18147                }
18148            }
18149        }
18150
18151        new_selections_by_buffer
18152            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18153
18154        if new_selections_by_buffer.is_empty() {
18155            return;
18156        }
18157
18158        // We defer the pane interaction because we ourselves are a workspace item
18159        // and activating a new item causes the pane to call a method on us reentrantly,
18160        // which panics if we're on the stack.
18161        window.defer(cx, move |window, cx| {
18162            workspace.update(cx, |workspace, cx| {
18163                let pane = if split {
18164                    workspace.adjacent_pane(window, cx)
18165                } else {
18166                    workspace.active_pane().clone()
18167                };
18168
18169                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18170                    let editor = buffer
18171                        .read(cx)
18172                        .file()
18173                        .is_none()
18174                        .then(|| {
18175                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18176                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18177                            // Instead, we try to activate the existing editor in the pane first.
18178                            let (editor, pane_item_index) =
18179                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18180                                    let editor = item.downcast::<Editor>()?;
18181                                    let singleton_buffer =
18182                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18183                                    if singleton_buffer == buffer {
18184                                        Some((editor, i))
18185                                    } else {
18186                                        None
18187                                    }
18188                                })?;
18189                            pane.update(cx, |pane, cx| {
18190                                pane.activate_item(pane_item_index, true, true, window, cx)
18191                            });
18192                            Some(editor)
18193                        })
18194                        .flatten()
18195                        .unwrap_or_else(|| {
18196                            workspace.open_project_item::<Self>(
18197                                pane.clone(),
18198                                buffer,
18199                                true,
18200                                true,
18201                                window,
18202                                cx,
18203                            )
18204                        });
18205
18206                    editor.update(cx, |editor, cx| {
18207                        let autoscroll = match scroll_offset {
18208                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18209                            None => Autoscroll::newest(),
18210                        };
18211                        let nav_history = editor.nav_history.take();
18212                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18213                            s.select_ranges(ranges);
18214                        });
18215                        editor.nav_history = nav_history;
18216                    });
18217                }
18218            })
18219        });
18220    }
18221
18222    // For now, don't allow opening excerpts in buffers that aren't backed by
18223    // regular project files.
18224    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18225        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18226    }
18227
18228    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18229        let snapshot = self.buffer.read(cx).read(cx);
18230        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18231        Some(
18232            ranges
18233                .iter()
18234                .map(move |range| {
18235                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18236                })
18237                .collect(),
18238        )
18239    }
18240
18241    fn selection_replacement_ranges(
18242        &self,
18243        range: Range<OffsetUtf16>,
18244        cx: &mut App,
18245    ) -> Vec<Range<OffsetUtf16>> {
18246        let selections = self.selections.all::<OffsetUtf16>(cx);
18247        let newest_selection = selections
18248            .iter()
18249            .max_by_key(|selection| selection.id)
18250            .unwrap();
18251        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18252        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18253        let snapshot = self.buffer.read(cx).read(cx);
18254        selections
18255            .into_iter()
18256            .map(|mut selection| {
18257                selection.start.0 =
18258                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18259                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18260                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18261                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18262            })
18263            .collect()
18264    }
18265
18266    fn report_editor_event(
18267        &self,
18268        event_type: &'static str,
18269        file_extension: Option<String>,
18270        cx: &App,
18271    ) {
18272        if cfg!(any(test, feature = "test-support")) {
18273            return;
18274        }
18275
18276        let Some(project) = &self.project else { return };
18277
18278        // If None, we are in a file without an extension
18279        let file = self
18280            .buffer
18281            .read(cx)
18282            .as_singleton()
18283            .and_then(|b| b.read(cx).file());
18284        let file_extension = file_extension.or(file
18285            .as_ref()
18286            .and_then(|file| Path::new(file.file_name(cx)).extension())
18287            .and_then(|e| e.to_str())
18288            .map(|a| a.to_string()));
18289
18290        let vim_mode = vim_enabled(cx);
18291
18292        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18293        let copilot_enabled = edit_predictions_provider
18294            == language::language_settings::EditPredictionProvider::Copilot;
18295        let copilot_enabled_for_language = self
18296            .buffer
18297            .read(cx)
18298            .language_settings(cx)
18299            .show_edit_predictions;
18300
18301        let project = project.read(cx);
18302        telemetry::event!(
18303            event_type,
18304            file_extension,
18305            vim_mode,
18306            copilot_enabled,
18307            copilot_enabled_for_language,
18308            edit_predictions_provider,
18309            is_via_ssh = project.is_via_ssh(),
18310        );
18311    }
18312
18313    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18314    /// with each line being an array of {text, highlight} objects.
18315    fn copy_highlight_json(
18316        &mut self,
18317        _: &CopyHighlightJson,
18318        window: &mut Window,
18319        cx: &mut Context<Self>,
18320    ) {
18321        #[derive(Serialize)]
18322        struct Chunk<'a> {
18323            text: String,
18324            highlight: Option<&'a str>,
18325        }
18326
18327        let snapshot = self.buffer.read(cx).snapshot(cx);
18328        let range = self
18329            .selected_text_range(false, window, cx)
18330            .and_then(|selection| {
18331                if selection.range.is_empty() {
18332                    None
18333                } else {
18334                    Some(selection.range)
18335                }
18336            })
18337            .unwrap_or_else(|| 0..snapshot.len());
18338
18339        let chunks = snapshot.chunks(range, true);
18340        let mut lines = Vec::new();
18341        let mut line: VecDeque<Chunk> = VecDeque::new();
18342
18343        let Some(style) = self.style.as_ref() else {
18344            return;
18345        };
18346
18347        for chunk in chunks {
18348            let highlight = chunk
18349                .syntax_highlight_id
18350                .and_then(|id| id.name(&style.syntax));
18351            let mut chunk_lines = chunk.text.split('\n').peekable();
18352            while let Some(text) = chunk_lines.next() {
18353                let mut merged_with_last_token = false;
18354                if let Some(last_token) = line.back_mut() {
18355                    if last_token.highlight == highlight {
18356                        last_token.text.push_str(text);
18357                        merged_with_last_token = true;
18358                    }
18359                }
18360
18361                if !merged_with_last_token {
18362                    line.push_back(Chunk {
18363                        text: text.into(),
18364                        highlight,
18365                    });
18366                }
18367
18368                if chunk_lines.peek().is_some() {
18369                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18370                        line.pop_front();
18371                    }
18372                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18373                        line.pop_back();
18374                    }
18375
18376                    lines.push(mem::take(&mut line));
18377                }
18378            }
18379        }
18380
18381        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18382            return;
18383        };
18384        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18385    }
18386
18387    pub fn open_context_menu(
18388        &mut self,
18389        _: &OpenContextMenu,
18390        window: &mut Window,
18391        cx: &mut Context<Self>,
18392    ) {
18393        self.request_autoscroll(Autoscroll::newest(), cx);
18394        let position = self.selections.newest_display(cx).start;
18395        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18396    }
18397
18398    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18399        &self.inlay_hint_cache
18400    }
18401
18402    pub fn replay_insert_event(
18403        &mut self,
18404        text: &str,
18405        relative_utf16_range: Option<Range<isize>>,
18406        window: &mut Window,
18407        cx: &mut Context<Self>,
18408    ) {
18409        if !self.input_enabled {
18410            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18411            return;
18412        }
18413        if let Some(relative_utf16_range) = relative_utf16_range {
18414            let selections = self.selections.all::<OffsetUtf16>(cx);
18415            self.change_selections(None, window, cx, |s| {
18416                let new_ranges = selections.into_iter().map(|range| {
18417                    let start = OffsetUtf16(
18418                        range
18419                            .head()
18420                            .0
18421                            .saturating_add_signed(relative_utf16_range.start),
18422                    );
18423                    let end = OffsetUtf16(
18424                        range
18425                            .head()
18426                            .0
18427                            .saturating_add_signed(relative_utf16_range.end),
18428                    );
18429                    start..end
18430                });
18431                s.select_ranges(new_ranges);
18432            });
18433        }
18434
18435        self.handle_input(text, window, cx);
18436    }
18437
18438    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18439        let Some(provider) = self.semantics_provider.as_ref() else {
18440            return false;
18441        };
18442
18443        let mut supports = false;
18444        self.buffer().update(cx, |this, cx| {
18445            this.for_each_buffer(|buffer| {
18446                supports |= provider.supports_inlay_hints(buffer, cx);
18447            });
18448        });
18449
18450        supports
18451    }
18452
18453    pub fn is_focused(&self, window: &Window) -> bool {
18454        self.focus_handle.is_focused(window)
18455    }
18456
18457    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18458        cx.emit(EditorEvent::Focused);
18459
18460        if let Some(descendant) = self
18461            .last_focused_descendant
18462            .take()
18463            .and_then(|descendant| descendant.upgrade())
18464        {
18465            window.focus(&descendant);
18466        } else {
18467            if let Some(blame) = self.blame.as_ref() {
18468                blame.update(cx, GitBlame::focus)
18469            }
18470
18471            self.blink_manager.update(cx, BlinkManager::enable);
18472            self.show_cursor_names(window, cx);
18473            self.buffer.update(cx, |buffer, cx| {
18474                buffer.finalize_last_transaction(cx);
18475                if self.leader_id.is_none() {
18476                    buffer.set_active_selections(
18477                        &self.selections.disjoint_anchors(),
18478                        self.selections.line_mode,
18479                        self.cursor_shape,
18480                        cx,
18481                    );
18482                }
18483            });
18484        }
18485    }
18486
18487    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18488        cx.emit(EditorEvent::FocusedIn)
18489    }
18490
18491    fn handle_focus_out(
18492        &mut self,
18493        event: FocusOutEvent,
18494        _window: &mut Window,
18495        cx: &mut Context<Self>,
18496    ) {
18497        if event.blurred != self.focus_handle {
18498            self.last_focused_descendant = Some(event.blurred);
18499        }
18500        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18501    }
18502
18503    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18504        self.blink_manager.update(cx, BlinkManager::disable);
18505        self.buffer
18506            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18507
18508        if let Some(blame) = self.blame.as_ref() {
18509            blame.update(cx, GitBlame::blur)
18510        }
18511        if !self.hover_state.focused(window, cx) {
18512            hide_hover(self, cx);
18513        }
18514        if !self
18515            .context_menu
18516            .borrow()
18517            .as_ref()
18518            .is_some_and(|context_menu| context_menu.focused(window, cx))
18519        {
18520            self.hide_context_menu(window, cx);
18521        }
18522        self.discard_inline_completion(false, cx);
18523        cx.emit(EditorEvent::Blurred);
18524        cx.notify();
18525    }
18526
18527    pub fn register_action<A: Action>(
18528        &mut self,
18529        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18530    ) -> Subscription {
18531        let id = self.next_editor_action_id.post_inc();
18532        let listener = Arc::new(listener);
18533        self.editor_actions.borrow_mut().insert(
18534            id,
18535            Box::new(move |window, _| {
18536                let listener = listener.clone();
18537                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18538                    let action = action.downcast_ref().unwrap();
18539                    if phase == DispatchPhase::Bubble {
18540                        listener(action, window, cx)
18541                    }
18542                })
18543            }),
18544        );
18545
18546        let editor_actions = self.editor_actions.clone();
18547        Subscription::new(move || {
18548            editor_actions.borrow_mut().remove(&id);
18549        })
18550    }
18551
18552    pub fn file_header_size(&self) -> u32 {
18553        FILE_HEADER_HEIGHT
18554    }
18555
18556    pub fn restore(
18557        &mut self,
18558        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18559        window: &mut Window,
18560        cx: &mut Context<Self>,
18561    ) {
18562        let workspace = self.workspace();
18563        let project = self.project.as_ref();
18564        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18565            let mut tasks = Vec::new();
18566            for (buffer_id, changes) in revert_changes {
18567                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18568                    buffer.update(cx, |buffer, cx| {
18569                        buffer.edit(
18570                            changes
18571                                .into_iter()
18572                                .map(|(range, text)| (range, text.to_string())),
18573                            None,
18574                            cx,
18575                        );
18576                    });
18577
18578                    if let Some(project) =
18579                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18580                    {
18581                        project.update(cx, |project, cx| {
18582                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18583                        })
18584                    }
18585                }
18586            }
18587            tasks
18588        });
18589        cx.spawn_in(window, async move |_, cx| {
18590            for (buffer, task) in save_tasks {
18591                let result = task.await;
18592                if result.is_err() {
18593                    let Some(path) = buffer
18594                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18595                        .ok()
18596                    else {
18597                        continue;
18598                    };
18599                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18600                        let Some(task) = cx
18601                            .update_window_entity(&workspace, |workspace, window, cx| {
18602                                workspace
18603                                    .open_path_preview(path, None, false, false, false, window, cx)
18604                            })
18605                            .ok()
18606                        else {
18607                            continue;
18608                        };
18609                        task.await.log_err();
18610                    }
18611                }
18612            }
18613        })
18614        .detach();
18615        self.change_selections(None, window, cx, |selections| selections.refresh());
18616    }
18617
18618    pub fn to_pixel_point(
18619        &self,
18620        source: multi_buffer::Anchor,
18621        editor_snapshot: &EditorSnapshot,
18622        window: &mut Window,
18623    ) -> Option<gpui::Point<Pixels>> {
18624        let source_point = source.to_display_point(editor_snapshot);
18625        self.display_to_pixel_point(source_point, editor_snapshot, window)
18626    }
18627
18628    pub fn display_to_pixel_point(
18629        &self,
18630        source: DisplayPoint,
18631        editor_snapshot: &EditorSnapshot,
18632        window: &mut Window,
18633    ) -> Option<gpui::Point<Pixels>> {
18634        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18635        let text_layout_details = self.text_layout_details(window);
18636        let scroll_top = text_layout_details
18637            .scroll_anchor
18638            .scroll_position(editor_snapshot)
18639            .y;
18640
18641        if source.row().as_f32() < scroll_top.floor() {
18642            return None;
18643        }
18644        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18645        let source_y = line_height * (source.row().as_f32() - scroll_top);
18646        Some(gpui::Point::new(source_x, source_y))
18647    }
18648
18649    pub fn has_visible_completions_menu(&self) -> bool {
18650        !self.edit_prediction_preview_is_active()
18651            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18652                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18653            })
18654    }
18655
18656    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18657        self.addons
18658            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18659    }
18660
18661    pub fn unregister_addon<T: Addon>(&mut self) {
18662        self.addons.remove(&std::any::TypeId::of::<T>());
18663    }
18664
18665    pub fn addon<T: Addon>(&self) -> Option<&T> {
18666        let type_id = std::any::TypeId::of::<T>();
18667        self.addons
18668            .get(&type_id)
18669            .and_then(|item| item.to_any().downcast_ref::<T>())
18670    }
18671
18672    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18673        let type_id = std::any::TypeId::of::<T>();
18674        self.addons
18675            .get_mut(&type_id)
18676            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18677    }
18678
18679    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18680        let text_layout_details = self.text_layout_details(window);
18681        let style = &text_layout_details.editor_style;
18682        let font_id = window.text_system().resolve_font(&style.text.font());
18683        let font_size = style.text.font_size.to_pixels(window.rem_size());
18684        let line_height = style.text.line_height_in_pixels(window.rem_size());
18685        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18686
18687        gpui::Size::new(em_width, line_height)
18688    }
18689
18690    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18691        self.load_diff_task.clone()
18692    }
18693
18694    fn read_metadata_from_db(
18695        &mut self,
18696        item_id: u64,
18697        workspace_id: WorkspaceId,
18698        window: &mut Window,
18699        cx: &mut Context<Editor>,
18700    ) {
18701        if self.is_singleton(cx)
18702            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18703        {
18704            let buffer_snapshot = OnceCell::new();
18705
18706            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18707                if !folds.is_empty() {
18708                    let snapshot =
18709                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18710                    self.fold_ranges(
18711                        folds
18712                            .into_iter()
18713                            .map(|(start, end)| {
18714                                snapshot.clip_offset(start, Bias::Left)
18715                                    ..snapshot.clip_offset(end, Bias::Right)
18716                            })
18717                            .collect(),
18718                        false,
18719                        window,
18720                        cx,
18721                    );
18722                }
18723            }
18724
18725            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18726                if !selections.is_empty() {
18727                    let snapshot =
18728                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18729                    self.change_selections(None, window, cx, |s| {
18730                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18731                            snapshot.clip_offset(start, Bias::Left)
18732                                ..snapshot.clip_offset(end, Bias::Right)
18733                        }));
18734                    });
18735                }
18736            };
18737        }
18738
18739        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18740    }
18741}
18742
18743fn vim_enabled(cx: &App) -> bool {
18744    cx.global::<SettingsStore>()
18745        .raw_user_settings()
18746        .get("vim_mode")
18747        == Some(&serde_json::Value::Bool(true))
18748}
18749
18750// Consider user intent and default settings
18751fn choose_completion_range(
18752    completion: &Completion,
18753    intent: CompletionIntent,
18754    buffer: &Entity<Buffer>,
18755    cx: &mut Context<Editor>,
18756) -> Range<usize> {
18757    fn should_replace(
18758        completion: &Completion,
18759        insert_range: &Range<text::Anchor>,
18760        intent: CompletionIntent,
18761        completion_mode_setting: LspInsertMode,
18762        buffer: &Buffer,
18763    ) -> bool {
18764        // specific actions take precedence over settings
18765        match intent {
18766            CompletionIntent::CompleteWithInsert => return false,
18767            CompletionIntent::CompleteWithReplace => return true,
18768            CompletionIntent::Complete | CompletionIntent::Compose => {}
18769        }
18770
18771        match completion_mode_setting {
18772            LspInsertMode::Insert => false,
18773            LspInsertMode::Replace => true,
18774            LspInsertMode::ReplaceSubsequence => {
18775                let mut text_to_replace = buffer.chars_for_range(
18776                    buffer.anchor_before(completion.replace_range.start)
18777                        ..buffer.anchor_after(completion.replace_range.end),
18778                );
18779                let mut completion_text = completion.new_text.chars();
18780
18781                // is `text_to_replace` a subsequence of `completion_text`
18782                text_to_replace
18783                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18784            }
18785            LspInsertMode::ReplaceSuffix => {
18786                let range_after_cursor = insert_range.end..completion.replace_range.end;
18787
18788                let text_after_cursor = buffer
18789                    .text_for_range(
18790                        buffer.anchor_before(range_after_cursor.start)
18791                            ..buffer.anchor_after(range_after_cursor.end),
18792                    )
18793                    .collect::<String>();
18794                completion.new_text.ends_with(&text_after_cursor)
18795            }
18796        }
18797    }
18798
18799    let buffer = buffer.read(cx);
18800
18801    if let CompletionSource::Lsp {
18802        insert_range: Some(insert_range),
18803        ..
18804    } = &completion.source
18805    {
18806        let completion_mode_setting =
18807            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18808                .completions
18809                .lsp_insert_mode;
18810
18811        if !should_replace(
18812            completion,
18813            &insert_range,
18814            intent,
18815            completion_mode_setting,
18816            buffer,
18817        ) {
18818            return insert_range.to_offset(buffer);
18819        }
18820    }
18821
18822    completion.replace_range.to_offset(buffer)
18823}
18824
18825fn insert_extra_newline_brackets(
18826    buffer: &MultiBufferSnapshot,
18827    range: Range<usize>,
18828    language: &language::LanguageScope,
18829) -> bool {
18830    let leading_whitespace_len = buffer
18831        .reversed_chars_at(range.start)
18832        .take_while(|c| c.is_whitespace() && *c != '\n')
18833        .map(|c| c.len_utf8())
18834        .sum::<usize>();
18835    let trailing_whitespace_len = buffer
18836        .chars_at(range.end)
18837        .take_while(|c| c.is_whitespace() && *c != '\n')
18838        .map(|c| c.len_utf8())
18839        .sum::<usize>();
18840    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18841
18842    language.brackets().any(|(pair, enabled)| {
18843        let pair_start = pair.start.trim_end();
18844        let pair_end = pair.end.trim_start();
18845
18846        enabled
18847            && pair.newline
18848            && buffer.contains_str_at(range.end, pair_end)
18849            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18850    })
18851}
18852
18853fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18854    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18855        [(buffer, range, _)] => (*buffer, range.clone()),
18856        _ => return false,
18857    };
18858    let pair = {
18859        let mut result: Option<BracketMatch> = None;
18860
18861        for pair in buffer
18862            .all_bracket_ranges(range.clone())
18863            .filter(move |pair| {
18864                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18865            })
18866        {
18867            let len = pair.close_range.end - pair.open_range.start;
18868
18869            if let Some(existing) = &result {
18870                let existing_len = existing.close_range.end - existing.open_range.start;
18871                if len > existing_len {
18872                    continue;
18873                }
18874            }
18875
18876            result = Some(pair);
18877        }
18878
18879        result
18880    };
18881    let Some(pair) = pair else {
18882        return false;
18883    };
18884    pair.newline_only
18885        && buffer
18886            .chars_for_range(pair.open_range.end..range.start)
18887            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18888            .all(|c| c.is_whitespace() && c != '\n')
18889}
18890
18891fn update_uncommitted_diff_for_buffer(
18892    editor: Entity<Editor>,
18893    project: &Entity<Project>,
18894    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18895    buffer: Entity<MultiBuffer>,
18896    cx: &mut App,
18897) -> Task<()> {
18898    let mut tasks = Vec::new();
18899    project.update(cx, |project, cx| {
18900        for buffer in buffers {
18901            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18902                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18903            }
18904        }
18905    });
18906    cx.spawn(async move |cx| {
18907        let diffs = future::join_all(tasks).await;
18908        if editor
18909            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18910            .unwrap_or(false)
18911        {
18912            return;
18913        }
18914
18915        buffer
18916            .update(cx, |buffer, cx| {
18917                for diff in diffs.into_iter().flatten() {
18918                    buffer.add_diff(diff, cx);
18919                }
18920            })
18921            .ok();
18922    })
18923}
18924
18925fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18926    let tab_size = tab_size.get() as usize;
18927    let mut width = offset;
18928
18929    for ch in text.chars() {
18930        width += if ch == '\t' {
18931            tab_size - (width % tab_size)
18932        } else {
18933            1
18934        };
18935    }
18936
18937    width - offset
18938}
18939
18940#[cfg(test)]
18941mod tests {
18942    use super::*;
18943
18944    #[test]
18945    fn test_string_size_with_expanded_tabs() {
18946        let nz = |val| NonZeroU32::new(val).unwrap();
18947        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18948        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18949        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18950        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18951        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18952        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18953        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18954        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18955    }
18956}
18957
18958/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18959struct WordBreakingTokenizer<'a> {
18960    input: &'a str,
18961}
18962
18963impl<'a> WordBreakingTokenizer<'a> {
18964    fn new(input: &'a str) -> Self {
18965        Self { input }
18966    }
18967}
18968
18969fn is_char_ideographic(ch: char) -> bool {
18970    use unicode_script::Script::*;
18971    use unicode_script::UnicodeScript;
18972    matches!(ch.script(), Han | Tangut | Yi)
18973}
18974
18975fn is_grapheme_ideographic(text: &str) -> bool {
18976    text.chars().any(is_char_ideographic)
18977}
18978
18979fn is_grapheme_whitespace(text: &str) -> bool {
18980    text.chars().any(|x| x.is_whitespace())
18981}
18982
18983fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18984    text.chars().next().map_or(false, |ch| {
18985        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18986    })
18987}
18988
18989#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18990enum WordBreakToken<'a> {
18991    Word { token: &'a str, grapheme_len: usize },
18992    InlineWhitespace { token: &'a str, grapheme_len: usize },
18993    Newline,
18994}
18995
18996impl<'a> Iterator for WordBreakingTokenizer<'a> {
18997    /// Yields a span, the count of graphemes in the token, and whether it was
18998    /// whitespace. Note that it also breaks at word boundaries.
18999    type Item = WordBreakToken<'a>;
19000
19001    fn next(&mut self) -> Option<Self::Item> {
19002        use unicode_segmentation::UnicodeSegmentation;
19003        if self.input.is_empty() {
19004            return None;
19005        }
19006
19007        let mut iter = self.input.graphemes(true).peekable();
19008        let mut offset = 0;
19009        let mut grapheme_len = 0;
19010        if let Some(first_grapheme) = iter.next() {
19011            let is_newline = first_grapheme == "\n";
19012            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19013            offset += first_grapheme.len();
19014            grapheme_len += 1;
19015            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19016                if let Some(grapheme) = iter.peek().copied() {
19017                    if should_stay_with_preceding_ideograph(grapheme) {
19018                        offset += grapheme.len();
19019                        grapheme_len += 1;
19020                    }
19021                }
19022            } else {
19023                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19024                let mut next_word_bound = words.peek().copied();
19025                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19026                    next_word_bound = words.next();
19027                }
19028                while let Some(grapheme) = iter.peek().copied() {
19029                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19030                        break;
19031                    };
19032                    if is_grapheme_whitespace(grapheme) != is_whitespace
19033                        || (grapheme == "\n") != is_newline
19034                    {
19035                        break;
19036                    };
19037                    offset += grapheme.len();
19038                    grapheme_len += 1;
19039                    iter.next();
19040                }
19041            }
19042            let token = &self.input[..offset];
19043            self.input = &self.input[offset..];
19044            if token == "\n" {
19045                Some(WordBreakToken::Newline)
19046            } else if is_whitespace {
19047                Some(WordBreakToken::InlineWhitespace {
19048                    token,
19049                    grapheme_len,
19050                })
19051            } else {
19052                Some(WordBreakToken::Word {
19053                    token,
19054                    grapheme_len,
19055                })
19056            }
19057        } else {
19058            None
19059        }
19060    }
19061}
19062
19063#[test]
19064fn test_word_breaking_tokenizer() {
19065    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19066        ("", &[]),
19067        ("  ", &[whitespace("  ", 2)]),
19068        ("Ʒ", &[word("Ʒ", 1)]),
19069        ("Ǽ", &[word("Ǽ", 1)]),
19070        ("", &[word("", 1)]),
19071        ("⋑⋑", &[word("⋑⋑", 2)]),
19072        (
19073            "原理,进而",
19074            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19075        ),
19076        (
19077            "hello world",
19078            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19079        ),
19080        (
19081            "hello, world",
19082            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19083        ),
19084        (
19085            "  hello world",
19086            &[
19087                whitespace("  ", 2),
19088                word("hello", 5),
19089                whitespace(" ", 1),
19090                word("world", 5),
19091            ],
19092        ),
19093        (
19094            "这是什么 \n 钢笔",
19095            &[
19096                word("", 1),
19097                word("", 1),
19098                word("", 1),
19099                word("", 1),
19100                whitespace(" ", 1),
19101                newline(),
19102                whitespace(" ", 1),
19103                word("", 1),
19104                word("", 1),
19105            ],
19106        ),
19107        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19108    ];
19109
19110    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19111        WordBreakToken::Word {
19112            token,
19113            grapheme_len,
19114        }
19115    }
19116
19117    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19118        WordBreakToken::InlineWhitespace {
19119            token,
19120            grapheme_len,
19121        }
19122    }
19123
19124    fn newline() -> WordBreakToken<'static> {
19125        WordBreakToken::Newline
19126    }
19127
19128    for (input, result) in tests {
19129        assert_eq!(
19130            WordBreakingTokenizer::new(input)
19131                .collect::<Vec<_>>()
19132                .as_slice(),
19133            *result,
19134        );
19135    }
19136}
19137
19138fn wrap_with_prefix(
19139    line_prefix: String,
19140    unwrapped_text: String,
19141    wrap_column: usize,
19142    tab_size: NonZeroU32,
19143    preserve_existing_whitespace: bool,
19144) -> String {
19145    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19146    let mut wrapped_text = String::new();
19147    let mut current_line = line_prefix.clone();
19148
19149    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19150    let mut current_line_len = line_prefix_len;
19151    let mut in_whitespace = false;
19152    for token in tokenizer {
19153        let have_preceding_whitespace = in_whitespace;
19154        match token {
19155            WordBreakToken::Word {
19156                token,
19157                grapheme_len,
19158            } => {
19159                in_whitespace = false;
19160                if current_line_len + grapheme_len > wrap_column
19161                    && current_line_len != line_prefix_len
19162                {
19163                    wrapped_text.push_str(current_line.trim_end());
19164                    wrapped_text.push('\n');
19165                    current_line.truncate(line_prefix.len());
19166                    current_line_len = line_prefix_len;
19167                }
19168                current_line.push_str(token);
19169                current_line_len += grapheme_len;
19170            }
19171            WordBreakToken::InlineWhitespace {
19172                mut token,
19173                mut grapheme_len,
19174            } => {
19175                in_whitespace = true;
19176                if have_preceding_whitespace && !preserve_existing_whitespace {
19177                    continue;
19178                }
19179                if !preserve_existing_whitespace {
19180                    token = " ";
19181                    grapheme_len = 1;
19182                }
19183                if current_line_len + grapheme_len > wrap_column {
19184                    wrapped_text.push_str(current_line.trim_end());
19185                    wrapped_text.push('\n');
19186                    current_line.truncate(line_prefix.len());
19187                    current_line_len = line_prefix_len;
19188                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19189                    current_line.push_str(token);
19190                    current_line_len += grapheme_len;
19191                }
19192            }
19193            WordBreakToken::Newline => {
19194                in_whitespace = true;
19195                if preserve_existing_whitespace {
19196                    wrapped_text.push_str(current_line.trim_end());
19197                    wrapped_text.push('\n');
19198                    current_line.truncate(line_prefix.len());
19199                    current_line_len = line_prefix_len;
19200                } else if have_preceding_whitespace {
19201                    continue;
19202                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19203                {
19204                    wrapped_text.push_str(current_line.trim_end());
19205                    wrapped_text.push('\n');
19206                    current_line.truncate(line_prefix.len());
19207                    current_line_len = line_prefix_len;
19208                } else if current_line_len != line_prefix_len {
19209                    current_line.push(' ');
19210                    current_line_len += 1;
19211                }
19212            }
19213        }
19214    }
19215
19216    if !current_line.is_empty() {
19217        wrapped_text.push_str(&current_line);
19218    }
19219    wrapped_text
19220}
19221
19222#[test]
19223fn test_wrap_with_prefix() {
19224    assert_eq!(
19225        wrap_with_prefix(
19226            "# ".to_string(),
19227            "abcdefg".to_string(),
19228            4,
19229            NonZeroU32::new(4).unwrap(),
19230            false,
19231        ),
19232        "# abcdefg"
19233    );
19234    assert_eq!(
19235        wrap_with_prefix(
19236            "".to_string(),
19237            "\thello world".to_string(),
19238            8,
19239            NonZeroU32::new(4).unwrap(),
19240            false,
19241        ),
19242        "hello\nworld"
19243    );
19244    assert_eq!(
19245        wrap_with_prefix(
19246            "// ".to_string(),
19247            "xx \nyy zz aa bb cc".to_string(),
19248            12,
19249            NonZeroU32::new(4).unwrap(),
19250            false,
19251        ),
19252        "// xx yy zz\n// aa bb cc"
19253    );
19254    assert_eq!(
19255        wrap_with_prefix(
19256            String::new(),
19257            "这是什么 \n 钢笔".to_string(),
19258            3,
19259            NonZeroU32::new(4).unwrap(),
19260            false,
19261        ),
19262        "这是什\n么 钢\n"
19263    );
19264}
19265
19266pub trait CollaborationHub {
19267    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19268    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19269    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19270}
19271
19272impl CollaborationHub for Entity<Project> {
19273    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19274        self.read(cx).collaborators()
19275    }
19276
19277    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19278        self.read(cx).user_store().read(cx).participant_indices()
19279    }
19280
19281    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19282        let this = self.read(cx);
19283        let user_ids = this.collaborators().values().map(|c| c.user_id);
19284        this.user_store().read_with(cx, |user_store, cx| {
19285            user_store.participant_names(user_ids, cx)
19286        })
19287    }
19288}
19289
19290pub trait SemanticsProvider {
19291    fn hover(
19292        &self,
19293        buffer: &Entity<Buffer>,
19294        position: text::Anchor,
19295        cx: &mut App,
19296    ) -> Option<Task<Vec<project::Hover>>>;
19297
19298    fn inline_values(
19299        &self,
19300        buffer_handle: Entity<Buffer>,
19301        range: Range<text::Anchor>,
19302        cx: &mut App,
19303    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19304
19305    fn inlay_hints(
19306        &self,
19307        buffer_handle: Entity<Buffer>,
19308        range: Range<text::Anchor>,
19309        cx: &mut App,
19310    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19311
19312    fn resolve_inlay_hint(
19313        &self,
19314        hint: InlayHint,
19315        buffer_handle: Entity<Buffer>,
19316        server_id: LanguageServerId,
19317        cx: &mut App,
19318    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19319
19320    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19321
19322    fn document_highlights(
19323        &self,
19324        buffer: &Entity<Buffer>,
19325        position: text::Anchor,
19326        cx: &mut App,
19327    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19328
19329    fn definitions(
19330        &self,
19331        buffer: &Entity<Buffer>,
19332        position: text::Anchor,
19333        kind: GotoDefinitionKind,
19334        cx: &mut App,
19335    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19336
19337    fn range_for_rename(
19338        &self,
19339        buffer: &Entity<Buffer>,
19340        position: text::Anchor,
19341        cx: &mut App,
19342    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19343
19344    fn perform_rename(
19345        &self,
19346        buffer: &Entity<Buffer>,
19347        position: text::Anchor,
19348        new_name: String,
19349        cx: &mut App,
19350    ) -> Option<Task<Result<ProjectTransaction>>>;
19351}
19352
19353pub trait CompletionProvider {
19354    fn completions(
19355        &self,
19356        excerpt_id: ExcerptId,
19357        buffer: &Entity<Buffer>,
19358        buffer_position: text::Anchor,
19359        trigger: CompletionContext,
19360        window: &mut Window,
19361        cx: &mut Context<Editor>,
19362    ) -> Task<Result<Option<Vec<Completion>>>>;
19363
19364    fn resolve_completions(
19365        &self,
19366        buffer: Entity<Buffer>,
19367        completion_indices: Vec<usize>,
19368        completions: Rc<RefCell<Box<[Completion]>>>,
19369        cx: &mut Context<Editor>,
19370    ) -> Task<Result<bool>>;
19371
19372    fn apply_additional_edits_for_completion(
19373        &self,
19374        _buffer: Entity<Buffer>,
19375        _completions: Rc<RefCell<Box<[Completion]>>>,
19376        _completion_index: usize,
19377        _push_to_history: bool,
19378        _cx: &mut Context<Editor>,
19379    ) -> Task<Result<Option<language::Transaction>>> {
19380        Task::ready(Ok(None))
19381    }
19382
19383    fn is_completion_trigger(
19384        &self,
19385        buffer: &Entity<Buffer>,
19386        position: language::Anchor,
19387        text: &str,
19388        trigger_in_words: bool,
19389        cx: &mut Context<Editor>,
19390    ) -> bool;
19391
19392    fn sort_completions(&self) -> bool {
19393        true
19394    }
19395
19396    fn filter_completions(&self) -> bool {
19397        true
19398    }
19399}
19400
19401pub trait CodeActionProvider {
19402    fn id(&self) -> Arc<str>;
19403
19404    fn code_actions(
19405        &self,
19406        buffer: &Entity<Buffer>,
19407        range: Range<text::Anchor>,
19408        window: &mut Window,
19409        cx: &mut App,
19410    ) -> Task<Result<Vec<CodeAction>>>;
19411
19412    fn apply_code_action(
19413        &self,
19414        buffer_handle: Entity<Buffer>,
19415        action: CodeAction,
19416        excerpt_id: ExcerptId,
19417        push_to_history: bool,
19418        window: &mut Window,
19419        cx: &mut App,
19420    ) -> Task<Result<ProjectTransaction>>;
19421}
19422
19423impl CodeActionProvider for Entity<Project> {
19424    fn id(&self) -> Arc<str> {
19425        "project".into()
19426    }
19427
19428    fn code_actions(
19429        &self,
19430        buffer: &Entity<Buffer>,
19431        range: Range<text::Anchor>,
19432        _window: &mut Window,
19433        cx: &mut App,
19434    ) -> Task<Result<Vec<CodeAction>>> {
19435        self.update(cx, |project, cx| {
19436            let code_lens = project.code_lens(buffer, range.clone(), cx);
19437            let code_actions = project.code_actions(buffer, range, None, cx);
19438            cx.background_spawn(async move {
19439                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19440                Ok(code_lens
19441                    .context("code lens fetch")?
19442                    .into_iter()
19443                    .chain(code_actions.context("code action fetch")?)
19444                    .collect())
19445            })
19446        })
19447    }
19448
19449    fn apply_code_action(
19450        &self,
19451        buffer_handle: Entity<Buffer>,
19452        action: CodeAction,
19453        _excerpt_id: ExcerptId,
19454        push_to_history: bool,
19455        _window: &mut Window,
19456        cx: &mut App,
19457    ) -> Task<Result<ProjectTransaction>> {
19458        self.update(cx, |project, cx| {
19459            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19460        })
19461    }
19462}
19463
19464fn snippet_completions(
19465    project: &Project,
19466    buffer: &Entity<Buffer>,
19467    buffer_position: text::Anchor,
19468    cx: &mut App,
19469) -> Task<Result<Vec<Completion>>> {
19470    let languages = buffer.read(cx).languages_at(buffer_position);
19471    let snippet_store = project.snippets().read(cx);
19472
19473    let scopes: Vec<_> = languages
19474        .iter()
19475        .filter_map(|language| {
19476            let language_name = language.lsp_id();
19477            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19478
19479            if snippets.is_empty() {
19480                None
19481            } else {
19482                Some((language.default_scope(), snippets))
19483            }
19484        })
19485        .collect();
19486
19487    if scopes.is_empty() {
19488        return Task::ready(Ok(vec![]));
19489    }
19490
19491    let snapshot = buffer.read(cx).text_snapshot();
19492    let chars: String = snapshot
19493        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19494        .collect();
19495    let executor = cx.background_executor().clone();
19496
19497    cx.background_spawn(async move {
19498        let mut all_results: Vec<Completion> = Vec::new();
19499        for (scope, snippets) in scopes.into_iter() {
19500            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19501            let mut last_word = chars
19502                .chars()
19503                .take_while(|c| classifier.is_word(*c))
19504                .collect::<String>();
19505            last_word = last_word.chars().rev().collect();
19506
19507            if last_word.is_empty() {
19508                return Ok(vec![]);
19509            }
19510
19511            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19512            let to_lsp = |point: &text::Anchor| {
19513                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19514                point_to_lsp(end)
19515            };
19516            let lsp_end = to_lsp(&buffer_position);
19517
19518            let candidates = snippets
19519                .iter()
19520                .enumerate()
19521                .flat_map(|(ix, snippet)| {
19522                    snippet
19523                        .prefix
19524                        .iter()
19525                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19526                })
19527                .collect::<Vec<StringMatchCandidate>>();
19528
19529            let mut matches = fuzzy::match_strings(
19530                &candidates,
19531                &last_word,
19532                last_word.chars().any(|c| c.is_uppercase()),
19533                100,
19534                &Default::default(),
19535                executor.clone(),
19536            )
19537            .await;
19538
19539            // Remove all candidates where the query's start does not match the start of any word in the candidate
19540            if let Some(query_start) = last_word.chars().next() {
19541                matches.retain(|string_match| {
19542                    split_words(&string_match.string).any(|word| {
19543                        // Check that the first codepoint of the word as lowercase matches the first
19544                        // codepoint of the query as lowercase
19545                        word.chars()
19546                            .flat_map(|codepoint| codepoint.to_lowercase())
19547                            .zip(query_start.to_lowercase())
19548                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19549                    })
19550                });
19551            }
19552
19553            let matched_strings = matches
19554                .into_iter()
19555                .map(|m| m.string)
19556                .collect::<HashSet<_>>();
19557
19558            let mut result: Vec<Completion> = snippets
19559                .iter()
19560                .filter_map(|snippet| {
19561                    let matching_prefix = snippet
19562                        .prefix
19563                        .iter()
19564                        .find(|prefix| matched_strings.contains(*prefix))?;
19565                    let start = as_offset - last_word.len();
19566                    let start = snapshot.anchor_before(start);
19567                    let range = start..buffer_position;
19568                    let lsp_start = to_lsp(&start);
19569                    let lsp_range = lsp::Range {
19570                        start: lsp_start,
19571                        end: lsp_end,
19572                    };
19573                    Some(Completion {
19574                        replace_range: range,
19575                        new_text: snippet.body.clone(),
19576                        source: CompletionSource::Lsp {
19577                            insert_range: None,
19578                            server_id: LanguageServerId(usize::MAX),
19579                            resolved: true,
19580                            lsp_completion: Box::new(lsp::CompletionItem {
19581                                label: snippet.prefix.first().unwrap().clone(),
19582                                kind: Some(CompletionItemKind::SNIPPET),
19583                                label_details: snippet.description.as_ref().map(|description| {
19584                                    lsp::CompletionItemLabelDetails {
19585                                        detail: Some(description.clone()),
19586                                        description: None,
19587                                    }
19588                                }),
19589                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19590                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19591                                    lsp::InsertReplaceEdit {
19592                                        new_text: snippet.body.clone(),
19593                                        insert: lsp_range,
19594                                        replace: lsp_range,
19595                                    },
19596                                )),
19597                                filter_text: Some(snippet.body.clone()),
19598                                sort_text: Some(char::MAX.to_string()),
19599                                ..lsp::CompletionItem::default()
19600                            }),
19601                            lsp_defaults: None,
19602                        },
19603                        label: CodeLabel {
19604                            text: matching_prefix.clone(),
19605                            runs: Vec::new(),
19606                            filter_range: 0..matching_prefix.len(),
19607                        },
19608                        icon_path: None,
19609                        documentation: snippet.description.clone().map(|description| {
19610                            CompletionDocumentation::SingleLine(description.into())
19611                        }),
19612                        insert_text_mode: None,
19613                        confirm: None,
19614                    })
19615                })
19616                .collect();
19617
19618            all_results.append(&mut result);
19619        }
19620
19621        Ok(all_results)
19622    })
19623}
19624
19625impl CompletionProvider for Entity<Project> {
19626    fn completions(
19627        &self,
19628        _excerpt_id: ExcerptId,
19629        buffer: &Entity<Buffer>,
19630        buffer_position: text::Anchor,
19631        options: CompletionContext,
19632        _window: &mut Window,
19633        cx: &mut Context<Editor>,
19634    ) -> Task<Result<Option<Vec<Completion>>>> {
19635        self.update(cx, |project, cx| {
19636            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19637            let project_completions = project.completions(buffer, buffer_position, options, cx);
19638            cx.background_spawn(async move {
19639                let snippets_completions = snippets.await?;
19640                match project_completions.await? {
19641                    Some(mut completions) => {
19642                        completions.extend(snippets_completions);
19643                        Ok(Some(completions))
19644                    }
19645                    None => {
19646                        if snippets_completions.is_empty() {
19647                            Ok(None)
19648                        } else {
19649                            Ok(Some(snippets_completions))
19650                        }
19651                    }
19652                }
19653            })
19654        })
19655    }
19656
19657    fn resolve_completions(
19658        &self,
19659        buffer: Entity<Buffer>,
19660        completion_indices: Vec<usize>,
19661        completions: Rc<RefCell<Box<[Completion]>>>,
19662        cx: &mut Context<Editor>,
19663    ) -> Task<Result<bool>> {
19664        self.update(cx, |project, cx| {
19665            project.lsp_store().update(cx, |lsp_store, cx| {
19666                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19667            })
19668        })
19669    }
19670
19671    fn apply_additional_edits_for_completion(
19672        &self,
19673        buffer: Entity<Buffer>,
19674        completions: Rc<RefCell<Box<[Completion]>>>,
19675        completion_index: usize,
19676        push_to_history: bool,
19677        cx: &mut Context<Editor>,
19678    ) -> Task<Result<Option<language::Transaction>>> {
19679        self.update(cx, |project, cx| {
19680            project.lsp_store().update(cx, |lsp_store, cx| {
19681                lsp_store.apply_additional_edits_for_completion(
19682                    buffer,
19683                    completions,
19684                    completion_index,
19685                    push_to_history,
19686                    cx,
19687                )
19688            })
19689        })
19690    }
19691
19692    fn is_completion_trigger(
19693        &self,
19694        buffer: &Entity<Buffer>,
19695        position: language::Anchor,
19696        text: &str,
19697        trigger_in_words: bool,
19698        cx: &mut Context<Editor>,
19699    ) -> bool {
19700        let mut chars = text.chars();
19701        let char = if let Some(char) = chars.next() {
19702            char
19703        } else {
19704            return false;
19705        };
19706        if chars.next().is_some() {
19707            return false;
19708        }
19709
19710        let buffer = buffer.read(cx);
19711        let snapshot = buffer.snapshot();
19712        if !snapshot.settings_at(position, cx).show_completions_on_input {
19713            return false;
19714        }
19715        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19716        if trigger_in_words && classifier.is_word(char) {
19717            return true;
19718        }
19719
19720        buffer.completion_triggers().contains(text)
19721    }
19722}
19723
19724impl SemanticsProvider for Entity<Project> {
19725    fn hover(
19726        &self,
19727        buffer: &Entity<Buffer>,
19728        position: text::Anchor,
19729        cx: &mut App,
19730    ) -> Option<Task<Vec<project::Hover>>> {
19731        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19732    }
19733
19734    fn document_highlights(
19735        &self,
19736        buffer: &Entity<Buffer>,
19737        position: text::Anchor,
19738        cx: &mut App,
19739    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19740        Some(self.update(cx, |project, cx| {
19741            project.document_highlights(buffer, position, cx)
19742        }))
19743    }
19744
19745    fn definitions(
19746        &self,
19747        buffer: &Entity<Buffer>,
19748        position: text::Anchor,
19749        kind: GotoDefinitionKind,
19750        cx: &mut App,
19751    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19752        Some(self.update(cx, |project, cx| match kind {
19753            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19754            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19755            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19756            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19757        }))
19758    }
19759
19760    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19761        // TODO: make this work for remote projects
19762        self.update(cx, |project, cx| {
19763            if project
19764                .active_debug_session(cx)
19765                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19766            {
19767                return true;
19768            }
19769
19770            buffer.update(cx, |buffer, cx| {
19771                project.any_language_server_supports_inlay_hints(buffer, cx)
19772            })
19773        })
19774    }
19775
19776    fn inline_values(
19777        &self,
19778        buffer_handle: Entity<Buffer>,
19779        range: Range<text::Anchor>,
19780        cx: &mut App,
19781    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19782        self.update(cx, |project, cx| {
19783            let (session, active_stack_frame) = project.active_debug_session(cx)?;
19784
19785            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19786        })
19787    }
19788
19789    fn inlay_hints(
19790        &self,
19791        buffer_handle: Entity<Buffer>,
19792        range: Range<text::Anchor>,
19793        cx: &mut App,
19794    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19795        Some(self.update(cx, |project, cx| {
19796            project.inlay_hints(buffer_handle, range, cx)
19797        }))
19798    }
19799
19800    fn resolve_inlay_hint(
19801        &self,
19802        hint: InlayHint,
19803        buffer_handle: Entity<Buffer>,
19804        server_id: LanguageServerId,
19805        cx: &mut App,
19806    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19807        Some(self.update(cx, |project, cx| {
19808            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19809        }))
19810    }
19811
19812    fn range_for_rename(
19813        &self,
19814        buffer: &Entity<Buffer>,
19815        position: text::Anchor,
19816        cx: &mut App,
19817    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19818        Some(self.update(cx, |project, cx| {
19819            let buffer = buffer.clone();
19820            let task = project.prepare_rename(buffer.clone(), position, cx);
19821            cx.spawn(async move |_, cx| {
19822                Ok(match task.await? {
19823                    PrepareRenameResponse::Success(range) => Some(range),
19824                    PrepareRenameResponse::InvalidPosition => None,
19825                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19826                        // Fallback on using TreeSitter info to determine identifier range
19827                        buffer.update(cx, |buffer, _| {
19828                            let snapshot = buffer.snapshot();
19829                            let (range, kind) = snapshot.surrounding_word(position);
19830                            if kind != Some(CharKind::Word) {
19831                                return None;
19832                            }
19833                            Some(
19834                                snapshot.anchor_before(range.start)
19835                                    ..snapshot.anchor_after(range.end),
19836                            )
19837                        })?
19838                    }
19839                })
19840            })
19841        }))
19842    }
19843
19844    fn perform_rename(
19845        &self,
19846        buffer: &Entity<Buffer>,
19847        position: text::Anchor,
19848        new_name: String,
19849        cx: &mut App,
19850    ) -> Option<Task<Result<ProjectTransaction>>> {
19851        Some(self.update(cx, |project, cx| {
19852            project.perform_rename(buffer.clone(), position, new_name, cx)
19853        }))
19854    }
19855}
19856
19857fn inlay_hint_settings(
19858    location: Anchor,
19859    snapshot: &MultiBufferSnapshot,
19860    cx: &mut Context<Editor>,
19861) -> InlayHintSettings {
19862    let file = snapshot.file_at(location);
19863    let language = snapshot.language_at(location).map(|l| l.name());
19864    language_settings(language, file, cx).inlay_hints
19865}
19866
19867fn consume_contiguous_rows(
19868    contiguous_row_selections: &mut Vec<Selection<Point>>,
19869    selection: &Selection<Point>,
19870    display_map: &DisplaySnapshot,
19871    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19872) -> (MultiBufferRow, MultiBufferRow) {
19873    contiguous_row_selections.push(selection.clone());
19874    let start_row = MultiBufferRow(selection.start.row);
19875    let mut end_row = ending_row(selection, display_map);
19876
19877    while let Some(next_selection) = selections.peek() {
19878        if next_selection.start.row <= end_row.0 {
19879            end_row = ending_row(next_selection, display_map);
19880            contiguous_row_selections.push(selections.next().unwrap().clone());
19881        } else {
19882            break;
19883        }
19884    }
19885    (start_row, end_row)
19886}
19887
19888fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19889    if next_selection.end.column > 0 || next_selection.is_empty() {
19890        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19891    } else {
19892        MultiBufferRow(next_selection.end.row)
19893    }
19894}
19895
19896impl EditorSnapshot {
19897    pub fn remote_selections_in_range<'a>(
19898        &'a self,
19899        range: &'a Range<Anchor>,
19900        collaboration_hub: &dyn CollaborationHub,
19901        cx: &'a App,
19902    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19903        let participant_names = collaboration_hub.user_names(cx);
19904        let participant_indices = collaboration_hub.user_participant_indices(cx);
19905        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19906        let collaborators_by_replica_id = collaborators_by_peer_id
19907            .iter()
19908            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19909            .collect::<HashMap<_, _>>();
19910        self.buffer_snapshot
19911            .selections_in_range(range, false)
19912            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19913                if replica_id == AGENT_REPLICA_ID {
19914                    Some(RemoteSelection {
19915                        replica_id,
19916                        selection,
19917                        cursor_shape,
19918                        line_mode,
19919                        collaborator_id: CollaboratorId::Agent,
19920                        user_name: Some("Agent".into()),
19921                        color: cx.theme().players().agent(),
19922                    })
19923                } else {
19924                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19925                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
19926                    let user_name = participant_names.get(&collaborator.user_id).cloned();
19927                    Some(RemoteSelection {
19928                        replica_id,
19929                        selection,
19930                        cursor_shape,
19931                        line_mode,
19932                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19933                        user_name,
19934                        color: if let Some(index) = participant_index {
19935                            cx.theme().players().color_for_participant(index.0)
19936                        } else {
19937                            cx.theme().players().absent()
19938                        },
19939                    })
19940                }
19941            })
19942    }
19943
19944    pub fn hunks_for_ranges(
19945        &self,
19946        ranges: impl IntoIterator<Item = Range<Point>>,
19947    ) -> Vec<MultiBufferDiffHunk> {
19948        let mut hunks = Vec::new();
19949        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19950            HashMap::default();
19951        for query_range in ranges {
19952            let query_rows =
19953                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19954            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19955                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19956            ) {
19957                // Include deleted hunks that are adjacent to the query range, because
19958                // otherwise they would be missed.
19959                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19960                if hunk.status().is_deleted() {
19961                    intersects_range |= hunk.row_range.start == query_rows.end;
19962                    intersects_range |= hunk.row_range.end == query_rows.start;
19963                }
19964                if intersects_range {
19965                    if !processed_buffer_rows
19966                        .entry(hunk.buffer_id)
19967                        .or_default()
19968                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19969                    {
19970                        continue;
19971                    }
19972                    hunks.push(hunk);
19973                }
19974            }
19975        }
19976
19977        hunks
19978    }
19979
19980    fn display_diff_hunks_for_rows<'a>(
19981        &'a self,
19982        display_rows: Range<DisplayRow>,
19983        folded_buffers: &'a HashSet<BufferId>,
19984    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19985        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19986        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19987
19988        self.buffer_snapshot
19989            .diff_hunks_in_range(buffer_start..buffer_end)
19990            .filter_map(|hunk| {
19991                if folded_buffers.contains(&hunk.buffer_id) {
19992                    return None;
19993                }
19994
19995                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19996                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19997
19998                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19999                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20000
20001                let display_hunk = if hunk_display_start.column() != 0 {
20002                    DisplayDiffHunk::Folded {
20003                        display_row: hunk_display_start.row(),
20004                    }
20005                } else {
20006                    let mut end_row = hunk_display_end.row();
20007                    if hunk_display_end.column() > 0 {
20008                        end_row.0 += 1;
20009                    }
20010                    let is_created_file = hunk.is_created_file();
20011                    DisplayDiffHunk::Unfolded {
20012                        status: hunk.status(),
20013                        diff_base_byte_range: hunk.diff_base_byte_range,
20014                        display_row_range: hunk_display_start.row()..end_row,
20015                        multi_buffer_range: Anchor::range_in_buffer(
20016                            hunk.excerpt_id,
20017                            hunk.buffer_id,
20018                            hunk.buffer_range,
20019                        ),
20020                        is_created_file,
20021                    }
20022                };
20023
20024                Some(display_hunk)
20025            })
20026    }
20027
20028    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20029        self.display_snapshot.buffer_snapshot.language_at(position)
20030    }
20031
20032    pub fn is_focused(&self) -> bool {
20033        self.is_focused
20034    }
20035
20036    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20037        self.placeholder_text.as_ref()
20038    }
20039
20040    pub fn scroll_position(&self) -> gpui::Point<f32> {
20041        self.scroll_anchor.scroll_position(&self.display_snapshot)
20042    }
20043
20044    fn gutter_dimensions(
20045        &self,
20046        font_id: FontId,
20047        font_size: Pixels,
20048        max_line_number_width: Pixels,
20049        cx: &App,
20050    ) -> Option<GutterDimensions> {
20051        if !self.show_gutter {
20052            return None;
20053        }
20054
20055        let descent = cx.text_system().descent(font_id, font_size);
20056        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20057        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20058
20059        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20060            matches!(
20061                ProjectSettings::get_global(cx).git.git_gutter,
20062                Some(GitGutterSetting::TrackedFiles)
20063            )
20064        });
20065        let gutter_settings = EditorSettings::get_global(cx).gutter;
20066        let show_line_numbers = self
20067            .show_line_numbers
20068            .unwrap_or(gutter_settings.line_numbers);
20069        let line_gutter_width = if show_line_numbers {
20070            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20071            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20072            max_line_number_width.max(min_width_for_number_on_gutter)
20073        } else {
20074            0.0.into()
20075        };
20076
20077        let show_code_actions = self
20078            .show_code_actions
20079            .unwrap_or(gutter_settings.code_actions);
20080
20081        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20082        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20083
20084        let git_blame_entries_width =
20085            self.git_blame_gutter_max_author_length
20086                .map(|max_author_length| {
20087                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20088                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20089
20090                    /// The number of characters to dedicate to gaps and margins.
20091                    const SPACING_WIDTH: usize = 4;
20092
20093                    let max_char_count = max_author_length.min(renderer.max_author_length())
20094                        + ::git::SHORT_SHA_LENGTH
20095                        + MAX_RELATIVE_TIMESTAMP.len()
20096                        + SPACING_WIDTH;
20097
20098                    em_advance * max_char_count
20099                });
20100
20101        let is_singleton = self.buffer_snapshot.is_singleton();
20102
20103        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20104        left_padding += if !is_singleton {
20105            em_width * 4.0
20106        } else if show_code_actions || show_runnables || show_breakpoints {
20107            em_width * 3.0
20108        } else if show_git_gutter && show_line_numbers {
20109            em_width * 2.0
20110        } else if show_git_gutter || show_line_numbers {
20111            em_width
20112        } else {
20113            px(0.)
20114        };
20115
20116        let shows_folds = is_singleton && gutter_settings.folds;
20117
20118        let right_padding = if shows_folds && show_line_numbers {
20119            em_width * 4.0
20120        } else if shows_folds || (!is_singleton && show_line_numbers) {
20121            em_width * 3.0
20122        } else if show_line_numbers {
20123            em_width
20124        } else {
20125            px(0.)
20126        };
20127
20128        Some(GutterDimensions {
20129            left_padding,
20130            right_padding,
20131            width: line_gutter_width + left_padding + right_padding,
20132            margin: -descent,
20133            git_blame_entries_width,
20134        })
20135    }
20136
20137    pub fn render_crease_toggle(
20138        &self,
20139        buffer_row: MultiBufferRow,
20140        row_contains_cursor: bool,
20141        editor: Entity<Editor>,
20142        window: &mut Window,
20143        cx: &mut App,
20144    ) -> Option<AnyElement> {
20145        let folded = self.is_line_folded(buffer_row);
20146        let mut is_foldable = false;
20147
20148        if let Some(crease) = self
20149            .crease_snapshot
20150            .query_row(buffer_row, &self.buffer_snapshot)
20151        {
20152            is_foldable = true;
20153            match crease {
20154                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20155                    if let Some(render_toggle) = render_toggle {
20156                        let toggle_callback =
20157                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20158                                if folded {
20159                                    editor.update(cx, |editor, cx| {
20160                                        editor.fold_at(buffer_row, window, cx)
20161                                    });
20162                                } else {
20163                                    editor.update(cx, |editor, cx| {
20164                                        editor.unfold_at(buffer_row, window, cx)
20165                                    });
20166                                }
20167                            });
20168                        return Some((render_toggle)(
20169                            buffer_row,
20170                            folded,
20171                            toggle_callback,
20172                            window,
20173                            cx,
20174                        ));
20175                    }
20176                }
20177            }
20178        }
20179
20180        is_foldable |= self.starts_indent(buffer_row);
20181
20182        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20183            Some(
20184                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20185                    .toggle_state(folded)
20186                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20187                        if folded {
20188                            this.unfold_at(buffer_row, window, cx);
20189                        } else {
20190                            this.fold_at(buffer_row, window, cx);
20191                        }
20192                    }))
20193                    .into_any_element(),
20194            )
20195        } else {
20196            None
20197        }
20198    }
20199
20200    pub fn render_crease_trailer(
20201        &self,
20202        buffer_row: MultiBufferRow,
20203        window: &mut Window,
20204        cx: &mut App,
20205    ) -> Option<AnyElement> {
20206        let folded = self.is_line_folded(buffer_row);
20207        if let Crease::Inline { render_trailer, .. } = self
20208            .crease_snapshot
20209            .query_row(buffer_row, &self.buffer_snapshot)?
20210        {
20211            let render_trailer = render_trailer.as_ref()?;
20212            Some(render_trailer(buffer_row, folded, window, cx))
20213        } else {
20214            None
20215        }
20216    }
20217}
20218
20219impl Deref for EditorSnapshot {
20220    type Target = DisplaySnapshot;
20221
20222    fn deref(&self) -> &Self::Target {
20223        &self.display_snapshot
20224    }
20225}
20226
20227#[derive(Clone, Debug, PartialEq, Eq)]
20228pub enum EditorEvent {
20229    InputIgnored {
20230        text: Arc<str>,
20231    },
20232    InputHandled {
20233        utf16_range_to_replace: Option<Range<isize>>,
20234        text: Arc<str>,
20235    },
20236    ExcerptsAdded {
20237        buffer: Entity<Buffer>,
20238        predecessor: ExcerptId,
20239        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20240    },
20241    ExcerptsRemoved {
20242        ids: Vec<ExcerptId>,
20243        removed_buffer_ids: Vec<BufferId>,
20244    },
20245    BufferFoldToggled {
20246        ids: Vec<ExcerptId>,
20247        folded: bool,
20248    },
20249    ExcerptsEdited {
20250        ids: Vec<ExcerptId>,
20251    },
20252    ExcerptsExpanded {
20253        ids: Vec<ExcerptId>,
20254    },
20255    BufferEdited,
20256    Edited {
20257        transaction_id: clock::Lamport,
20258    },
20259    Reparsed(BufferId),
20260    Focused,
20261    FocusedIn,
20262    Blurred,
20263    DirtyChanged,
20264    Saved,
20265    TitleChanged,
20266    DiffBaseChanged,
20267    SelectionsChanged {
20268        local: bool,
20269    },
20270    ScrollPositionChanged {
20271        local: bool,
20272        autoscroll: bool,
20273    },
20274    Closed,
20275    TransactionUndone {
20276        transaction_id: clock::Lamport,
20277    },
20278    TransactionBegun {
20279        transaction_id: clock::Lamport,
20280    },
20281    Reloaded,
20282    CursorShapeChanged,
20283    PushedToNavHistory {
20284        anchor: Anchor,
20285        is_deactivate: bool,
20286    },
20287}
20288
20289impl EventEmitter<EditorEvent> for Editor {}
20290
20291impl Focusable for Editor {
20292    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20293        self.focus_handle.clone()
20294    }
20295}
20296
20297impl Render for Editor {
20298    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20299        let settings = ThemeSettings::get_global(cx);
20300
20301        let mut text_style = match self.mode {
20302            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20303                color: cx.theme().colors().editor_foreground,
20304                font_family: settings.ui_font.family.clone(),
20305                font_features: settings.ui_font.features.clone(),
20306                font_fallbacks: settings.ui_font.fallbacks.clone(),
20307                font_size: rems(0.875).into(),
20308                font_weight: settings.ui_font.weight,
20309                line_height: relative(settings.buffer_line_height.value()),
20310                ..Default::default()
20311            },
20312            EditorMode::Full { .. } => TextStyle {
20313                color: cx.theme().colors().editor_foreground,
20314                font_family: settings.buffer_font.family.clone(),
20315                font_features: settings.buffer_font.features.clone(),
20316                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20317                font_size: settings.buffer_font_size(cx).into(),
20318                font_weight: settings.buffer_font.weight,
20319                line_height: relative(settings.buffer_line_height.value()),
20320                ..Default::default()
20321            },
20322        };
20323        if let Some(text_style_refinement) = &self.text_style_refinement {
20324            text_style.refine(text_style_refinement)
20325        }
20326
20327        let background = match self.mode {
20328            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20329            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20330            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20331        };
20332
20333        EditorElement::new(
20334            &cx.entity(),
20335            EditorStyle {
20336                background,
20337                horizontal_padding: Pixels::default(),
20338                local_player: cx.theme().players().local(),
20339                text: text_style,
20340                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20341                syntax: cx.theme().syntax().clone(),
20342                status: cx.theme().status().clone(),
20343                inlay_hints_style: make_inlay_hints_style(cx),
20344                inline_completion_styles: make_suggestion_styles(cx),
20345                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20346            },
20347        )
20348    }
20349}
20350
20351impl EntityInputHandler for Editor {
20352    fn text_for_range(
20353        &mut self,
20354        range_utf16: Range<usize>,
20355        adjusted_range: &mut Option<Range<usize>>,
20356        _: &mut Window,
20357        cx: &mut Context<Self>,
20358    ) -> Option<String> {
20359        let snapshot = self.buffer.read(cx).read(cx);
20360        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20361        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20362        if (start.0..end.0) != range_utf16 {
20363            adjusted_range.replace(start.0..end.0);
20364        }
20365        Some(snapshot.text_for_range(start..end).collect())
20366    }
20367
20368    fn selected_text_range(
20369        &mut self,
20370        ignore_disabled_input: bool,
20371        _: &mut Window,
20372        cx: &mut Context<Self>,
20373    ) -> Option<UTF16Selection> {
20374        // Prevent the IME menu from appearing when holding down an alphabetic key
20375        // while input is disabled.
20376        if !ignore_disabled_input && !self.input_enabled {
20377            return None;
20378        }
20379
20380        let selection = self.selections.newest::<OffsetUtf16>(cx);
20381        let range = selection.range();
20382
20383        Some(UTF16Selection {
20384            range: range.start.0..range.end.0,
20385            reversed: selection.reversed,
20386        })
20387    }
20388
20389    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20390        let snapshot = self.buffer.read(cx).read(cx);
20391        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20392        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20393    }
20394
20395    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20396        self.clear_highlights::<InputComposition>(cx);
20397        self.ime_transaction.take();
20398    }
20399
20400    fn replace_text_in_range(
20401        &mut self,
20402        range_utf16: Option<Range<usize>>,
20403        text: &str,
20404        window: &mut Window,
20405        cx: &mut Context<Self>,
20406    ) {
20407        if !self.input_enabled {
20408            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20409            return;
20410        }
20411
20412        self.transact(window, cx, |this, window, cx| {
20413            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20414                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20415                Some(this.selection_replacement_ranges(range_utf16, cx))
20416            } else {
20417                this.marked_text_ranges(cx)
20418            };
20419
20420            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20421                let newest_selection_id = this.selections.newest_anchor().id;
20422                this.selections
20423                    .all::<OffsetUtf16>(cx)
20424                    .iter()
20425                    .zip(ranges_to_replace.iter())
20426                    .find_map(|(selection, range)| {
20427                        if selection.id == newest_selection_id {
20428                            Some(
20429                                (range.start.0 as isize - selection.head().0 as isize)
20430                                    ..(range.end.0 as isize - selection.head().0 as isize),
20431                            )
20432                        } else {
20433                            None
20434                        }
20435                    })
20436            });
20437
20438            cx.emit(EditorEvent::InputHandled {
20439                utf16_range_to_replace: range_to_replace,
20440                text: text.into(),
20441            });
20442
20443            if let Some(new_selected_ranges) = new_selected_ranges {
20444                this.change_selections(None, window, cx, |selections| {
20445                    selections.select_ranges(new_selected_ranges)
20446                });
20447                this.backspace(&Default::default(), window, cx);
20448            }
20449
20450            this.handle_input(text, window, cx);
20451        });
20452
20453        if let Some(transaction) = self.ime_transaction {
20454            self.buffer.update(cx, |buffer, cx| {
20455                buffer.group_until_transaction(transaction, cx);
20456            });
20457        }
20458
20459        self.unmark_text(window, cx);
20460    }
20461
20462    fn replace_and_mark_text_in_range(
20463        &mut self,
20464        range_utf16: Option<Range<usize>>,
20465        text: &str,
20466        new_selected_range_utf16: Option<Range<usize>>,
20467        window: &mut Window,
20468        cx: &mut Context<Self>,
20469    ) {
20470        if !self.input_enabled {
20471            return;
20472        }
20473
20474        let transaction = self.transact(window, cx, |this, window, cx| {
20475            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20476                let snapshot = this.buffer.read(cx).read(cx);
20477                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20478                    for marked_range in &mut marked_ranges {
20479                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20480                        marked_range.start.0 += relative_range_utf16.start;
20481                        marked_range.start =
20482                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20483                        marked_range.end =
20484                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20485                    }
20486                }
20487                Some(marked_ranges)
20488            } else if let Some(range_utf16) = range_utf16 {
20489                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20490                Some(this.selection_replacement_ranges(range_utf16, cx))
20491            } else {
20492                None
20493            };
20494
20495            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20496                let newest_selection_id = this.selections.newest_anchor().id;
20497                this.selections
20498                    .all::<OffsetUtf16>(cx)
20499                    .iter()
20500                    .zip(ranges_to_replace.iter())
20501                    .find_map(|(selection, range)| {
20502                        if selection.id == newest_selection_id {
20503                            Some(
20504                                (range.start.0 as isize - selection.head().0 as isize)
20505                                    ..(range.end.0 as isize - selection.head().0 as isize),
20506                            )
20507                        } else {
20508                            None
20509                        }
20510                    })
20511            });
20512
20513            cx.emit(EditorEvent::InputHandled {
20514                utf16_range_to_replace: range_to_replace,
20515                text: text.into(),
20516            });
20517
20518            if let Some(ranges) = ranges_to_replace {
20519                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20520            }
20521
20522            let marked_ranges = {
20523                let snapshot = this.buffer.read(cx).read(cx);
20524                this.selections
20525                    .disjoint_anchors()
20526                    .iter()
20527                    .map(|selection| {
20528                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20529                    })
20530                    .collect::<Vec<_>>()
20531            };
20532
20533            if text.is_empty() {
20534                this.unmark_text(window, cx);
20535            } else {
20536                this.highlight_text::<InputComposition>(
20537                    marked_ranges.clone(),
20538                    HighlightStyle {
20539                        underline: Some(UnderlineStyle {
20540                            thickness: px(1.),
20541                            color: None,
20542                            wavy: false,
20543                        }),
20544                        ..Default::default()
20545                    },
20546                    cx,
20547                );
20548            }
20549
20550            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20551            let use_autoclose = this.use_autoclose;
20552            let use_auto_surround = this.use_auto_surround;
20553            this.set_use_autoclose(false);
20554            this.set_use_auto_surround(false);
20555            this.handle_input(text, window, cx);
20556            this.set_use_autoclose(use_autoclose);
20557            this.set_use_auto_surround(use_auto_surround);
20558
20559            if let Some(new_selected_range) = new_selected_range_utf16 {
20560                let snapshot = this.buffer.read(cx).read(cx);
20561                let new_selected_ranges = marked_ranges
20562                    .into_iter()
20563                    .map(|marked_range| {
20564                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20565                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20566                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20567                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20568                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20569                    })
20570                    .collect::<Vec<_>>();
20571
20572                drop(snapshot);
20573                this.change_selections(None, window, cx, |selections| {
20574                    selections.select_ranges(new_selected_ranges)
20575                });
20576            }
20577        });
20578
20579        self.ime_transaction = self.ime_transaction.or(transaction);
20580        if let Some(transaction) = self.ime_transaction {
20581            self.buffer.update(cx, |buffer, cx| {
20582                buffer.group_until_transaction(transaction, cx);
20583            });
20584        }
20585
20586        if self.text_highlights::<InputComposition>(cx).is_none() {
20587            self.ime_transaction.take();
20588        }
20589    }
20590
20591    fn bounds_for_range(
20592        &mut self,
20593        range_utf16: Range<usize>,
20594        element_bounds: gpui::Bounds<Pixels>,
20595        window: &mut Window,
20596        cx: &mut Context<Self>,
20597    ) -> Option<gpui::Bounds<Pixels>> {
20598        let text_layout_details = self.text_layout_details(window);
20599        let gpui::Size {
20600            width: em_width,
20601            height: line_height,
20602        } = self.character_size(window);
20603
20604        let snapshot = self.snapshot(window, cx);
20605        let scroll_position = snapshot.scroll_position();
20606        let scroll_left = scroll_position.x * em_width;
20607
20608        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20609        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20610            + self.gutter_dimensions.width
20611            + self.gutter_dimensions.margin;
20612        let y = line_height * (start.row().as_f32() - scroll_position.y);
20613
20614        Some(Bounds {
20615            origin: element_bounds.origin + point(x, y),
20616            size: size(em_width, line_height),
20617        })
20618    }
20619
20620    fn character_index_for_point(
20621        &mut self,
20622        point: gpui::Point<Pixels>,
20623        _window: &mut Window,
20624        _cx: &mut Context<Self>,
20625    ) -> Option<usize> {
20626        let position_map = self.last_position_map.as_ref()?;
20627        if !position_map.text_hitbox.contains(&point) {
20628            return None;
20629        }
20630        let display_point = position_map.point_for_position(point).previous_valid;
20631        let anchor = position_map
20632            .snapshot
20633            .display_point_to_anchor(display_point, Bias::Left);
20634        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20635        Some(utf16_offset.0)
20636    }
20637}
20638
20639trait SelectionExt {
20640    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20641    fn spanned_rows(
20642        &self,
20643        include_end_if_at_line_start: bool,
20644        map: &DisplaySnapshot,
20645    ) -> Range<MultiBufferRow>;
20646}
20647
20648impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20649    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20650        let start = self
20651            .start
20652            .to_point(&map.buffer_snapshot)
20653            .to_display_point(map);
20654        let end = self
20655            .end
20656            .to_point(&map.buffer_snapshot)
20657            .to_display_point(map);
20658        if self.reversed {
20659            end..start
20660        } else {
20661            start..end
20662        }
20663    }
20664
20665    fn spanned_rows(
20666        &self,
20667        include_end_if_at_line_start: bool,
20668        map: &DisplaySnapshot,
20669    ) -> Range<MultiBufferRow> {
20670        let start = self.start.to_point(&map.buffer_snapshot);
20671        let mut end = self.end.to_point(&map.buffer_snapshot);
20672        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20673            end.row -= 1;
20674        }
20675
20676        let buffer_start = map.prev_line_boundary(start).0;
20677        let buffer_end = map.next_line_boundary(end).0;
20678        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20679    }
20680}
20681
20682impl<T: InvalidationRegion> InvalidationStack<T> {
20683    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20684    where
20685        S: Clone + ToOffset,
20686    {
20687        while let Some(region) = self.last() {
20688            let all_selections_inside_invalidation_ranges =
20689                if selections.len() == region.ranges().len() {
20690                    selections
20691                        .iter()
20692                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20693                        .all(|(selection, invalidation_range)| {
20694                            let head = selection.head().to_offset(buffer);
20695                            invalidation_range.start <= head && invalidation_range.end >= head
20696                        })
20697                } else {
20698                    false
20699                };
20700
20701            if all_selections_inside_invalidation_ranges {
20702                break;
20703            } else {
20704                self.pop();
20705            }
20706        }
20707    }
20708}
20709
20710impl<T> Default for InvalidationStack<T> {
20711    fn default() -> Self {
20712        Self(Default::default())
20713    }
20714}
20715
20716impl<T> Deref for InvalidationStack<T> {
20717    type Target = Vec<T>;
20718
20719    fn deref(&self) -> &Self::Target {
20720        &self.0
20721    }
20722}
20723
20724impl<T> DerefMut for InvalidationStack<T> {
20725    fn deref_mut(&mut self) -> &mut Self::Target {
20726        &mut self.0
20727    }
20728}
20729
20730impl InvalidationRegion for SnippetState {
20731    fn ranges(&self) -> &[Range<Anchor>] {
20732        &self.ranges[self.active_index]
20733    }
20734}
20735
20736fn inline_completion_edit_text(
20737    current_snapshot: &BufferSnapshot,
20738    edits: &[(Range<Anchor>, String)],
20739    edit_preview: &EditPreview,
20740    include_deletions: bool,
20741    cx: &App,
20742) -> HighlightedText {
20743    let edits = edits
20744        .iter()
20745        .map(|(anchor, text)| {
20746            (
20747                anchor.start.text_anchor..anchor.end.text_anchor,
20748                text.clone(),
20749            )
20750        })
20751        .collect::<Vec<_>>();
20752
20753    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20754}
20755
20756pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20757    match severity {
20758        DiagnosticSeverity::ERROR => colors.error,
20759        DiagnosticSeverity::WARNING => colors.warning,
20760        DiagnosticSeverity::INFORMATION => colors.info,
20761        DiagnosticSeverity::HINT => colors.info,
20762        _ => colors.ignored,
20763    }
20764}
20765
20766pub fn styled_runs_for_code_label<'a>(
20767    label: &'a CodeLabel,
20768    syntax_theme: &'a theme::SyntaxTheme,
20769) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20770    let fade_out = HighlightStyle {
20771        fade_out: Some(0.35),
20772        ..Default::default()
20773    };
20774
20775    let mut prev_end = label.filter_range.end;
20776    label
20777        .runs
20778        .iter()
20779        .enumerate()
20780        .flat_map(move |(ix, (range, highlight_id))| {
20781            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20782                style
20783            } else {
20784                return Default::default();
20785            };
20786            let mut muted_style = style;
20787            muted_style.highlight(fade_out);
20788
20789            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20790            if range.start >= label.filter_range.end {
20791                if range.start > prev_end {
20792                    runs.push((prev_end..range.start, fade_out));
20793                }
20794                runs.push((range.clone(), muted_style));
20795            } else if range.end <= label.filter_range.end {
20796                runs.push((range.clone(), style));
20797            } else {
20798                runs.push((range.start..label.filter_range.end, style));
20799                runs.push((label.filter_range.end..range.end, muted_style));
20800            }
20801            prev_end = cmp::max(prev_end, range.end);
20802
20803            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20804                runs.push((prev_end..label.text.len(), fade_out));
20805            }
20806
20807            runs
20808        })
20809}
20810
20811pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20812    let mut prev_index = 0;
20813    let mut prev_codepoint: Option<char> = None;
20814    text.char_indices()
20815        .chain([(text.len(), '\0')])
20816        .filter_map(move |(index, codepoint)| {
20817            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20818            let is_boundary = index == text.len()
20819                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20820                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20821            if is_boundary {
20822                let chunk = &text[prev_index..index];
20823                prev_index = index;
20824                Some(chunk)
20825            } else {
20826                None
20827            }
20828        })
20829}
20830
20831pub trait RangeToAnchorExt: Sized {
20832    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20833
20834    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20835        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20836        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20837    }
20838}
20839
20840impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20841    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20842        let start_offset = self.start.to_offset(snapshot);
20843        let end_offset = self.end.to_offset(snapshot);
20844        if start_offset == end_offset {
20845            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20846        } else {
20847            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20848        }
20849    }
20850}
20851
20852pub trait RowExt {
20853    fn as_f32(&self) -> f32;
20854
20855    fn next_row(&self) -> Self;
20856
20857    fn previous_row(&self) -> Self;
20858
20859    fn minus(&self, other: Self) -> u32;
20860}
20861
20862impl RowExt for DisplayRow {
20863    fn as_f32(&self) -> f32 {
20864        self.0 as f32
20865    }
20866
20867    fn next_row(&self) -> Self {
20868        Self(self.0 + 1)
20869    }
20870
20871    fn previous_row(&self) -> Self {
20872        Self(self.0.saturating_sub(1))
20873    }
20874
20875    fn minus(&self, other: Self) -> u32 {
20876        self.0 - other.0
20877    }
20878}
20879
20880impl RowExt for MultiBufferRow {
20881    fn as_f32(&self) -> f32 {
20882        self.0 as f32
20883    }
20884
20885    fn next_row(&self) -> Self {
20886        Self(self.0 + 1)
20887    }
20888
20889    fn previous_row(&self) -> Self {
20890        Self(self.0.saturating_sub(1))
20891    }
20892
20893    fn minus(&self, other: Self) -> u32 {
20894        self.0 - other.0
20895    }
20896}
20897
20898trait RowRangeExt {
20899    type Row;
20900
20901    fn len(&self) -> usize;
20902
20903    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20904}
20905
20906impl RowRangeExt for Range<MultiBufferRow> {
20907    type Row = MultiBufferRow;
20908
20909    fn len(&self) -> usize {
20910        (self.end.0 - self.start.0) as usize
20911    }
20912
20913    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20914        (self.start.0..self.end.0).map(MultiBufferRow)
20915    }
20916}
20917
20918impl RowRangeExt for Range<DisplayRow> {
20919    type Row = DisplayRow;
20920
20921    fn len(&self) -> usize {
20922        (self.end.0 - self.start.0) as usize
20923    }
20924
20925    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20926        (self.start.0..self.end.0).map(DisplayRow)
20927    }
20928}
20929
20930/// If select range has more than one line, we
20931/// just point the cursor to range.start.
20932fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20933    if range.start.row == range.end.row {
20934        range
20935    } else {
20936        range.start..range.start
20937    }
20938}
20939pub struct KillRing(ClipboardItem);
20940impl Global for KillRing {}
20941
20942const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20943
20944enum BreakpointPromptEditAction {
20945    Log,
20946    Condition,
20947    HitCondition,
20948}
20949
20950struct BreakpointPromptEditor {
20951    pub(crate) prompt: Entity<Editor>,
20952    editor: WeakEntity<Editor>,
20953    breakpoint_anchor: Anchor,
20954    breakpoint: Breakpoint,
20955    edit_action: BreakpointPromptEditAction,
20956    block_ids: HashSet<CustomBlockId>,
20957    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20958    _subscriptions: Vec<Subscription>,
20959}
20960
20961impl BreakpointPromptEditor {
20962    const MAX_LINES: u8 = 4;
20963
20964    fn new(
20965        editor: WeakEntity<Editor>,
20966        breakpoint_anchor: Anchor,
20967        breakpoint: Breakpoint,
20968        edit_action: BreakpointPromptEditAction,
20969        window: &mut Window,
20970        cx: &mut Context<Self>,
20971    ) -> Self {
20972        let base_text = match edit_action {
20973            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20974            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20975            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20976        }
20977        .map(|msg| msg.to_string())
20978        .unwrap_or_default();
20979
20980        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20981        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20982
20983        let prompt = cx.new(|cx| {
20984            let mut prompt = Editor::new(
20985                EditorMode::AutoHeight {
20986                    max_lines: Self::MAX_LINES as usize,
20987                },
20988                buffer,
20989                None,
20990                window,
20991                cx,
20992            );
20993            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20994            prompt.set_show_cursor_when_unfocused(false, cx);
20995            prompt.set_placeholder_text(
20996                match edit_action {
20997                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20998                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20999                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21000                },
21001                cx,
21002            );
21003
21004            prompt
21005        });
21006
21007        Self {
21008            prompt,
21009            editor,
21010            breakpoint_anchor,
21011            breakpoint,
21012            edit_action,
21013            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21014            block_ids: Default::default(),
21015            _subscriptions: vec![],
21016        }
21017    }
21018
21019    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21020        self.block_ids.extend(block_ids)
21021    }
21022
21023    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21024        if let Some(editor) = self.editor.upgrade() {
21025            let message = self
21026                .prompt
21027                .read(cx)
21028                .buffer
21029                .read(cx)
21030                .as_singleton()
21031                .expect("A multi buffer in breakpoint prompt isn't possible")
21032                .read(cx)
21033                .as_rope()
21034                .to_string();
21035
21036            editor.update(cx, |editor, cx| {
21037                editor.edit_breakpoint_at_anchor(
21038                    self.breakpoint_anchor,
21039                    self.breakpoint.clone(),
21040                    match self.edit_action {
21041                        BreakpointPromptEditAction::Log => {
21042                            BreakpointEditAction::EditLogMessage(message.into())
21043                        }
21044                        BreakpointPromptEditAction::Condition => {
21045                            BreakpointEditAction::EditCondition(message.into())
21046                        }
21047                        BreakpointPromptEditAction::HitCondition => {
21048                            BreakpointEditAction::EditHitCondition(message.into())
21049                        }
21050                    },
21051                    cx,
21052                );
21053
21054                editor.remove_blocks(self.block_ids.clone(), None, cx);
21055                cx.focus_self(window);
21056            });
21057        }
21058    }
21059
21060    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21061        self.editor
21062            .update(cx, |editor, cx| {
21063                editor.remove_blocks(self.block_ids.clone(), None, cx);
21064                window.focus(&editor.focus_handle);
21065            })
21066            .log_err();
21067    }
21068
21069    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21070        let settings = ThemeSettings::get_global(cx);
21071        let text_style = TextStyle {
21072            color: if self.prompt.read(cx).read_only(cx) {
21073                cx.theme().colors().text_disabled
21074            } else {
21075                cx.theme().colors().text
21076            },
21077            font_family: settings.buffer_font.family.clone(),
21078            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21079            font_size: settings.buffer_font_size(cx).into(),
21080            font_weight: settings.buffer_font.weight,
21081            line_height: relative(settings.buffer_line_height.value()),
21082            ..Default::default()
21083        };
21084        EditorElement::new(
21085            &self.prompt,
21086            EditorStyle {
21087                background: cx.theme().colors().editor_background,
21088                local_player: cx.theme().players().local(),
21089                text: text_style,
21090                ..Default::default()
21091            },
21092        )
21093    }
21094}
21095
21096impl Render for BreakpointPromptEditor {
21097    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21098        let gutter_dimensions = *self.gutter_dimensions.lock();
21099        h_flex()
21100            .key_context("Editor")
21101            .bg(cx.theme().colors().editor_background)
21102            .border_y_1()
21103            .border_color(cx.theme().status().info_border)
21104            .size_full()
21105            .py(window.line_height() / 2.5)
21106            .on_action(cx.listener(Self::confirm))
21107            .on_action(cx.listener(Self::cancel))
21108            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21109            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21110    }
21111}
21112
21113impl Focusable for BreakpointPromptEditor {
21114    fn focus_handle(&self, cx: &App) -> FocusHandle {
21115        self.prompt.focus_handle(cx)
21116    }
21117}
21118
21119fn all_edits_insertions_or_deletions(
21120    edits: &Vec<(Range<Anchor>, String)>,
21121    snapshot: &MultiBufferSnapshot,
21122) -> bool {
21123    let mut all_insertions = true;
21124    let mut all_deletions = true;
21125
21126    for (range, new_text) in edits.iter() {
21127        let range_is_empty = range.to_offset(&snapshot).is_empty();
21128        let text_is_empty = new_text.is_empty();
21129
21130        if range_is_empty != text_is_empty {
21131            if range_is_empty {
21132                all_deletions = false;
21133            } else {
21134                all_insertions = false;
21135            }
21136        } else {
21137            return false;
21138        }
21139
21140        if !all_insertions && !all_deletions {
21141            return false;
21142        }
21143    }
21144    all_insertions || all_deletions
21145}
21146
21147struct MissingEditPredictionKeybindingTooltip;
21148
21149impl Render for MissingEditPredictionKeybindingTooltip {
21150    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21151        ui::tooltip_container(window, cx, |container, _, cx| {
21152            container
21153                .flex_shrink_0()
21154                .max_w_80()
21155                .min_h(rems_from_px(124.))
21156                .justify_between()
21157                .child(
21158                    v_flex()
21159                        .flex_1()
21160                        .text_ui_sm(cx)
21161                        .child(Label::new("Conflict with Accept Keybinding"))
21162                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21163                )
21164                .child(
21165                    h_flex()
21166                        .pb_1()
21167                        .gap_1()
21168                        .items_end()
21169                        .w_full()
21170                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21171                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21172                        }))
21173                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21174                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21175                        })),
21176                )
21177        })
21178    }
21179}
21180
21181#[derive(Debug, Clone, Copy, PartialEq)]
21182pub struct LineHighlight {
21183    pub background: Background,
21184    pub border: Option<gpui::Hsla>,
21185    pub include_gutter: bool,
21186    pub type_id: Option<TypeId>,
21187}
21188
21189fn render_diff_hunk_controls(
21190    row: u32,
21191    status: &DiffHunkStatus,
21192    hunk_range: Range<Anchor>,
21193    is_created_file: bool,
21194    line_height: Pixels,
21195    editor: &Entity<Editor>,
21196    _window: &mut Window,
21197    cx: &mut App,
21198) -> AnyElement {
21199    h_flex()
21200        .h(line_height)
21201        .mr_1()
21202        .gap_1()
21203        .px_0p5()
21204        .pb_1()
21205        .border_x_1()
21206        .border_b_1()
21207        .border_color(cx.theme().colors().border_variant)
21208        .rounded_b_lg()
21209        .bg(cx.theme().colors().editor_background)
21210        .gap_1()
21211        .occlude()
21212        .shadow_md()
21213        .child(if status.has_secondary_hunk() {
21214            Button::new(("stage", row as u64), "Stage")
21215                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21216                .tooltip({
21217                    let focus_handle = editor.focus_handle(cx);
21218                    move |window, cx| {
21219                        Tooltip::for_action_in(
21220                            "Stage Hunk",
21221                            &::git::ToggleStaged,
21222                            &focus_handle,
21223                            window,
21224                            cx,
21225                        )
21226                    }
21227                })
21228                .on_click({
21229                    let editor = editor.clone();
21230                    move |_event, _window, cx| {
21231                        editor.update(cx, |editor, cx| {
21232                            editor.stage_or_unstage_diff_hunks(
21233                                true,
21234                                vec![hunk_range.start..hunk_range.start],
21235                                cx,
21236                            );
21237                        });
21238                    }
21239                })
21240        } else {
21241            Button::new(("unstage", row as u64), "Unstage")
21242                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21243                .tooltip({
21244                    let focus_handle = editor.focus_handle(cx);
21245                    move |window, cx| {
21246                        Tooltip::for_action_in(
21247                            "Unstage Hunk",
21248                            &::git::ToggleStaged,
21249                            &focus_handle,
21250                            window,
21251                            cx,
21252                        )
21253                    }
21254                })
21255                .on_click({
21256                    let editor = editor.clone();
21257                    move |_event, _window, cx| {
21258                        editor.update(cx, |editor, cx| {
21259                            editor.stage_or_unstage_diff_hunks(
21260                                false,
21261                                vec![hunk_range.start..hunk_range.start],
21262                                cx,
21263                            );
21264                        });
21265                    }
21266                })
21267        })
21268        .child(
21269            Button::new(("restore", row as u64), "Restore")
21270                .tooltip({
21271                    let focus_handle = editor.focus_handle(cx);
21272                    move |window, cx| {
21273                        Tooltip::for_action_in(
21274                            "Restore Hunk",
21275                            &::git::Restore,
21276                            &focus_handle,
21277                            window,
21278                            cx,
21279                        )
21280                    }
21281                })
21282                .on_click({
21283                    let editor = editor.clone();
21284                    move |_event, window, cx| {
21285                        editor.update(cx, |editor, cx| {
21286                            let snapshot = editor.snapshot(window, cx);
21287                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21288                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21289                        });
21290                    }
21291                })
21292                .disabled(is_created_file),
21293        )
21294        .when(
21295            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21296            |el| {
21297                el.child(
21298                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21299                        .shape(IconButtonShape::Square)
21300                        .icon_size(IconSize::Small)
21301                        // .disabled(!has_multiple_hunks)
21302                        .tooltip({
21303                            let focus_handle = editor.focus_handle(cx);
21304                            move |window, cx| {
21305                                Tooltip::for_action_in(
21306                                    "Next Hunk",
21307                                    &GoToHunk,
21308                                    &focus_handle,
21309                                    window,
21310                                    cx,
21311                                )
21312                            }
21313                        })
21314                        .on_click({
21315                            let editor = editor.clone();
21316                            move |_event, window, cx| {
21317                                editor.update(cx, |editor, cx| {
21318                                    let snapshot = editor.snapshot(window, cx);
21319                                    let position =
21320                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21321                                    editor.go_to_hunk_before_or_after_position(
21322                                        &snapshot,
21323                                        position,
21324                                        Direction::Next,
21325                                        window,
21326                                        cx,
21327                                    );
21328                                    editor.expand_selected_diff_hunks(cx);
21329                                });
21330                            }
21331                        }),
21332                )
21333                .child(
21334                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21335                        .shape(IconButtonShape::Square)
21336                        .icon_size(IconSize::Small)
21337                        // .disabled(!has_multiple_hunks)
21338                        .tooltip({
21339                            let focus_handle = editor.focus_handle(cx);
21340                            move |window, cx| {
21341                                Tooltip::for_action_in(
21342                                    "Previous Hunk",
21343                                    &GoToPreviousHunk,
21344                                    &focus_handle,
21345                                    window,
21346                                    cx,
21347                                )
21348                            }
21349                        })
21350                        .on_click({
21351                            let editor = editor.clone();
21352                            move |_event, window, cx| {
21353                                editor.update(cx, |editor, cx| {
21354                                    let snapshot = editor.snapshot(window, cx);
21355                                    let point =
21356                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21357                                    editor.go_to_hunk_before_or_after_position(
21358                                        &snapshot,
21359                                        point,
21360                                        Direction::Prev,
21361                                        window,
21362                                        cx,
21363                                    );
21364                                    editor.expand_selected_diff_hunks(cx);
21365                                });
21366                            }
21367                        }),
21368                )
21369            },
21370        )
21371        .into_any_element()
21372}